#1033

Moving Stones Until Consecutive

Medium
MathBrainteaserSortingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution leverages the gaps between the stones to determine the minimum and maximum moves efficiently without unnecessary iterations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the positions of the stones.
  2. 2Step 2: Calculate the gaps between the stones.
  3. 3Step 3: Determine the minimum moves based on the gaps.
  4. 4Step 4: Calculate the maximum moves based on the total distance.
solution.py11 lines
1def numMovesStones(a, b, c):
2    positions = sorted([a, b, c])
3    min_moves = 0
4    max_moves = positions[2] - positions[0] - 2
5    if max_moves == 0:
6        return [0, 0]
7    if positions[1] - positions[0] <= 2 or positions[2] - positions[1] <= 2:
8        min_moves = 1
9    else:
10        min_moves = 2
11    return [min_moves, max_moves]

Complexity note: The complexity remains constant as we perform a fixed number of operations regardless of the input size.

  • 1The maximum number of moves is determined by the total distance between the stones minus 2.
  • 2The minimum number of moves depends on the gaps between the stones and can be as low as 0 or 1.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.