Payments app~20 min2s · 256 MBtarget O(h + k) time, O(h) spaceclassic twin: lc-230tree-recursion
A payments app files its receipt ids in a search tree. Smaller ids sit on the left, and larger ids on the right. The oldest receipts are archived in order, so support often asks for the k-th smallest id still in the tree.
The tree can hold 100,000 receipts. Your team lead wants the answer without reading the whole tree when k is small.
Write kth_smallest(values, left, right, k).
0 to n - 1, and receipt 0 is the top of the tree. There is at least one receipt.values[i] is the id of receipt i. left[i] and right[i] are the receipts on its left and right, or -1 where there is none.k-th smallest id, counting the smallest as number 1. k is at least 1 and at most n, so there is always an answer.Input: values = [8, 3, 10, 1, 6, 14, 4, 7, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], k = 4
Output: 6The ids in order are 1, 3, 4, 6, 7, 8, 10, 13, 14, and the 4th is 6. The walk goes left as far as it can, takes the top of the stack, and then continues on the right of that receipt.
| Round | Stack after going left (trips) | Trip taken (id) | k left |
|---|---|---|---|
| 1 | [0, 1, 3] |
3 (1) | 3 |
| 2 | [0, 1] |
1 (3) | 2 |
| 3 | [0, 4, 6] |
6 (4) | 1 |
| 4 | [0, 4] |
4 (6) | 0 |
It stops after 4 receipts, and the right side of 8 is never read.
Input: values = [5], left = [-1], right = [-1], k = 1
Output: 5Input: values = [2, 1, 3], left = [1, -1, -1], right = [2, -1, -1], k = 3
Output: 31 ≤ length of values = length of left = length of right ≤ 10^51 ≤ values[i] ≤ 10^9, and the ids are distinctleft and right is -1 or a receipt number from 1 to n - 101 ≤ k ≤ nReceipts can arrive in sorted order, so the tree can be a chain of 100,000 receipts. Searching from the top again for each next id then costs about n steps each, which is n^2 / 2 steps in total.
Walk the tree in order once with a stack, and stop at the k-th id. Each receipt is put on the stack once and taken off once.