Skip to the solution
MediumDSA11 min read

How do you find the kth smallest element in a BST?

700 views

The problem

Question presented to candidate: "Given the root of a binary search tree and an integer k, write a Python function that returns the kth smallest value in the tree (k is 1-indexed). Then tell me what you would change if the tree is modified often and kth-smallest is asked many times."

What a strong answer should cover:

  • In-order traversal of a BST visits values in sorted order, so the kth visited node is the answer.
  • Stop early: an iterative in-order walk with an explicit stack costs O(h + k) time and O(h) space instead of O(n).
  • The simple version (collect the whole in-order list, return index k โˆ’ 1) is O(n) time and O(n) space โ€” correct, but wasteful.
  • The follow-up: store a subtree size in every node (an order-statistic tree) so each query is one root-to-node walk, O(h), and updates keep sizes current.
  • Invalid k (k < 1 or k > n) and what to return.
  • Python specifics: a list as the stack; a generator with yield from plus itertools.islice is a neat lazy alternative, but recursive generators still hit the recursion limit on deep trees.

Clarifying questions expected:

  • Is k always between 1 and the number of nodes?
  • Will the tree be modified between queries, and how many queries will there be?

Code / implementation expected: Yes โ€” an iterative in-order walk with a list as the stack, in Python 3.

  • trees
  • bst
  • inorder

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonEarly-stop in-order for every k, checked against the list method
PythonOrder-statistic tree: subtree sizes vs in-order walk (1,000 keys)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 73 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you search a sorted 2D matrix?

Continue