#3782
Last Remaining Integer After Alternating Deletion Operations
HardMathRecursionRecursionDivide and Conquer
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach uses recursion to efficiently determine the last remaining integer without simulating the entire deletion process. It leverages the pattern of remaining integers based on the current direction of deletion.
⚙️
Algorithm
3 steps- 1Step 1: Define a recursive function that takes the current range and direction.
- 2Step 2: If only one number remains, return it.
- 3Step 3: Depending on the direction, calculate the new range after deleting every second number.
solution.py9 lines
1def last_remaining_optimal(n):
2 def helper(start, length, left):
3 if length == 1:
4 return start
5 if left:
6 return helper(start, (length + 1) // 2, not left)
7 else:
8 return helper(start + (length % 2), length // 2, not left)
9 return helper(1, n, True)ℹ
Complexity note: The recursive depth can go up to n, leading to linear time complexity, while the space complexity is due to the call stack.
- 1The direction of deletion alternates, affecting which numbers remain.
- 2The problem can be solved recursively by tracking the start and length.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.