Bird
Raised Fist0
Interview Prepbinary-search-treesmediumAmazonGoogleFacebookBloomberg

Kth Smallest Element in a BST

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Steps
setup

Initialize stack and current pointer

We start with an empty stack and set current to the root node (value 3). The count of visited nodes is zero.

💡 Initialization sets up the data structures needed for iterative in-order traversal.
Line:stack = [] current = root count = 0
💡 The traversal will begin from the root, and the stack will help us backtrack after reaching leftmost nodes.
📊
Kth Smallest Element in a BST - Watch the Algorithm Execute, Step by Step
Watching each stack operation and pointer movement reveals how in-order traversal naturally visits nodes in ascending order, making it the fastest way to understand the kth smallest element search.
Step 1/10
·Active fillAnswer cell
Current node: 1
3124
Current node: 2
3124
3124
Current node: 2
3124
Result: [1]
Current node: 2
3124
Result: [1]
Return: 1
3124
Result: [1]
Return: 1
3124
Result: [1]
Return: 1
Current node: 5
3124
Result: [1]
Return: 1
3124
Result: [1]
Return: 1
3124
Result: [1, 2, 3, 4]
Return: 1

Key Takeaways

In-order traversal visits BST nodes in ascending order, enabling direct access to the kth smallest element by counting visits.

This insight is hard to see from code alone because the traversal order and counting are implicit; visualization makes it explicit.

The stack stores nodes whose left subtrees are fully explored but whose right subtrees are yet to be visited, enabling backtracking.

Understanding the stack's role clarifies how iterative traversal mimics recursion.

The algorithm stops immediately when the kth smallest node is visited, optimizing performance by avoiding unnecessary traversal.

This early stopping is subtle in code but critical for efficiency, and visualization highlights this decision clearly.

Practice

(1/5)
1. Consider the following code for computing the range sum of a BST. Given the BST with root value 10, left child 5, right child 15, and range [7, 15], what is the final value of total returned by rangeSumBST?
easy
A. 25
B. 15
C. 40
D. 30

Solution

  1. Step 1: Trace initial stack and total

    Start with stack=[10], total=0.
  2. Step 2: Pop 10 (in range), add 10, push left(5) and right(15)

    total=10, stack=[5,15]
  3. Step 3: Pop 15 (in range), add 15, push left(null) and right(null)

    total=25, stack=[5,null,null]
  4. Step 4: Pop null (skip), then pop null (skip), then pop 5 (less than low=7), push right(null)

    total=25, stack=[null]
  5. Step 5: Pop null (skip), stack empty, return total=25

    5 is less than low, so it is skipped and not added.
  6. Final Answer:

    Option A -> Option A
  7. Quick Check:

    Sum includes 10 and 15 only, total=25 [OK]
Hint: Only nodes within [7,15] add to total [OK]
Common Mistakes:
  • Adding nodes outside range
  • Forgetting to push children after adding node
2. Given the following code for trimming a BST and the input tree with root value 3, left child 1, right child 4, and low=2, high=3, what is the value of the root node after trimming?
easy
A. 2
B. 3
C. 1
D. 4

Solution

  1. Step 1: Move root to valid range

    Root=3 is within [2,3], so no change.
  2. Step 2: Trim left subtree

    Left child=1 < 2, so replace left child with its right subtree (None). Left child becomes None.
  3. Step 3: Trim right subtree

    Right child=4 > 3, so replace right child with its left subtree (None). Right child becomes None.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Root remains 3 with no children after trimming [OK]
Hint: Check root adjustment before subtree trimming [OK]
Common Mistakes:
  • Assuming root changes when already in range
  • Forgetting to trim subtrees correctly
3. Consider the following code snippet implementing the optimal approach for Two Sum IV in BST. Given the BST with nodes [5,3,6,2,4,null,7] and target k=9, what is the value of variable s during the first iteration of the while loop?
easy
A. 9
B. 5
C. 11
D. 7

Solution

  1. Step 1: Perform inorder traversal

    Inorder traversal of BST yields sorted array: [2, 3, 4, 5, 6, 7]
  2. Step 2: Calculate s in first iteration

    left=0 (value=2), right=5 (value=7), s = 2 + 7 = 9
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sum matches target k=9 on first iteration [OK]
Hint: Inorder array first + last sum equals target [OK]
Common Mistakes:
  • Off-by-one error in indexing left or right
  • Confusing node values with indices
  • Miscomputing sum s
4. Consider the following Python code implementing BST validation using inorder traversal. What is the output of the program when run with the given test cases?
easy
A. true followed by false
B. true followed by true
C. false followed by true
D. false followed by false

Solution

  1. Step 1: Trace first tree (2,1,3)

    Inorder traversal yields [1,2,3], strictly increasing, so returns true.
  2. Step 2: Trace second tree (5,1,4 with children 3 and 6)

    Inorder traversal yields [1,5,3,4,6], 3 < 5 violates BST property, so returns false.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    First tree valid BST, second invalid due to subtree violation [OK]
Hint: Inorder traversal must be strictly increasing [OK]
Common Mistakes:
  • Assuming subtree root comparison is enough
  • Confusing output order
  • Missing strict inequality check
5. The following code attempts to compute the range sum of a BST using iterative DFS with pruning. Identify the line containing the subtle bug that causes incorrect results or inefficiency.
medium
A. Line that appends node.left when node.val < low
B. Line that pops node from stack
C. Line that adds node.val to total
D. Line that appends node.right when node.val is in range

Solution

  1. Step 1: Understand pruning logic

    If node.val < low, left subtree nodes are smaller and cannot be in range, so left subtree should be skipped.
  2. Step 2: Identify incorrect line

    Appending node.left when node.val < low causes unnecessary traversal of left subtree, violating pruning. It should append node.right instead.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Correct pruning requires appending node.right only when node.val < low [OK]
Hint: Prune left subtree if node.val < low [OK]
Common Mistakes:
  • Appending wrong subtree when pruning
  • Forgetting to check null nodes