Ctrl K

Route in a Snake-Numbered Tree

Medium
An infinite complete binary tree is numbered row by row with 1, 2, 3, … in a snake pattern: in odd rows (first, third, fifth, …) the numbers run left to right, and in even rows (second, fourth, …) they run right to left. So the root is 1, the second row reads 3, 2 from left to right, the third reads 4, 5, 6, 7, and the fourth reads 15, 14, …, 8. Given the tag tag of a node in this tree, return the tags along the path from the root down to that node, inclusive, starting with the root.
Example 1
tag=11 → [1, 2, 6, 11]

Rows: 1 | 3 2 | 4 5 6 7 | 15 14 13 12 11 10 9 8. Tag 11 is fifth in row four; its parent is third in row three (6), whose parent is 2, then the root 1.

Example 2
tag=1 → [1]

The root is the whole route on its own.

Example 3
tag=20 → [1, 3, 5, 13, 20]
Constraints
  • 1 ≤ tag ≤ 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCounting Search Tree Shapes MediumOther Orders for the Same Search Tree HardPruning Duel on a Growing Tree HardIs It a Search Tree? MediumTwo Mixed-Up Nodes Medium
loading Python…
Input
tag=11
Expected
[1, 2, 6, 11]

Run checks the first 3 tests in your browser. Submit checks all 71 tests on the server, hidden ones included.