LeetCode #3782 — HARD

Last Remaining Integer After Alternating Deletion Operations

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer n.

We write the integers from 1 to n in a sequence from left to right. Then, alternately apply the following two operations until only one integer remains, starting with operation 1:

  • Operation 1: Starting from the left, delete every second number.
  • Operation 2: Starting from the right, delete every second number.

Return the last remaining integer.

Example 1:

Input: n = 8

Output: 3

Explanation:

  • Write [1, 2, 3, 4, 5, 6, 7, 8] in a sequence.
  • Starting from the left, we delete every second number: [1, 2, 3, 4, 5, 6, 7, 8]. The remaining integers are [1, 3, 5, 7].
  • Starting from the right, we delete every second number: [1, 3, 5, 7]. The remaining integers are [3, 7].
  • Starting from the left, we delete every second number: [3, 7]. The remaining integer is [3].

Example 2:

Input: n = 5

Output: 1

Explanation:

  • Write [1, 2, 3, 4, 5] in a sequence.
  • Starting from the left, we delete every second number: [1, 2, 3, 4, 5]. The remaining integers are [1, 3, 5].
  • Starting from the right, we delete every second number: [1, 3, 5]. The remaining integers are [1, 5].
  • Starting from the left, we delete every second number: [1, 5]. The remaining integer is [1].

Example 3:

Input: n = 1

Output: 1

Explanation:

  • Write [1] in a sequence.
  • The last remaining integer is 1.

Constraints:

  • 1 <= n <= 1015

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer n. We write the integers from 1 to n in a sequence from left to right. Then, alternately apply the following two operations until only one integer remains, starting with operation 1: Operation 1: Starting from the left, delete every second number. Operation 2: Starting from the right, delete every second number. Return the last remaining integer.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Math

Example 1

8

Example 2

5

Example 3

1
Step 02

Core Insight

What unlocks the optimal approach

  • Use divide and conquer.
  • Maintain the start value, remaining length, and current direction using recursion.
  • Track the current direction (left or right) and update the start value based on the parity of the remaining length.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3782: Last Remaining Integer After Alternating Deletion Operations
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3782: Last Remaining Integer After Alternating Deletion Operations
// package main
// 
// // https://space.bilibili.com/206214
// func lastInteger1(n int64) int64 {
// 	start, d := int64(1), int64(1) // 等差数列首项,公差
// 	for ; n > 1; n = (n + 1) / 2 {
// 		start += (n - 2 + n%2) * d
// 		d *= -2
// 	}
// 	return start
// }
// 
// // https://oeis.org/A090569
// func lastInteger(n int64) int64 {
// 	const mask = 0xAAAAAAAAAAAAAAA // ...1010
// 	return (n-1)&mask + 1 // 取出 n-1 的从低到高第 2,4,6,... 位,最后再加一(从 1 开始)
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

ITERATIVE
O(n) time
O(1) space

Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.

MATH INSIGHT
O(log n) time
O(1) space

Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.

Shortcut: Look for mathematical properties that eliminate iteration. Repeated squaring → O(log n). Modular arithmetic avoids overflow.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.