Minimum Operations to Make Array Continuous

Find the fewest values to replace so that an array holds consecutive numbers with no repeats.

You are given an array of integers nums of length n. The array is called continuous when all its values are different and the largest value minus the smallest value equals n - 1. In one operation you may replace any value in the array with any integer. Return the smallest number of operations that makes nums continuous.

Example 1
Input: nums = [4, 2, 5, 3]
Output: 0
Explanation: the values are different and 5 - 2 = 3, which is the length 4 minus 1.
Example 2
Input: nums = [1, 2, 3, 5, 6]
Output: 1
Explanation: replace 6 with 4, which gives the values 1 to 5.
Example 3
Input: nums = [1, 10, 100, 1000]
Output: 3
Explanation: keep 1 and replace the other three values with 2, 3 and 4.
Solution

The Idea

What does a continuous array look like? Sort Example 1 and it reads 2, 3, 4, 5: four different numbers, one after another, with no gap. That is no accident. Four different whole numbers that lie only 3 apart, smallest to largest, have no room for a gap. So a continuous array of length n is always a run of n consecutive numbers, in any order.

Now take Example 2, [1, 2, 3, 5, 6]. Its length is 5, so it must end up as five consecutive numbers. Replacing 6 with 4 gives 1, 2, 3, 4, 5, in one operation. But that is not the only choice. Replacing 1 and 2 with 4 and 7 gives 3, 4, 5, 6, 7, in two operations. So the real question is: which run of five numbers should the array become?

Each choice of run is a range on the number line. Look at the picture below. The top row is the range 1 to 5. The values 1, 2, 3 and 5 already lie inside it, so they stay. Only 6 lies outside, so it is replaced, and it fills the gap at 4.

The values 1, 2, 3, 5, 6 on a number line. The range 1 to 5 holds 1, 2, 3 and 5, so only 6 is replaced, filling the gap at 4. The range 3 to 7 holds 3, 5 and 6, so 1 and 2 are replaced, filling 4 and 7.

The bottom row is the range 3 to 7. It keeps only 3, 5 and 6, so 1 and 2 are replaced, and they fill the gaps at 4 and 7. Two operations instead of one.

So the operations are simply the values that do not fit. For a chosen range, the answer is n minus the number of values already inside it. Fewer operations means more values kept, so we look for the range of n consecutive numbers that already holds the most values of the array.

One detail: two equal values can never both stay, because the final values must all be different. In [7, 7, 7, 7] one 7 stays and the other three are replaced, so only different values count as kept.

Solution Approach

Turning that idea into code means settling three things: which ranges to try, how to count the values inside each range quickly, and how to deal with repeated values.

Which ranges to try

A range could start at any integer, so where do we look? Trying every start from the smallest value to the largest is too slow when the values are far apart: Example 3 already spans 1 to 1000 with only four values, and values can lie far further apart.

Fortunately, a best range can always start at a value of the array. Suppose a range starts at a number that is not in the array. Slide it right until its start reaches the smallest value it keeps. No kept value falls out on the left, since none lay below that value, and on the right the range only takes in more. So it is enough to try each different value v as a start, with the range v to v + n - 1.

Counting the values in each range

How do we count the values inside one range? The simple way scans the whole array for every start. That is n starts times n values, about 10 billion steps for an array of 100,000 values.

Sorting helps here. Once the different values are in increasing order, the values inside a range form a block of neighbours. The block begins at the start value and ends at the last value that is not past the range's end. Two markers track it: left points at the start value, and right stops just after the block, so the block holds right - left values.

When left moves to the next value, the range moves right too, so its end only grows. right therefore never has to move back; it only moves forward from where it stopped. Two markers that move the same way, where the stretch between them is what counts, are called a sliding window.

For Example 2, the different values are 1, 2, 3, 5, 6 and n is 5. With left on 1, the range is 1 to 5 and right stops just after 5, so 4 values fit. With left on 2, the range is 2 to 6, right moves past 6, and 4 values fit again. With left on 3, the range is 3 to 7, and only 3 values fit. The best is 4 kept, so 5 - 4 = 1 operation.

Repeated values

What happens to repeats? After sorting, equal values sit side by side, so one pass can keep each value once. The width of the range still uses n, the original length, because the final array still has n values. The copies that were dropped are not among the kept values, so n minus the number kept counts them as operations without any extra work.

Java Solution

The method minOperations works in these steps:

  1. First, store the original length in n, copy the array with nums.clone() into sorted, and sort the copy with Arrays.sort(sorted). The caller's array keeps its order.
  2. Remove repeats with one loop over sorted. unique counts the different values written so far, and a value is written to sorted[unique] only when it differs from the value before it. Afterwards, the first unique slots hold each value once, in increasing order.
  3. Set best to n, since replacing every value always works, and set right to 0. Then a loop moves left over the different values. Each one starts the range sorted[left] to sorted[left] + n - 1.
  4. Inside that loop, a while loop moves right forward as long as sorted[right] is inside the range. The values from left to right - 1 fit, so kept is right - left, and best takes n - kept when that is smaller.
  5. When the loop is done, return best.

The main method runs the three examples, then [1, 1, 3], where a repeat leaves room in the range, four equal values, and an array of a single value.

Java
import java.util.Arrays;

public class MimimumOperationsToMakeArrayContinuous {

    public static int minOperations(int[] nums) {
        int n = nums.length;
        int[] sorted = nums.clone();
        Arrays.sort(sorted);
        int unique = 0;
        for (int i = 0; i < n; i++) {
            if (i == 0 || sorted[i] != sorted[i - 1]) {
                sorted[unique++] = sorted[i];     // keep each value once, in order
            }
        }
        int best = n;
        int right = 0;
        for (int left = 0; left < unique; left++) {
            // the final range would be sorted[left] .. sorted[left] + n - 1
            while (right < unique && sorted[right] <= sorted[left] + n - 1) {
                right++;
            }
            int kept = right - left;
            best = Math.min(best, n - kept);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(minOperations(new int[] {4, 2, 5, 3}));
        System.out.println(minOperations(new int[] {1, 2, 3, 5, 6}));
        System.out.println(minOperations(new int[] {1, 10, 100, 1000}));
        System.out.println(minOperations(new int[] {1, 1, 3}));
        System.out.println(minOperations(new int[] {7, 7, 7, 7}));
        System.out.println(minOperations(new int[] {42}));
    }
}

Running it prints:

Output
0
1
3
1
3
0

The 0, 1 and 3 at the top match the three examples. In Example 3, no range of four consecutive numbers can hold two of 1, 10, 100 and 1000, so only one value stays.

Look at the fourth line, 1, from [1, 1, 3]. The different values are 1 and 3, but the range still covers n = 3 numbers, 1 to 3. Both values fit, and the second 1 becomes 2. This is why the width uses n and not unique. With unique, the range would be 1 to 2, it would miss 3, and the same input prints 2.

The fifth line, 3, is [7, 7, 7, 7]: one 7 stays and the copies are replaced, for example with 8, 9 and 10. The last line is 0, because a single value is already continuous: 42 - 42 = 0, which is the length 1 minus 1.

Complexity

The work is the sort, plus two passes over the sorted copy.

  • Time: O(n log n), where n is the length of the array. Arrays.sort on the copy takes O(n log n). Removing repeats is one pass, and in the window pass right only moves forward, so the two loops together take O(n) steps.
  • Space: O(n). The sorted copy has n slots, and removing repeats reuses it, so nothing else grows with the input.

A window whose right end only moves forward also drives Minimum Size Subarray Sum.