Minimum Number of Operations to Make Array Continuous

Updated on 19 June, 2025
Minimum Number of Operations to Make Array Continuous header image

Problem Statement

In this problem, we are provided with an array of integers, named nums. Our goal is to make this array "continuous" through a series of operations. An operation consists of replacing any element in the array with any integer. An array is deemed continuous if it satisfies two criteria:

  • All elements within the array are distinct.
  • The difference between the maximum and minimum elements in the array equals the length of the array minus one.

Our task is to determine the minimum number of operations required to transform the given array into a continuous one.

Examples

Example 1

Input:

nums = [4,2,5,3]

Output:

0

Explanation:

 nums is already continuous.

Example 2

Input:

nums = [1,2,3,5,6]

Output:

1

Explanation:

 One possible solution is to change the last element to 4.
The resulting array is [1,2,3,5,4], which is continuous.

Example 3

Input:

nums = [1,10,100,1000]

Output:

3

Explanation:

 One possible solution is to:
- Change the second element to 2.
- Change the third element to 3.
- Change the fourth element to 4.
The resulting array is [1,2,3,4], which is continuous.

Constraints

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Approach and Intuition

The problem of making an array continuous hinges on understanding two primary conditions: the uniqueness of elements and the specific range they must occupy.

  1. Understanding Uniqueness:

    • Firstly, ensure that no two elements in the array nums are the same. This might require changing some values if there are duplicates.
  2. Determining the Range:

    • The target range for the elements is derived from the condition max - min = nums.length - 1. This implies if the smallest value in the array (after ensuring uniqueness) is min, then the array should contain all numbers from min to min + nums.length - 1.
  3. Approach Breakdown:

    • Sorting and Duplication: Begin by sorting the array to easily identify and handle duplicates.
    • Window Sliding Technique: Use a sliding window to determine a subarray that is already continuous or close to continuous. The size of the window will be affected by ensuring we maintain the length nums.length between the minimum and maximum values within it.
    • Counting Changes: The minimum number of operations would then be defined by how many numbers outside this identified subarray need replacing to extend or shift this subarray to fulfill the continuity condition.

This methodology leans on efficiently counting and modifying elements to stitch together a continuous range within the array, minimizing the number of alterations required. Each step, from handling duplicates to dynamically adjusting the range of the sliding window, is geared towards constructing an array that adheres to the definition of being continuous.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int minimumOperations(vector<int>& nums) {
        int length = nums.size();
        int result = length;
        
        set<int> sortedUnique(nums.begin(), nums.end());
        vector<int> compressedNums(sortedUnique.begin(), sortedUnique.end());
        
        int right = 0;
        for (int left = 0; left < compressedNums.size(); left++) {
            while (right < compressedNums.size() && compressedNums[right] < compressedNums[left] + length) {
                right++;
            }
            
            int cnt = right - left;
            result = min(result, length - cnt);
        }
        
        return result;
    }
};

The code provided for solving the problem "Minimum Number of Operations to Make Array Continuous" in C++ involves a series of steps to calculate the minimum number of modifications required to make the elements of an array form a continuous series.

  • Initially, the size of the given array nums is stored in the variable length, and this variable is also initialized to result which eventually will hold the minimum number of operations.
  • Use a set to remove duplicates and sort nums. The sorted and unique elements are then transferred into a vector named compressedNums.
  • Two pointers approach is used here, one (left) iterating through the compressedNums and the other (right) trying to find the maximum range [left, right] such that all elements within this range are less than compressedNums[left] + length.
  • For each position left, adjust right such that compressedNums[right] is less than compressedNums[left] + length. Calculate the number of elements (cnt) within this [left, right) range.
  • The variable result is updated with the minimum value of itself and length - cnt which represents the number of operations needed for this particular subarray to meet the criteria.
  • At the end, result stores the minimal number of operations required, and it is returned.

With this approach, utilize two pointers effectively to minimize traversals and ensure efficiency in generating the result, thus optimizing the solution for large arrays.

java
class Solution {
    public int minTransformations(int[] elements) {
        int count = elements.length;
        int finalCount = count;
        
        HashSet<Integer> uniqElements = new HashSet<>();
        for (int element : elements) {
            uniqElements.add(element);
        }
        
        int[] distinctElements = new int[uniqElements.size()];
        int currentIndex = 0;
        
        for (int val : uniqElements) {
            distinctElements[currentIndex++] = val;
        }

        Arrays.sort(distinctElements);
        
        int end = 0;
        for (int start = 0; start < distinctElements.length; start++) {
            while (end < distinctElements.length && distinctElements[end] < distinctElements[start] + count) {
                end++;
            }

            int totalValid = end - start;
            finalCount = Math.min(finalCount, count - totalValid);
        }
        
        return finalCount;
    }
}

The solution provided solves the problem of finding the minimum number of operations required to make an array continuous. This Java solution involves the following steps:

  1. Initialize a variable to store the length of the input array elements.
  2. Create a HashSet to determine and store the unique elements from the array.
  3. Convert the HashSet to an array and sort it for easier processing.
  4. Use a sliding window approach to determine the maximum number of contiguous elements that can be formed within a range of the sorted unique elements.
  5. Calculate the minimum operations needed by subtracting the size of the largest contiguous subsequence found from the total number of unique elements.
  6. Return the calculated minimum operations.

The approach efficiently reduces the complexity by focusing only on the unique elements and leveraging the sorted property to use a two-pointer technique, ensuring that the operations required to make the array continuous are minimized.

python
class Solution:
    def calculateMinimumOperations(self, numbers: List[int]) -> int:
        count_numbers = len(numbers)
        result = count_numbers
        unique_sorted_numbers = sorted(set(numbers))
        pointer = 0
        
        for index in range(len(unique_sorted_numbers)):
            while pointer < len(unique_sorted_numbers) and unique_sorted_numbers[pointer] < unique_sorted_numbers[index] + count_numbers:
                pointer += 1
            
            count = pointer - index
            result = min(result, count_numbers - count)

        return result

The given Python code defines a method to calculate the minimum number of operations required to make an array continuous. Here is a concise step-by-step explanation of the implemented logic:

  1. Retrieve and store the length of the provided number array.
  2. Initialize the variable result with the length of the array. This variable will eventually hold the minimum number of operations needed.
  3. Remove duplicates from the array and sort the unique values for efficient processing.
  4. Use two pointers, index and pointer, to iterate through the unique and sorted array. Here, index is used in the outer loop to select each number sequentially, and pointer is used in the inner loop to find how many sequential numbers (counting up from the current number) can fit within the span defined by the array length.
  5. Inside the inner loop, increment the pointer until the element at the pointer position exceeds the current number at index position plus the length of the original array.
  6. Calculate the count of continuous numbers by subtracting index from pointer.
  7. Update result to store the lesser value between result and the difference between the original array length and the count from the previous step.
  8. The method ends by returning result, representing the minimum number of operations needed to make the array continuous.

This code leverages sorting and a two-pointer technique to efficiently find the minimum operations required, offering an optimized solution for the problem.

Comments

No comments yet.