The Moving Stones Until Consecutive II problem generalizes the three-stone problem to n stones. You move an endpoint stone to any unoccupied position (not necessarily between stones), and the goal is to make all stones consecutive. Find the minimum and maximum number of moves. This coding problem uses sliding window for the minimum and a formula for the maximum.
Meta asks this medium problem because it extends the brainteaser into a more algorithmic challenge requiring sliding window techniques. The maximum moves formula is straightforward but the minimum requires carefully finding the longest window already containing a run of consecutive positions. The array, math, sorting, and sliding window interview pattern is applied.
Sorting + maximum formula + sliding window for minimum.
max(stones[-1] - stones[-2] - 1, stones[1] - stones[0] - 1) + n - 2. (Move either the leftmost or rightmost stone optimally.)stones[j] - stones[i] ≤ n-1, count how many stones are already in the window. Minimum moves = n - max(stones in any window). Special case: when the window is n-1 long (almost full) but has one gap, min might need +1.Stones: [7, 4, 9]. Sorted: [4, 7, 9]. n=3.
Two-complexity problems (min and max) often require independent algorithms for each part. Practice them separately: compute max with the formula, then tackle min with sliding window. The sliding window minimum count approach — find the window of n positions containing the most existing stones — generalizes to other "pack n items into the smallest window" problems. Practice both formulas until they become second nature.