Problem 1040

Abstract / Summary

Given a row of stones, move the fewest stones to make them all consecutive.

Note

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

Python 1040.py

class Solution:
    def numMovesStonesII(self, stones: List[int]) -> List[int]:
        stones.sort()
        size  = len(stones)
        inner = size - 2

        # maximum
        # find the range with the least stones (except one endpoint)
        # move a stone next to an endpoint, then move that endpoint next to the other endpoint
        high = max(stones[-1] - stones[1], stones[-2] - stones[0]) - inner

        # minimum:
        # find the range with the most stones
        low  = +inf
        left = 0
        for right, s in enumerate(stones):
            while s - stones[left] > size - 1:
                left += 1
            moves = size - (right - left + 1)

            # final move can be tricky if all stones are consecutive except an endpoint:
            # abcdef...g
            if moves == 1 and s - stones[left] == inner:
                moves = inner

            low = min(low, moves)

        return [ low, high ]
28 lines | 973 bytes | submitted July 18, 2024 | GitHub   43% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (20k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Sliding Window
  • Sorting
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.numMovesStonesII method computes the minimum and maximum number of moves required to arrange a set of stones on a number line into a consecutive sequence. The algorithm first sorts the input positions, then derives the maximum move count using a simple range calculation, and finally determines the minimum move count through a sliding-window scan that identifies the densest sub-interval of stones. Edge-case handling is embedded in the window logic, and the implementation achieves linear time performance after the initial sort.

Sorting and Basic Variables

The method begins by ordering the stone positions, which guarantees that subsequent index arithmetic reflects true distances on the line.

stones.sort()
size  = len(stones)
inner = size - 2

size stores the total number of stones, while inner represents the count of stones that are not at either endpoint of the final consecutive block. These values are reused throughout the computation, avoiding repeated length calculations.

Computing the Maximum Number of Moves

The maximum move count is derived from the observation that the worst case occurs when the largest empty gap lies adjacent to one of the endpoints. By moving a stone next to that endpoint and then shifting the endpoint toward the opposite side, the algorithm captures the worst-case scenario in constant time.

high = max(stones[-1] - stones[1], stones[-2] - stones[0]) - inner

Here stones[-1] - stones[1] measures the span from the rightmost stone to the second leftmost stone, and stones[-2] - stones[0] measures the span from the second rightmost stone to the leftmost stone. Subtracting inner yields the number of moves needed to fill the largest gap while keeping the endpoints fixed.

Sliding-Window Scan for the Minimum Moves

The core of the minimum-move calculation is a sliding window that expands to include as many stones as possible within a window of length size - 1. The window is defined by two indices, left and right, where right iterates over the sorted stones.

low  = +inf
left = 0
for right, s in enumerate(stones):
    while s - stones[left] > size - 1:
        left += 1
    moves = size - (right - left + 1)

    if moves == 1 and s - stones[left] == inner:
        moves = inner

    low = min(low, moves)

Window Expansion

The inner while loop contracts the left side of the window whenever the current span exceeds the allowed length (size - 1). This ensures that the window always represents a feasible interval that could become consecutive after moving the remaining stones.

Move Count Derivation

moves is calculated as the total number of stones minus the count already fitting inside the current window (right - left + 1). This directly yields the number of stones that must be relocated to achieve a consecutive block.

Special-Case Adjustment

When the algorithm encounters a situation where exactly one stone lies outside a nearly consecutive block (moves == 1) and the span of the window equals inner, it recognizes the pattern abcdef...g where all interior stones are already consecutive and only an endpoint is isolated. In this configuration, a single move cannot close the gap; instead, the isolated endpoint must travel across the entire interior, requiring inner moves. The conditional block replaces the naïve count of 1 with inner to reflect this reality.

Minimum Selection

low retains the smallest move count observed across all window positions, guaranteeing that the final result reflects the optimal strategy.

Edge-Case Handling

The algorithm explicitly addresses the scenario where the stones are already consecutive except for one endpoint. The conditional adjustment inside the loop detects this pattern and substitutes the correct move count, preventing an underestimation of the required steps.

Another implicit edge case is the situation where all stones are already consecutive. In that case, the sliding window will eventually cover the entire array, yielding moves = 0, and low will be set to zero, correctly indicating that no moves are needed.

Performance Optimizations

The method achieves linear traversal after sorting by maintaining a single moving pointer (left) that never retreats. This monotonic advancement eliminates the need for nested loops and ensures that each stone index is examined at most twice-once as the right boundary and once as the left boundary. The use of pre-computed constants (size, inner) avoids repeated attribute lookups inside the loop, reducing overhead.

Sorting dominates the runtime, but the subsequent O(n) scan is optimal for the problem’s constraints. Memory usage is minimal, relying only on a few integer variables and the sorted input list, thereby keeping the footprint low.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a row of colorful pebbles sitting on a long wooden track. Some pebbles are close together, and some have big gaps between them. The goal is to slide these pebbles along the track until they are all sitting right next to each other in one solid line.

First, think about the easiest way to make a solid line. You sort all the pebbles by their position from smallest to largest so they are in order. To find the biggest number of moves, you look at the gap between the pebbles on the far ends. You pick up a pebble that is far away and move it slowly toward the others, one space at a time. This takes the most effort because you have to make many small jumps to bridge the wide gap.

To find the smallest number of moves, you look for a group of pebbles that are already somewhat close to each other. You want to surround these pebbles with the others you have. You slide the ones that are furthest away toward this cozy group. By carefully watching how many spaces are open, you calculate how many slides it takes to fill those empty spots. Sometimes there is a special tricky case where a pebble is almost in the right place but sits just one step away, and that requires a little extra attention to finish the line. You keep track of how many moves this group takes and pick the smallest total. By looking at all the possible groups to squeeze together, you find the quickest way to turn the scattered pebbles into one neat row.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.56 | σ = 1.55

Complexity Analysis

Time: loglinear
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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
suxrobGM C#
wisdompeak C++
28 links | 14 authors | 7 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

3 solutions   July 18, 2024

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