Moving Stones Until Consecutive II - Problem

Imagine you have stones scattered along a number line. Your goal is to move them until they form consecutive positions (like 5, 6, 7).

Here's the catch: You can only move endpoint stones - the leftmost or rightmost stones in your collection. When you move a stone, it must land in an unoccupied position and no longer be an endpoint.

For example, with stones at [1, 2, 5], you cannot move the stone at position 5 anywhere because it would still remain the rightmost stone!

The puzzle ends when all stones are in consecutive positions. Your task is to find both the minimum and maximum number of moves possible.

Input: An integer array stones representing positions on the X-axis

Output: An array [min_moves, max_moves]

Input & Output

example_1.py โ€” Basic Case
$ Input: stones = [7,4,9]
โ€บ Output: [1,2]
๐Ÿ’ก Note: We can move 4 to 8 to get [7,8,9] in 1 move (minimum). For maximum, we can move 4 to 6, then 7 to 8 to get [6,8,9], then 6 to 7 for [7,8,9] (2 moves total).
example_2.py โ€” Larger Gap
$ Input: stones = [6,5,4,3,10]
โ€บ Output: [2,3]
๐Ÿ’ก Note: We can move 3 to 8, then 10 to 7 to get [4,5,6,7,8]. The minimum is 2 moves, maximum is 3 moves by creating larger gaps first.
example_3.py โ€” Already Consecutive
$ Input: stones = [1,2,3,4,5]
โ€บ Output: [0,0]
๐Ÿ’ก Note: The stones are already in consecutive positions, so no moves are needed for both minimum and maximum.

Constraints

  • 3 โ‰ค stones.length โ‰ค 104
  • 1 โ‰ค stones[i] โ‰ค 109
  • All values in stones are unique
  • At least 3 stones are required for the game to be interesting

Visualization

Tap to expand
Moving Stones Strategy VisualizationInitial: [7, 4, 9] โ†’ Sorted: [4, 7, 9]479Minimum Strategy: Sliding WindowWindow [7,8,9]: has 2 stonesMove 4 โ†’ 8: Final [7,8,9] in 1 moveMaximum Strategy: Maximize GapsMove 4 โ†’ 6Move 7 โ†’ 8Result: [6,8,9] โ†’ [7,8,9] in 2 movesAnswer: [1, 2] - minimum and maximum moves
Understanding the Visualization
1
Sort the Positions
First, arrange stones by position to see the current layout clearly
2
Find Best Window
Use sliding window to find where n consecutive positions would capture the most existing stones
3
Calculate Minimum
Minimum moves = n - (stones already in best window)
4
Calculate Maximum
For maximum, choose the endpoint move that leaves the largest gap
Key Takeaway
๐ŸŽฏ Key Insight: Separate minimum and maximum strategies - sliding window finds efficient packing, while greedy maximizes gaps before convergence.
Asked in
Google 15 Meta 12 Apple 8 Amazon 6
31.2K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen