Moving Stones Until Consecutive II - Problem

There are some stones in different positions on the X-axis. You are given an integer array stones where stones[i] represents the position of the i-th stone.

Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.

For example, if the stones are at positions [1,2,5], you cannot move the endpoint stone at position 5 to position 3 or 4 because it would still be an endpoint stone.

The game ends when you cannot make any more moves (i.e., the stones are in consecutive positions). Return an integer array answer of length 2 where:

  • answer[0] is the minimum number of moves you can play
  • answer[1] is the maximum number of moves you can play

Input & Output

Example 1 — 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 [8,9,10], taking 2 moves total.
Example 2 — Already Consecutive
$ Input: stones = [6,5,4,3,10]
Output: [2,3]
💡 Note: For minimum: move 3 to 7 and 10 to 8 to get [4,5,6,7,8]. For maximum: avoid the larger gap by keeping either [3,4,5,6] or [5,6,7,8,9,10] pattern.
Example 3 — Large Gaps
$ Input: stones = [1,3,8]
Output: [1,2]
💡 Note: Minimum: move 1 to 7 to get [3,7,8], then move endpoint to make consecutive. Maximum: move 8 to 2, then 3 to get larger sequence.

Constraints

  • 3 ≤ stones.length ≤ 104
  • 1 ≤ stones[i] ≤ 109

Visualization

Tap to expand
Moving Stones Until Consecutive IINumber Line479endpointmiddleendpointGoal: Move endpoints to make consecutive stones789Consecutive ResultMove 4→8Output: [1, 2] - minimum 1 move, maximum 2 moves
Understanding the Visualization
1
Input
Stones at positions [7,4,9] on number line
2
Rules
Only endpoint stones (smallest/largest position) can be moved
3
Goal
Make all stones consecutive with minimum and maximum moves
Key Takeaway
🎯 Key Insight: Use sliding window for minimum moves and gap analysis for maximum moves
Asked in
Google 15 Amazon 12 Facebook 8
18.8K Views
Medium Frequency
~35 min Avg. Time
425 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