Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones.
Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.
stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone.The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).
Return an integer array answer of length 2 where:
answer[0] is the minimum number of moves you can play, andanswer[1] is the maximum number of moves you can play.Example 1:
Input: stones = [7,4,9] Output: [1,2] Explanation: We can move 4 -> 8 for one move to finish the game. Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.
Example 2:
Input: stones = [6,5,4,3,10] Output: [2,3] Explanation: We can move 3 -> 8 then 10 -> 7 to finish the game. Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.
Constraints:
3 <= stones.length <= 1041 <= stones[i] <= 109stones are unique.Problem summary: There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones. Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone. In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where: answer[0] is the minimum number of moves you can play, and answer[1] is the maximum number of moves you can play.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Sliding Window
[7,4,9]
[6,5,4,3,10]
minimum-number-of-operations-to-make-array-continuous)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1040: Moving Stones Until Consecutive II
class Solution {
public int[] numMovesStonesII(int[] stones) {
Arrays.sort(stones);
int n = stones.length;
int mi = n;
int mx = Math.max(stones[n - 1] - stones[1] + 1, stones[n - 2] - stones[0] + 1) - (n - 1);
for (int i = 0, j = 0; j < n; ++j) {
while (stones[j] - stones[i] + 1 > n) {
++i;
}
if (j - i + 1 == n - 1 && stones[j] - stones[i] == n - 2) {
mi = Math.min(mi, 2);
} else {
mi = Math.min(mi, n - (j - i + 1));
}
}
return new int[] {mi, mx};
}
}
// Accepted solution for LeetCode #1040: Moving Stones Until Consecutive II
func numMovesStonesII(stones []int) []int {
sort.Ints(stones)
n := len(stones)
mi := n
mx := max(stones[n-1]-stones[1]+1, stones[n-2]-stones[0]+1) - (n - 1)
i := 0
for j, x := range stones {
for x-stones[i]+1 > n {
i++
}
if j-i+1 == n-1 && stones[j]-stones[i] == n-2 {
mi = min(mi, 2)
} else {
mi = min(mi, n-(j-i+1))
}
}
return []int{mi, mx}
}
# Accepted solution for LeetCode #1040: Moving Stones Until Consecutive II
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]
// Accepted solution for LeetCode #1040: Moving Stones Until Consecutive II
struct Solution;
impl Solution {
fn num_moves_stones_ii(mut stones: Vec<i32>) -> Vec<i32> {
stones.sort_unstable();
let n = stones.len();
let mut min = n as i32;
let mut max = 0;
max = max.max(stones[n - 1] - stones[1] + 1 - n as i32 + 1);
max = max.max(stones[n - 2] - stones[0] + 1 - n as i32 + 1);
let mut l = 0;
for r in 0..n {
while stones[r] - stones[l] + 1 > n as i32 {
l += 1;
}
let d = r - l + 1;
if d == n - 1 && stones[r] - stones[l] + 1 == n as i32 - 1 {
min = min.min(2);
} else {
min = min.min((n - d) as i32);
}
}
vec![min, max]
}
}
#[test]
fn test() {
let stones = vec![7, 4, 9];
let res = vec![1, 2];
assert_eq!(Solution::num_moves_stones_ii(stones), res);
let stones = vec![6, 5, 4, 3, 10];
let res = vec![2, 3];
assert_eq!(Solution::num_moves_stones_ii(stones), res);
let stones = vec![100, 101, 104, 102, 103];
let res = vec![0, 0];
assert_eq!(Solution::num_moves_stones_ii(stones), res);
}
// Accepted solution for LeetCode #1040: Moving Stones Until Consecutive II
function numMovesStonesII(stones: number[]): number[] {
stones.sort((a, b) => a - b);
const n = stones.length;
let mi = n;
const mx = Math.max(stones[n - 1] - stones[1] + 1, stones[n - 2] - stones[0] + 1) - (n - 1);
for (let i = 0, j = 0; j < n; ++j) {
while (stones[j] - stones[i] + 1 > n) {
++i;
}
if (j - i + 1 === n - 1 && stones[j] - stones[i] === n - 2) {
mi = Math.min(mi, 2);
} else {
mi = Math.min(mi, n - (j - i + 1));
}
}
return [mi, mx];
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.