Problem 390

Abstract / Summary

Players take turns removing every second number from a list until one remains and the task is to find that last number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0390.py

class Solution:
    def lastRemaining(self, n: int) -> int:
        gap   = 1
        left  = 1
        right = n
        dir   = True
        while left < right:
            length = 1 + ((right - left) // gap)
            if dir:
                left += gap
                if length % 2 == 1:
                    right -= gap
            else:
                right -= gap
                if length % 2 == 1:
                    left += gap

            dir  = not dir
            gap *= 2

        return left # or right
21 lines | 544 bytes | submitted September 19, 2023 | GitHub   5% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 46% (200k+ submissions).

Typical patterns to solve this problem:
  • Math
  • Recursion
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method lastRemaining that computes the final surviving element when repeatedly eliminating numbers from a sequence 1 to n in alternating left-to-right and right-to-left passes. The algorithm models the elimination process mathematically, updating boundaries and step size until only one number remains.

Core Logic

The method begins by initializing four variables that describe the current state of the elimination process.

gap   = 1
left  = 1
right = n
dir   = True

gap represents the distance between consecutive survivors after each pass. left and right hold the current smallest and largest surviving numbers, respectively. dir is a Boolean flag indicating the direction of the next elimination pass: True for left-to-right, False for right-to-left.

The main loop continues while more than one candidate remains, i.e., while left < right.

while left < right:
    length = 1 + ((right - left) // gap)
    ...

length computes how many numbers are currently in the interval [left, right] given the current gap. This calculation is crucial because the parity of length determines whether the far endpoint survives the current pass.

Direction-Specific Updates

When dir is True (left-to-right), the algorithm discards the current left value and moves the left boundary forward by one gap.

if dir:
    left += gap
    if length % 2 == 1:
        right -= gap

If the number of elements (length) is odd, the rightmost element also gets eliminated, so right is moved inward by one gap.

When dir is False (right-to-left), the symmetric operation is performed.

else:
    right -= gap
    if length % 2 == 1:
        left += gap

Here the right boundary is always reduced, and the left boundary is reduced only when the count of elements is odd.

Direction Toggle and Gap Expansion

After processing a pass, the direction flag is flipped and the gap is doubled, reflecting that every second element survives each round.

dir  = not dir
gap *= 2

These two statements ensure that the next iteration works on a sparser set of numbers and alternates the elimination direction.

Termination

The loop exits when left meets right. At that point both variables hold the same value, which is the last remaining number. The method returns this value.

return left  # or right

Because left and right are equal, either variable can be returned.

Edge Cases Handled

The algorithm gracefully handles the smallest possible input, n = 1. In that scenario the initial condition left < right is false, so the loop body never executes and the method returns left, which is 1.

When n is an even number, the parity checks (length % 2 == 1) correctly determine whether the far endpoint survives each pass. The alternating direction combined with the parity logic ensures that the algorithm works for any n, whether odd or even, without requiring special-case code.

If n is a power of two, the elimination pattern becomes regular, and the gap doubling aligns perfectly with the remaining interval size. The loop still converges correctly because the parity condition naturally evaluates to even at each step, leaving only the left boundary to move inward.

Performance Optimizations

The implementation avoids constructing explicit lists or performing element-wise deletions. Instead, it tracks only four scalar variables, which keeps memory usage minimal.

By computing the number of remaining elements (length) directly from the current boundaries and gap, the code eliminates the need for iterative counting. This constant-time calculation per iteration contributes to a fast convergence.

Doubling the gap after each pass reduces the number of iterations dramatically. Each iteration effectively halves the number of candidates, leading to a logarithmic number of loop executions relative to n.

The use of simple arithmetic and Boolean toggling (dir = not dir) ensures that each iteration runs with minimal overhead, leveraging Python’s fast integer operations.

Overall, the method achieves an efficient solution by modeling the elimination process analytically rather than simulating it step by step.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a line of toys numbered from one to n laid out on the floor. This code acts like a playful rule for removing those toys.

First, think of a gap between each toy. At the start, the gap is just one step. There is a left end of the line and a right end of the line. Also, there is a direction that keeps switching back and forth.

The computer looks at how many toys are left in the line. As long as there is more than one toy, it keeps going. It calculates the total length of the line. If the direction points to the right, the computer removes the first toy on the left and jumps to the next one by increasing the gap. If the count of toys is odd, it also removes the toy on the far right.

If the direction is pointing the other way, the computer removes the toy on the far right instead and jumps back by increasing the gap. If the count is odd, it removes the one on the far left too.

After each step, the direction flips like a light switch. Then the gap gets twice as big, which is like skipping even more toys each time. This continues until only one toy remains.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.65 | σ = 0.78

Complexity Analysis

Time: logarithmic
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
wisdompeak C++
31 links | 19 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 easy 5 medium 2 hard
10 solutions   September 19, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality