Search~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-108tree-recursion
A search engine stores the ids of the documents that match a word as a sorted list. Every night it loads each list as a search tree, so that a lookup follows one short path.
The list can hold 100,000 ids. If the ids were added one by one in sorted order, the tree would be a chain, and a lookup would take 100,000 steps. Your team lead wants a tree that stays balanced.
Write balanced_levels(ids).
ids is a list of distinct ids in increasing order. An empty list gives an empty tree.m ids, the one with (m - 1) // 2 ids before it. The ids before the root form the left part, and the ids after it form the right part.Input: ids = [1, 3, 4, 6, 7, 8, 10, 13, 14]
Output: [[7], [3, 10], [1, 4, 8, 13], [6, 14]]The tree has 4 levels. The part 1 to 14 has 9 ids, so its root is the one with 4 ids before it, which is 7. The left part, 1 to 6, has 4 ids, and its lower middle is 3.
Each part is written as its first and last id. The queue keeps the parts of one level together.
| Level | Parts (first id to last id) | Root of each part | Parts for the next level |
|---|---|---|---|
| 1 | 1 to 14 | 7 | 2 |
| 2 | 1 to 6; 8 to 14 | 3, 10 | 4 |
| 3 | 1; 4 to 6; 8; 13 to 14 | 1, 4, 8, 13 | 2 |
| 4 | 6; 14 | 6, 14 | 0 |
Input: ids = [5]
Output: [[5]]Input: ids = []
Output: []0 ≤ length of ids ≤ 10^51 ≤ ids[i] ≤ 10^9Adding the ids one by one in sorted order makes a chain of 100,000 nodes, with 100,000 levels. A lookup in it takes 100,000 steps.
A balanced tree of 100,000 ids has 17 levels. Choose each root from the middle of its part, and every part is about half the size of the one above it.