Problem Description
Given a sorted list of numbers from 1 to n, repeatedly remove elements in alternating rounds. First, remove the first element and every other element from left to right; then, remove the last element and every other element from right to left. Continue this process, alternating directions, until only one number remains. Return that number.
Key Insights
- The head element (first element of the current list) always gets removed in the left-to-right elimination.
- In right-to-left elimination, the head moves only when the count of remaining elements is odd.
- Instead of simulating the removals (which would be inefficient for large n), update the head mathematically based on the current step and direction.
- Use a loop that halves the number of remaining elements in each round, doubling the step size, and switching the elimination direction.
Space and Time Complexity
Time Complexity: O(log n) - The number of remaining elements is roughly halved each round. Space Complexity: O(1) - Only a constant amount of extra space is used.
Solution
Maintain variables for the head (starting at 1), step size (initially 1), remaining element count (n), and elimination direction (starting from left-to-right). In each round, update the head according to the following rules:
- If eliminating from left-to-right, always update the head.
- If eliminating from right-to-left, update the head only if the remaining number count is odd. After each round, double the step size and halve the remaining elements. Toggle the elimination direction. Continue until there is only one element remaining, which is the final answer.