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 with 0 nodes.
  • level_order[0] is the root's value, and each non-None node (in breadth-first order) consumes the next two list positions for its left child and right child. None entries denote missing children and do not consume child slots; trailing None entries 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 most 10^5 non-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 to 10^5.

Step-by-step walkthrough

  1. Understand the BST rule and the level-order input

    In a strict Binary Search Tree (BST), every node holding value v imposes an ordering rule on all nodes below it: - Every node anywhere in its left subtree must satisfy value < v. - Every node anywhere in its right subtree must satisfy value > 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]), node 9 is smaller than its parent 18, yet 9 sits inside the right subtree of root 12 where every value must exceed 12. 2. Count violating descendants once: Even if a node fails bounds imposed by three different ancestors, that node still adds 1 to 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 duplicate 12 inside the left subtree of root 12 in 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)
    
  2. 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 h is about log2(n). But nothing requires the input tree to be balanced! On a single right-leaning chain of n = 100,000 nodes, node k walks through k ancestors:

    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 an O(n) solution that checks each node in O(1) time without walking back up the tree.

  3. 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 (say 50, 25, 15, 30, 40, 20). Do we really need to remember all ten numbers?

    No! Being strictly greater than 2, 10, 7, and 8 all at once is identical to being strictly greater than their maximum, 10. Being strictly less than 50, 25, 15, 30, 40, and 20 is 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 if low_bound < node_value < high_bound (so it is invalid when node_value <= low_bound or node_value >= high_bound). - Each parent passes an updated interval down to its two children in O(1) time.

  4. 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 7 sits in the right subtree of 10, so 7 must still exceed 10. Using min and max guarantees 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).

  5. Decode `level_order` and validate in one breadth-first pass

    We do not even need to build TreeNode objects first, nor use recursion (which would crash with RecursionError on a 10^5-node chain because Python's default call-stack limit is 1,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 with level_order? Because level_order lists children in breadth-first order! Every time we pop the front node from queue, level_order[slot_index] and level_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, 6
    
    from 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_count
    

    Notice slot_index < len(level_order): compact level-order inputs omit trailing Nones after the last real node (for instance [5, 1]), so checking bounds handles truncated lists effortlessly.

  6. 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 ended
    

    Look at what happened to node 4: because it sits in the right subtree of 8 (> 8) and the left subtree of 6 (< 6), its interval became (8, 6) — an empty range! No number can be both greater than 8 and less than 6, so 4 (and anything below 4, if it had children) automatically fails node_value <= low_bound or node_value >= high_bound. Total invalid nodes = 2.

  7. 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_order is inspected once as slot_index advances from 1 to len(level_order), and each non-null node is appended to and popped from deque once in O(1) time with two numeric comparisons and at most one min/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 1 tuple at a time on a skewed chain (O(1)), and at most roughly n / 2 tuples on the bottom level of a complete binary tree (O(n)).

Edge cases

  • Empty tree ([] or [None]): Returns 0 immediately before touching the queue.
  • Single-node tree ([7] or [-3]): The root has range (-inf, +inf) and zero ancestors, so it always returns 0.
  • Duplicate values ([2, 2] or [12, 7, 18, 3, 12, 9, 25]): Because BST inequalities are strict, a descendant equal to any ancestor bound satisfies node_value <= low_bound or node_value >= high_bound and is counted as invalid.
  • Grandparent violation with valid parent ([12, 7, 18, 3, 12, 9, 25]): 9 < 18 satisfies its parent, but 9 <= 12 fails 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 child 4, max(10, 4) keeps low_bound = 10, so 7 is caught as invalid (2 total) while 12 is recognized as valid (1 total).
  • Empty/inverted intervals (low_bound >= high_bound): When a node sits right of 8 and left of 6, its interval becomes (8, 6); no number can satisfy 8 < x < 6, so our check x <= 8 or x >= 6 automatically flags every descendant in that subtree.
  • Skewed 10^5-node chains: Because the BFS loop is completely iterative, a 100,000-deep chain runs in milliseconds without hitting Python's recursion limit.

Common mistakes

  • Passing (low_bound, node_value) and (node_value, high_bound) without min/max: That works only when you abort on the first invalid node. Continuing past an invalid node without min/max overwrites tighter ancestor bounds and undercounts invalid descendants (e.g., returning 1 instead of 2 on [10, None, 4, None, 7]).
  • Checking only parent-child pairs: Misses violations caused by grandparents or higher ancestors (returns 0 instead of 2 on 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 (11 is valid while 4 is invalid below 6 in 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 (6 and 4) violate ancestor ranges!
  • Using recursive DFS in Python: A skewed tree with n = 10^5 exceeds Python's default 1,000-frame call-stack limit and raises RecursionError.
  • Using 2 * i + 1 and 2 * i + 2 heap indexing on level_order: Compact level-order arrays skip child slots for None entries ([10, None, 4, None, 7] has length 5, not 7), so heap index arithmetic reads the wrong slots whenever None nodes appear above leaves.

Alternative approaches

  • Two-step tree construction + iterative stack DFS: You can decode level_order into explicit TreeNode objects first and then run an iterative depth-first stack holding (node, low_bound, high_bound). It achieves the same O(n) time and O(n) worst-case space, though fusing the level-order decode with the range check saves allocating n node 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 with min/max, and iterate using a Python list stack = [(root, float("-inf"), float("inf"))]: pop (node, low, high), increment invalid_count when node.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 preserves O(n) time while remaining immune to RecursionError on 10^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 <=, meaning high_bound becomes an inclusive upper bound while low_bound stays exclusive. You would update left_high = min(high_bound, node_value) and right_low = max(low_bound, node_value) as before, and flag a node as invalid when node_value <= low_bound or node_value > high_bound (and if an inclusive high_bound ever becomes <= an exclusive low_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: both 99 and 500 satisfy their ancestors, while 101, 102, and 103 all violate > 500, so count_invalid_bst_nodes returns 3. Yet changing just 1 node (500 to 100) turns the entire chain into 99 -> 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 traversal arr[0..m-1] and keeps the largest subset of indices with arr[j] - arr[i] >= j - i (equivalent to the longest non-decreasing subsequence of arr[i] - i).

Follow-up questions

Similar questions

More Applovin interview questions

All 2 Applovin questions →