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.
Variables
curr=3
stackSize=1
count=0
How to think about it
- In-order visits BST values in ascending order.
- Use a stack to iterate manually so you can stop at rank k.
- 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 1
1{"arr":[3,1,4,null,2],"k":1}
Example 2
3{"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