#1040
Moving Stones Until Consecutive II
MediumArrayMathSliding WindowSortingSortingGap Analysis
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal solution leverages sorting and gap analysis to quickly determine the minimum and maximum moves required to achieve three consecutive stones. This method is efficient and avoids unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Sort the stones array.
- 2Step 2: Calculate the minimum moves by checking how many stones are already in consecutive positions and how many moves are needed to fill the gaps.
- 3Step 3: For maximum moves, consider the largest gaps at the ends of the sorted array and calculate how many stones can be moved into those gaps.
solution.py5 lines
1def numMovesStonesII(stones):
2 stones.sort()
3 min_moves = max(0, 2 - (stones[-1] - stones[0] + 1 - len(stones)))
4 max_moves = max(stones[-1] - stones[-2] - 1, stones[1] - stones[0] - 1)
5 return [min_moves, max_moves]ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, which is efficient for the input size constraints.
- 1Understanding the concept of endpoint stones is crucial to solving the problem effectively.
- 2The relationship between gaps and the number of moves needed to fill them is key to determining both minimum and maximum moves.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.