Moving Stones Until Consecutive - Problem

There are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones.

In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, and z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y.

The game ends when you cannot make any more moves (i.e., the stones are in three 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: a = 1, b = 2, c = 5
Output: [1, 2]
💡 Note: Sorted positions: [1, 2, 5]. Gap between 2 and 5 is 2 spaces. Min: move stone at 5 to position 3 in 1 move. Max: fill gap by moving stones one by one, taking 2 moves total.
Example 2 — Already Close to Consecutive
$ Input: a = 4, b = 3, c = 2
Output: [0, 0]
💡 Note: Sorted positions: [2, 3, 4]. Already consecutive! No moves needed, so both min and max are 0.
Example 3 — Large Gaps
$ Input: a = 1, b = 9, c = 2
Output: [2, 6]
💡 Note: Sorted positions: [1, 2, 9]. Large gap of 6 between 2 and 9. Min: need 2 moves to make consecutive. Max: can make 6 moves by filling the gap gradually.

Constraints

  • 1 ≤ a, b, c ≤ 100
  • a, b, c are distinct integers

Visualization

Tap to expand
Moving Stones Until Consecutive INPUT 1 2 3 4 5 a b c gap=0 gap=2 Position Values: a = 1 b = 2 c = 5 Sorted: [1, 2, 5] endpoint endpoint Gap Analysis: gap1 = b - a - 1 = 0 gap2 = c - b - 1 = 2 total gap = 2 ALGORITHM STEPS 1 Sort positions Order: a=1, b=2, c=5 2 Check consecutive 1,2,5 not consecutive 3 Find minimum moves gap1=0 or gap2=1? min=1 4 Find maximum moves max = total gaps = 2 Minimum: Move c(5) to 3 1 2 3 1 move Maximum: Move one at a time Move 1: c(5)-->4 Move 2: c(4)-->3 2 moves FINAL RESULT Goal: Consecutive Positions 1 2 3 a b c OUTPUT [1, 2] Explanation: Minimum = 1 move Move stone at 5 to 3 Maximum = 2 moves 5-->4, then 4-->3 Key Insight: For MINIMUM: If any gap is 0 or 1, we need at most 1-2 moves. If gap=1 exists, move endpoint to that gap (1 move). For MAXIMUM: Move endpoint stones one position at a time = (gap1 + gap2) = total empty spaces between stones. Special case: If already consecutive, return [0, 0]. Two stones adjacent? At most 1 move needed. TutorialsPoint - Moving Stones Until Consecutive | Optimal Solution
Asked in
Google 12 Facebook 8
12.0K Views
Medium Frequency
~15 min Avg. Time
234 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