Moving Stones Until Consecutive II — LeetCode 1040 Python Solution
MediumArrayMathSortingSliding Window
- Problem
- #1040
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones.
Example
- Input
- stones = [7,4,9]
- Output
- [1,2]
- Explanation
- We can move 4 -> 8 for one move to finish the game.
Python solution
Python
class Solution:
def numMovesStonesII(self, stones: List[int]) -> List[int]:
stones.sort()
mi = n = len(stones)
mx = max(stones[-1] - stones[1] + 1, stones[-2] - stones[0] + 1) - (n - 1)
i = 0
for j, x in enumerate(stones):
while x - stones[i] + 1 > n:
i += 1
if j - i + 1 == n - 1 and x - stones[i] == n - 2:
mi = min(mi, 2)
else:
mi = min(mi, n - (j - i + 1))
return [mi, mx]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1040. Moving Stones Until Consecutive II is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1040. Moving Stones Until Consecutive II?
- LeetCode 1040. Moving Stones Until Consecutive II is rated Medium on LeetCode.
- What topics does LeetCode 1040. Moving Stones Until Consecutive II cover?
- LeetCode 1040. Moving Stones Until Consecutive II is tagged Array, Math, Sorting and Sliding Window on LeetCode.