Moving Stones Until Consecutive

medium math sorting simulation

Problem

Three stones sit at distinct integer positions a, b, c on a number line. In one move you take a stone from an endpoint position (the smallest or largest) and place it at any empty integer position strictly between the other two stones. The game ends when the three stones are consecutive (e.g. 4, 5, 6). Return the minimum and maximum number of moves.

Inputa = 1, b = 2, c = 5
Output[1, 2]
Min: move 5 → 3 to get 1, 2, 3 (one move). Max: move 5 → 4, then 1 → 3 (two moves).

def num_moves_stones(a, b, c):
    x, y, z = sorted([a, b, c])
    left = y - x - 1
    right = z - y - 1
    if left == 0 and right == 0:
        return [0, 0]
    mn = 1 if (left <= 1 or right <= 1) else 2
    mx = left + right
    return [mn, mx]
function numMovesStones(a, b, c) {
  const [x, y, z] = [a, b, c].sort((p, q) => p - q);
  const left = y - x - 1;
  const right = z - y - 1;
  if (left === 0 && right === 0) return [0, 0];
  const mn = (left <= 1 || right <= 1) ? 1 : 2;
  const mx = left + right;
  return [mn, mx];
}
class Solution {
    public int[] numMovesStones(int a, int b, int c) {
        int[] s = { a, b, c };
        Arrays.sort(s);
        int left = s[1] - s[0] - 1;
        int right = s[2] - s[1] - 1;
        if (left == 0 && right == 0) return new int[]{ 0, 0 };
        int mn = (left <= 1 || right <= 1) ? 1 : 2;
        int mx = left + right;
        return new int[]{ mn, mx };
    }
}
vector<int> numMovesStones(int a, int b, int c) {
    int s[3] = { a, b, c };
    sort(s, s + 3);
    int left = s[1] - s[0] - 1;
    int right = s[2] - s[1] - 1;
    if (left == 0 && right == 0) return { 0, 0 };
    int mn = (left <= 1 || right <= 1) ? 1 : 2;
    int mx = left + right;
    return { mn, mx };
}
Time: O(1) Space: O(1)