K-th Fastest Finisher
At a city marathon, each finishing time in seconds goes into a binary search tree as the runner crosses the line: faster left, slower right. The tree is never re-sorted, so its shape depends on finishing order.
The prize table calls runners by place: the 3rd fastest, the 10th for a spot prize. The tree already keeps times in order, so there is no need to copy them out and sort.
Your task
Write kthFastest(root, k). root is a valid binary search tree. Return its k-th smallest value (k = 1 is the smallest).
All times are different, and k is between 1 and the number of nodes. Trees are shown in level order, like [9000, 8000, 9500], with null for a missing child. Your function receives real TreeNode objects with val, left and right.
kthFastest(root: TreeNode, k: int) → int
Examples
root = [9000, 8000, 9500, 7800, 8600, 9200, 9900] k = 3
8600
In sorted order the times are 7800, 8000, 8600, 9000, 9200, 9500 and 9900, so the 3rd is 8600. The 3rd value in the tree layout is 9500, and that is the wrong answer.
root = [9000, 8000, 9500, 7800, 8600, 9200, 9900] k = 7
9900
Place 7 of 7 is the slowest runner, which is the rightmost node. Places count from 1, so k = 7 is the last runner and not past the end.
Constraints
- 1 ≤ number of runners ≤ 1,000
- 1 ≤ k ≤ number of runners
- 1 ≤ time ≤ 86,400, all different
- The tree is a valid binary search tree, at most 500 levels deep.
Start with brute force
Collect every time into a list, sort it, and return the item at k - 1. That is O(n log n) and always visits all n runners, even when you only want the fastest.
The sort is wasted work, because the tree already stores the times in order. An in-order walk reads them in sorted order and can stop after k of them.
Hints
0 of 4 shown- Hint 1
In a search tree, where is the fastest time? Which time comes right after it?
- Hint 2
Left subtree, then node, then right subtree visits the values from smallest to largest. That order is called in-order.
- Hint 3
So the answer is the k-th node an in-order walk visits. Do you need to finish the walk once you reach k?
- Hint 4
Do an in-order walk with a counter (recursively, or with a stack: push nodes while going left, pop one, count it, then go to its right child). When the counter reaches k, return that value and stop.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
In a binary search tree, left is smaller and right is larger, so "left subtree, node, right subtree" visits values in sorted order. Count as you visit and stop at k.
Trace [9000, 8000, 9500, 7800, 8600, 9200, 9900] with k = 3:
- Start at 9000 and keep going left, pushing 9000, 8000 and 7800 onto the stack.
- Pop 7800. The count is 1, and it has no right child.
- Pop 8000. The count is 2. Go right to 8600 and keep going left, which pushes only 8600.
- Pop 8600. The count is 3, which equals
k, so return 8600.
9500, 9200 and 9900 are never touched. The explicit stack does the job of the recursion, and it makes stopping at k easy.
function kthFastest(root, k) {
const stack = [];
let node = root;
while (true) {
while (node !== null) { // slide to the smallest unvisited time
stack.push(node);
node = node.left;
}
node = stack.pop(); // next time in sorted order
k -= 1;
if (k === 0) return node.val;
node = node.right; // then the times just above it
}
}def kth_fastest(root, k):
stack = []
node = root
while True:
while node is not None: # slide to the smallest unvisited time
stack.append(node)
node = node.left
node = stack.pop() # next time in sorted order
k -= 1
if k == 0:
return node.val
node = node.right # then the times just above itRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.