MediumNo. 1033

Moving Stones Until Consecutive — LeetCode 1033 Python Solution

Topics
Brainteaser, Math
Reading time
2 min

The 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.

Example

Input
a = 1, b = 2, c = 5
Output
[1,2]
Explanation
Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.

Python solution

PythonSolution
class Solution:
    def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
        x, z = min(a, b, c), max(a, b, c)
        y = a + b + c - x - z
        mi = mx = 0
        if z - x > 2:
            mi = 1 if y - x < 3 or z - y < 3 else 2
            mx = z - x - 2
        return [mi, mx]

Complexity

Time
O(n) or O(1)
Space · auxiliary
O(1)

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1033. Moving Stones Until Consecutive is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1040Moving Stones Until Consecutive IIMedium
0292Nim GameEasy
0319Bulb SwitcherMedium
2396Strictly Palindromic NumberMedium
1037Valid BoomerangEasy
1041Robot Bounded In CircleMedium

Frequently asked questions

How hard is LeetCode 1033. Moving Stones Until Consecutive?

LeetCode 1033. Moving Stones Until Consecutive is rated Medium on LeetCode.

What topics does LeetCode 1033. Moving Stones Until Consecutive cover?

LeetCode 1033. Moving Stones Until Consecutive is tagged Brainteaser and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.