1113. Moving Stones Until Consecutive II
My accepted Python solution to LeetCode problem 1113, Moving Stones Until Consecutive II, running in 14ms.
- Difficulty: Medium
- Python
- Runtime 14ms
- Memory 18.2MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 14ms, memory 18.2MB, accepted 2026-01-02.
class Solution:
def numMovesStonesII(self, stones: List[int]) -> List[int]:
stones.sort()
n = len(stones)
# Maximum moves: fill all gaps except one endpoint
# Either skip first gap or skip last gap
max_moves = max(stones[n-1] - stones[1] - n + 2,
stones[n-2] - stones[0] - n + 2)
# Minimum moves: use sliding window
min_moves = n
j = 0
for i in range(n):
# Find window [stones[j], stones[i]] that can fit n consecutive stones
while stones[i] - stones[j] >= n:
j += 1
# Number of stones in window [j, i]
window_stones = i - j + 1
# Special case: if all stones in window are consecutive
# and we need only 1 more stone at the end
if window_stones == n - 1 and stones[i] - stones[j] == n - 2:
min_moves = min(min_moves, 2)
else:
min_moves = min(min_moves, n - window_stones)
return [min_moves, max_moves]