Magicsheet logo

Minimum Number of Operations to Make Array Continuous

Hard
12.5%
Updated 8/1/2025

Minimum Number of Operations to Make Array Continuous

1. What is this problem about?

The Minimum Number of Operations to Make Array Continuous interview question is a "Hard" difficulty problem involving sorting and range management. An array of length n is "continuous" if all its elements are unique and the difference between the maximum and minimum element is n-1. You can replace any element with any other integer. Your goal is to find the minimum number of replacements to make the array continuous.

2. Why is this asked in interviews?

Uber and Microsoft use this to test a candidate's ability to rephrase an optimization problem. The core question is: "What is the maximum number of elements from the original array that can be part of a continuous range?". Once you find that maximum (let's call it max_keep), the answer is simply n - max_keep.

3. Algorithmic pattern used

This utilizes the Array, Hash Table, Sliding Window, Binary Search interview pattern.

  1. Remove duplicates from the array (using a Hash Table or Set) and sort it.
  2. For each element array[i], imagine it is the start of the continuous range: [array[i], array[i] + n - 1].
  3. Use a Sliding Window or Binary Search to find how many elements of the unique/sorted array fall within this range.
  4. Keep track of the maximum number of elements found.
  5. Final answer is n - max.

4. Example explanation

Original: [4, 2, 5, 3], n=4 Sorted unique: [2, 3, 4, 5]

  1. Start at 2: Range is [2, 2+4-1] = [2, 5]. All 4 elements fit. Keep = 4.
  2. Result: 4 - 4 = 0 operations.

Original: [1, 2, 3, 5, 6], n=5 Sorted unique: [1, 2, 3, 5, 6]

  1. Start at 1: Range is [1, 5]. Elements [1, 2, 3, 5] fit. Keep = 4.
  2. Start at 2: Range is [2, 6]. Elements [2, 3, 5, 6] fit. Keep = 4. Result: 5 - 4 = 1 operation.

5. Common mistakes candidates make

A common mistake is not removing duplicates before processing, which leads to incorrect counts of how many unique elements fit in the n-1 span. Another error is trying to find the range using O(n^2) brute force instead of an O(n log n) binary search or O(n) sliding window.

6. Interview preparation tip

When asked for the "minimum changes to satisfy a range property," try to find the "maximum elements that already satisfy the property." This inversion of the problem often leads to much cleaner logic involving sorting and searching.

Similar Questions