CodeArchon

mediumTreesAmazonGoogleFacebookUber

Rank Index Finder

A tournament database holds player scores in a sorted hierarchy. The ranking engine needs the K-th lowest score efficiently.

Given the root of a binary search tree and an integer k, return the k-th smallest value (1-indexed) across all node values.

Choose approach

3
curr
1
4
2
1/4
Narrationstep 1 of 4

Descend to left of Node 3. Push onto stack.

1def kthSmallest(root, k):
2 stack, count = [], 0
3 curr = root
4 while curr or stack:
5 while curr:
6 stack.append(curr)
7 curr = curr.left
8 curr = stack.pop()
9 count += 1
10 if count == k:
11 return curr.val
12 curr = curr.right
Variables
curr=3
stackSize=1
count=0

How to think about it

  1. In-order visits BST values in ascending order.
  2. Use a stack to iterate manually so you can stop at rank k.
  3. Increment a counter at each pop; return when counter == k.

Edge cases to catch in interview

  • k = 1 -> leftmost node.
  • k = n -> rightmost node (requires full traversal).

Examples

Example 11
{"arr":[3,1,4,null,2],"k":1}
Example 23
{"arr":[5,3,6,2,4,null,null,1],"k":3}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed