Skip to main content
LeetCode 390, Medium. Topics: Math, Recursion. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 34 parametrized pytest cases, and a playground notebook:

Problem

You have a list <code>arr</code> of all integers in the range <code>[1, n]</code> sorted in a strictly increasing order. Apply the following algorithm on <code>arr</code>: <ul> <li>Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.</li> <li>Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.</li> <li>Keep repeating the steps again, alternating left to right and right to left, until a single number remains.</li> </ul> <p>Given the integer <code>n</code>, return <em>the last number that remains in</em> <code>arr</code>.</p>

Examples

Constraints

  • 1 <= n <= 10<sup>9</sup>

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026