Count BST Order Violations
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given a binary tree of integers encoded as a compact breadth-first array level_order, implement count_invalid_bst_nodes(level_order) to return how many nodes break the Binary Search Tree (BST) ordering invariant.
In a strict BST, every node holding value v constrains all descendants beneath it:
- Every node anywhere in its left subtree must have value strictly smaller than v (< v).
- Every node anywhere in its right subtree must have value strictly larger than v (> v).
Equal values violate strict ordering. A node is counted as invalid whenever its value falls outside the allowed open interval (low, high) established by all of its ancestors:
- Count per violating node: even if a node breaks bounds from several ancestors at once, it contributes 1 to the answer.
- The root has no ancestors and therefore never violates an ancestor constraint.
- Traversal continues below invalid nodes, keeping all tighter bounds from higher ancestors intact.
Level-order encoding
- An empty list
[]or[None]represents an empty tree with0nodes. level_order[0]is the root's value, and each non-Nonenode (in breadth-first order) consumes the next two list positions for its left child and right child.Noneentries denote missing children and do not consume child slots; trailingNoneentries after the final present node may be omitted.
Examples
Example 1
Input: level_order = [8, 3, 6, None, None, 4, 11]
Tree:
8
/ \
3 6
/ \
4 11
Output: 2
Root 8 and left child 3 (3 < 8) are valid. Right child 6 sits in the right subtree of 8 where values must exceed 8, so 6 is invalid. Beneath 6, left child 4 must satisfy both > 8 and < 6 (impossible, so 4 is also invalid), whereas right child 11 satisfies both > 8 and > 6 and is valid.
Example 2
Input: level_order = [4, -2, 9, -5, 1, None, 14]
Output: 0
Every node lies strictly within the range required by all of its ancestors (-5 < -2 < 1 < 4 < 9 < 14).
Example 3
Input: level_order = [12, 7, 18, 3, 12, 9, 25]
Tree:
12
/ \
7 18
/ \ / \
3 12 9 25
Output: 2
Two grandchildren violate root 12 despite satisfying their immediate parents: the second 12 (right child of 7) lies in the left subtree of 12 where values must be strictly < 12, and 9 (left child of 18) lies in the right subtree of 12 where values must be strictly > 12.
Constraints
0 <= len(level_order) <= 2 * 10^5(at most10^5non-null nodes).- Present node values are integers in
[-10^9, 10^9]. - Your algorithm should run in
O(n)time and handle skewed trees of depth up to10^5.
Step-by-step walkthrough
Understand the BST rule and the level-order input
In a strict Binary Search Tree (BST), every node holding value
vimposes an ordering rule on all nodes below it: - Every node anywhere in its left subtree must satisfyvalue < v. - Every node anywhere in its right subtree must satisfyvalue > v.We want to count how many nodes fail at least one ancestor's rule. Notice three details from the specification and examples: 1. Check all ancestors, not just the parent: In Example 3 (
[12, 7, 18, 3, 12, 9, 25]), node9is smaller than its parent18, yet9sits inside the right subtree of root12where every value must exceed12. 2. Count violating descendants once: Even if a node fails bounds imposed by three different ancestors, that node still adds1to the count (and the root itself has zero ancestors, so it is always valid). 3. Strict inequality: Equal values (<=or>=) count as invalid, such as the duplicate12inside the left subtree of root12in Example 3.The judge passes the tree in compact level-order format:
level_order[0]is the root, and each existing (non-None) node in breadth-first order owns the next two list slots (left child, right child). Missing nodes (None) do not get child slots of their own:level_order = [8, 3, 6, None, None, 4, 11] index: 0 1 2 3 4 5 6 8 (slot 0 -> children at slots 1, 2) / \ 3 6 (3 owns slots 3, 4 = None, None; 6 owns slots 5, 6 = 4, 11) / \ 4 11 (6 <= 8 and 4 <= 8 violate ancestor 8 -> 2 invalid nodes)See why checking ancestors one by one is too slow
A direct brute-force approach checks every node by walking all the way up its parent pointers to the root and testing each ancestor along the path.
How slow can that get? If the tree is balanced, height
his aboutlog2(n). But nothing requires the input tree to be balanced! On a single right-leaning chain ofn = 100,000nodes, nodekwalks throughkancestors:1 + 2 + 3 + ... + 99,999 ~= 5 * 10^9 comparisons (O(n^2) time -> times out!)To finish comfortably within time limits for
n = 10^5, we need anO(n)solution that checks each node inO(1)time without walking back up the tree.Compress all ancestors into one open interval `(low, high)`
Suppose a node has ten ancestors above it: four where we branched right (say
2,10,7,8) and six where we branched left (say50,25,15,30,40,20). Do we really need to remember all ten numbers?No! Being strictly greater than
2,10,7, and8all at once is identical to being strictly greater than their maximum,10. Being strictly less than50,25,15,30,40, and20is identical to being strictly less than their minimum,15.So all ancestor constraints on any node collapse into a single open interval
(low_bound, high_bound): - The root has no ancestors, so its allowed interval is(-inf, +inf). - A node is valid if and only iflow_bound < node_value < high_bound(so it is invalid whennode_value <= low_bound or node_value >= high_bound). - Each parent passes an updated interval down to its two children inO(1)time.Subtle trap: why child bounds need `min` and `max`
If you have written standard "is this tree a valid BST?" code before, you probably passed
(low, node_value)to the left child and(node_value, high)to the right child.Watch out — that shortcut breaks when we continue past an invalid node!
In boolean BST validation, the algorithm stops as soon as it sees an invalid node, so every parent that ever recurses is guaranteed to lie inside
(low, high). Here we must keep counting below invalid nodes, and an invalid node can lie outside its own interval! Look at[10, None, 4, None, 7]:10 allowed: (-inf, +inf) -> valid \ 4 right of 10 -> allowed: (10, +inf) -> 4 <= 10, INVALID! \ 7 right of 10 AND right of 4: WRONG if we pass (4, +inf) -> 7 > 4 looks valid! RIGHT with (max(10, 4), +inf) = (10, +inf) -> 7 <= 10, INVALID!Node
7sits in the right subtree of10, so7must still exceed10. Usingminandmaxguarantees a child's allowed window never widens past an earlier ancestor's rule: - Left child receives(low_bound, min(high_bound, node_value)). - Right child receives(max(low_bound, node_value), high_bound).Decode `level_order` and validate in one breadth-first pass
We do not even need to build
TreeNodeobjects first, nor use recursion (which would crash withRecursionErroron a10^5-node chain because Python's default call-stack limit is1,000).Instead, we use a FIFO queue (
collections.deque, where items leave from the front in the exact order they entered at the back). Why does a queue line up so cleanly withlevel_order? Becauselevel_orderlists children in breadth-first order! Every time we pop the front node fromqueue,level_order[slot_index]andlevel_order[slot_index + 1]are guaranteed to be that exact node's left and right child slots:level_order: [ 8, 3, 6, None, None, 4, 11 ] root |---8's---| |----3's----| |---6's---| slot 1, 2 slot 3, 4 slot 5, 6from collections import deque from typing import List, Optional def count_invalid_bst_nodes(level_order: List[Optional[int]]) -> int: if not level_order or level_order[0] is None: return 0 invalid_count = 0 queue = deque([(level_order[0], float("-inf"), float("inf"))]) slot_index = 1 while queue: node_value, low_bound, high_bound = queue.popleft() if node_value <= low_bound or node_value >= high_bound: invalid_count += 1 if slot_index < len(level_order) and level_order[slot_index] is not None: left_value = level_order[slot_index] left_high = min(high_bound, node_value) queue.append((left_value, low_bound, left_high)) slot_index += 1 if slot_index < len(level_order) and level_order[slot_index] is not None: right_value = level_order[slot_index] right_low = max(low_bound, node_value) queue.append((right_value, right_low, high_bound)) slot_index += 1 return invalid_countNotice
slot_index < len(level_order): compact level-order inputs omit trailingNones after the last real node (for instance[5, 1]), so checking bounds handles truncated lists effortlessly.Trace Example 1 step by step
Let's trace
level_order = [8, 3, 6, None, None, 4, 11]:Tree: 8 (-inf, +inf) valid / \ 3 6 3: (-inf, 8) valid | 6: (8, +inf) INVALID (6 <= 8) / \ 4 11 4: (8, 6) INVALID | 11: (8, +inf) valid (11 > 8) Queue trace: Pop (8, -inf, +inf) -> 8 in (-inf, +inf): OK slots 1, 2 are 3, 6 -> push (3, -inf, 8), push (6, 8, +inf) Pop (3, -inf, 8) -> 3 in (-inf, 8): OK slots 3, 4 are None, None Pop (6, 8, +inf) -> 6 <= 8: INVALID (invalid_count = 1) left_high = min(+inf, 6) = 6, right_low = max(8, 6) = 8 slots 5, 6 are 4, 11 -> push (4, 8, 6), push (11, 8, +inf) Pop (4, 8, 6) -> 4 <= 8: INVALID (invalid_count = 2) list ended Pop (11, 8, +inf) -> 11 in (8, +inf): OK list endedLook at what happened to node
4: because it sits in the right subtree of8(> 8) and the left subtree of6(< 6), its interval became(8, 6)— an empty range! No number can be both greater than8and less than6, so4(and anything below4, if it had children) automatically failsnode_value <= low_bound or node_value >= high_bound. Total invalid nodes =2.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque def count_invalid_bst_nodes(level_order: List[Optional[int]]) -> int: # Phase 1: An empty list or a null root has zero nodes, so zero violations. if not level_order or level_order[0] is None: return 0 invalid_count = 0 # queue: deque of (node_value, low_bound, high_bound) in breadth-first order, # e.g. deque([(8, -inf, +inf)]). # A node is valid iff low_bound < node_value < high_bound for ALL ancestors. queue = deque([(level_order[0], float("-inf"), float("inf"))]) # slot_index: index of the next unread child slot in level_order. # Because compact level-order lists children of non-null nodes in FIFO order, # each popped node owns the next two slots (left child, then right child). slot_index = 1 # Phase 2: Process every node iteratively (avoiding recursion limits up to 10^5). while queue: node_value, low_bound, high_bound = queue.popleft() # Strict BST inequality: duplicates (==) also violate the ancestor range. if node_value <= low_bound or node_value >= high_bound: invalid_count += 1 # Phase 3: Tighten bounds for children using min/max rather than replacing # high_bound or low_bound blindly. If node_value itself was invalid (outside # its range), min/max prevents loosening a stricter ancestor constraint! if slot_index < len(level_order) and level_order[slot_index] is not None: left_value = level_order[slot_index] left_high = min(high_bound, node_value) queue.append((left_value, low_bound, left_high)) slot_index += 1 if slot_index < len(level_order) and level_order[slot_index] is not None: right_value = level_order[slot_index] right_low = max(low_bound, node_value) queue.append((right_value, right_low, high_bound)) slot_index += 1 return invalid_count✅ Submit now — all tests should pass.
Intuition & how it works
Think of walking down a binary search tree (BST) (a binary tree where every node in a left subtree is strictly smaller than that subtree's root and every node in a right subtree is strictly larger) like narrowing a price filter as you click deeper into categories. At the top of the tree, any integer in (-inf, +inf) is allowed; stepping into a left child adds a strict ceiling (< parent), and stepping into a right child adds a strict floor (> parent). Instead of forcing every node to climb back up the tree to compare itself with all of its ancestors one by one, each parent passes down the single tightest (low_bound, high_bound) window required by every ancestor above it.
Two obvious approaches fail here. Checking all ancestors upward from every node takes O(n^2) time on a tall, skinny chain of 10^5 nodes, while comparing each node only with its direct parent misses grandparent violations (such as 9 being the left child of 18 inside the right subtree of 12 in Example 3). Even standard boolean BST-validation code hides a trap: passing (node_value, high_bound) instead of (max(low_bound, node_value), high_bound) accidentally loosens the floor below an invalid node!
We process the compact level_order array in a single breadth-first search (BFS) (visiting nodes level by level from top to bottom) using a FIFO queue (a "first-in, first-out" line where nodes leave from the front in the same order they were added at the back). Consider Example 1, level_order = [8, 3, 6, None, None, 4, 11]:
1. Root 8 pops with (-inf, +inf) (valid) and pushes left child 3 with (-inf, 8) and right child 6 with (8, +inf).
2. Node 3 pops with (-inf, 8) (valid) and consumes two None child slots.
3. Node 6 pops with (8, +inf): since 6 <= 8, invalid_count becomes 1. It pushes left child 4 with (8, min(+inf, 6)) = (8, 6) and right child 11 with (max(8, 6), +inf) = (8, +inf).
4. Node 4 fails (8, 6) (invalid_count becomes 2), while node 11 satisfies 8 < 11 < +inf, returning 2.
Complexity
Let n be the length of level_order (which is at most roughly twice the number of non-null tree nodes) and w be the maximum width of the tree (the largest number of nodes on a single level).
- Time — O(n): Every slot in
level_orderis inspected once asslot_indexadvances from1tolen(level_order), and each non-null node is appended to and popped fromdequeonce inO(1)time with two numeric comparisons and at most onemin/max. - Space — O(w), which is O(n) in the worst case: The queue holds only the active frontier between the current level and the next level — just
1tuple at a time on a skewed chain (O(1)), and at most roughlyn / 2tuples on the bottom level of a complete binary tree (O(n)).
Edge cases
- Empty tree (
[]or[None]): Returns0immediately before touching the queue. - Single-node tree (
[7]or[-3]): The root has range(-inf, +inf)and zero ancestors, so it always returns0. - Duplicate values (
[2, 2]or[12, 7, 18, 3, 12, 9, 25]): Because BST inequalities are strict, a descendant equal to any ancestor bound satisfiesnode_value <= low_boundornode_value >= high_boundand is counted as invalid. - Grandparent violation with valid parent (
[12, 7, 18, 3, 12, 9, 25]):9 < 18satisfies its parent, but9 <= 12fails its grandparent's lower bound. - Valid and invalid nodes underneath an invalid ancestor (
[10, None, 4, None, 7]vs[10, None, 4, None, 12]): Below the invalid right child4,max(10, 4)keepslow_bound = 10, so7is caught as invalid (2total) while12is recognized as valid (1total). - Empty/inverted intervals (
low_bound >= high_bound): When a node sits right of8and left of6, its interval becomes(8, 6); no number can satisfy8 < x < 6, so our checkx <= 8 or x >= 6automatically flags every descendant in that subtree. - Skewed
10^5-node chains: Because the BFS loop is completely iterative, a100,000-deep chain runs in milliseconds without hitting Python's recursion limit.
Common mistakes
- Passing
(low_bound, node_value)and(node_value, high_bound)withoutmin/max: That works only when you abort on the first invalid node. Continuing past an invalid node withoutmin/maxoverwrites tighter ancestor bounds and undercounts invalid descendants (e.g., returning1instead of2on[10, None, 4, None, 7]). - Checking only parent-child pairs: Misses violations caused by grandparents or higher ancestors (returns
0instead of2on Example 3). - Stopping traversal inside an invalid node's subtree: Even when a node violates the BST rule, some of its descendants may be valid and others invalid (
11is valid while4is invalid below6in Example 1), so you must always keep traversing. - Counting inversions or drops in the in-order traversal: An in-order traversal visits left subtree, then current node, then right subtree (
[3, 8, 4, 6, 11]on Example 1). That sequence has only one drop (8 -> 4), even though two nodes (6and4) violate ancestor ranges! - Using recursive DFS in Python: A skewed tree with
n = 10^5exceeds Python's default1,000-frame call-stack limit and raisesRecursionError. - Using
2 * i + 1and2 * i + 2heap indexing onlevel_order: Compact level-order arrays skip child slots forNoneentries ([10, None, 4, None, 7]has length5, not7), so heap index arithmetic reads the wrong slots wheneverNonenodes appear above leaves.
Alternative approaches
- Two-step tree construction + iterative stack DFS: You can decode
level_orderinto explicitTreeNodeobjects first and then run an iterative depth-first stack holding(node, low_bound, high_bound). It achieves the sameO(n)time andO(n)worst-case space, though fusing the level-order decode with the range check saves allocatingnnode objects.
Follow-up questions
- What changes if the tree is passed as pointer-based TreeNode objects rather than a level-order array? Keep the exact same
(low_bound, high_bound)logic withmin/max, and iterate using a Python liststack = [(root, float("-inf"), float("inf"))]: pop(node, low, high), incrementinvalid_countwhennode.val <= low or node.val >= high, and push(node.left, low, min(high, node.val))and(node.right, max(low, node.val), high)for non-null children. Staying iterative with an explicit stack preservesO(n)time while remaining immune toRecursionErroron10^5-deep chains. - How would you adjust the range check if left subtrees allowed duplicate values (left <= node < right)? Only the left-side comparison changes from strict
<to<=, meaninghigh_boundbecomes an inclusive upper bound whilelow_boundstays exclusive. You would updateleft_high = min(high_bound, node_value)andright_low = max(low_bound, node_value)as before, and flag a node as invalid whennode_value <= low_bound or node_value > high_bound(and if an inclusivehigh_boundever becomes<=an exclusivelow_bound, that empty interval still rejects every number). - Does counting invalid nodes give the minimum number of value edits required to repair the BST? No — they solve two different problems! Consider a right-leaning chain
99 -> 500 -> 101 -> 102 -> 103: both99and500satisfy their ancestors, while101,102, and103all violate> 500, socount_invalid_bst_nodesreturns3. Yet changing just 1 node (500to100) turns the entire chain into99 -> 100 -> 101 -> 102 -> 103, a completely valid integer BST! Finding the minimum number of integer value edits instead flattens the tree via an in-order traversalarr[0..m-1]and keeps the largest subset of indices witharr[j] - arr[i] >= j - i(equivalent to the longest non-decreasing subsequence ofarr[i] - i).
Follow-up questions
- What changes if the tree is passed as pointer-based TreeNode objects rather than a level-order array?
- How would you adjust the range check if left subtrees allowed duplicate values (left <= node < right)?
- Does counting invalid nodes give the minimum number of value edits required to repair the BST?
Similar questions
- Zero-Detour Ride-Pool Matching on a Grid
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One