Taro Logo

Minimum Number of Operations to Make Array Continuous

#153 Most AskedHard
Topics:
ArraysTwo PointersBinary Search

You are given an integer array nums. In one operation, you can replace any element in nums with any integer.

nums is considered continuous if both of the following conditions are fulfilled:

  • All elements in nums are unique.
  • The difference between the maximum element and the minimum element in nums equals nums.length - 1.

For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.

Return the minimum number of operations to make nums continuous.

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements in the input array `nums`, and can they include negative numbers and zeros?
  2. Can the input array contain duplicate values, and if so, do duplicate elements count as distinct elements when we try to make the array continuous?
  3. What is the minimum possible length of the input array `nums`? Can it be a single element?
  4. When we replace an element with 'any integer', are there any restrictions on what that integer can be, or can we reuse existing values?
  5. If the array is already continuous, should the function return 0 operations?

Brute Force Solution

Approach

To figure out the minimum number of changes needed to make a collection of numbers consecutive, the brute force approach involves testing every single possible sequence of consecutive numbers that could theoretically be formed. We then count how many changes each of those possibilities would require.

Here's how the algorithm would work step-by-step:

  1. First, look at the total count of items in your collection, because that tells you how long any valid consecutive sequence needs to be.
  2. Next, pick a starting number for your target consecutive sequence and imagine the full sequence of numbers that would follow it.
  3. Compare your imagined sequence against your actual collection of numbers to see how many items are missing.
  4. Count how many items you would need to add or change to make your actual collection match your imagined sequence.
  5. Repeat this process by picking a different starting number and imagining a new consecutive sequence.
  6. Do this for every possible starting number you can think of.
  7. Finally, compare the counts from all your tests and pick the one that required the fewest changes.

Code Implementation

def min_operations(nums):
    total_items = len(nums)
    minimum_operations = total_items

    # We test every unique number in the array as the potential starting point of our sequence
    for starting_number in nums:
        target_sequence_end = starting_number + total_items - 1
        current_missing_count = 0

        for sequence_element in range(starting_number, target_sequence_end + 1):
            if sequence_element not in nums:
                current_missing_count += 1

        # We track the smallest number of missing elements found across all tested target sequences
        if current_missing_count < minimum_operations:
            minimum_operations = current_missing_count

    return minimum_operations

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items in your collection serving as a starting number, we imagine a consecutive sequence of length n and compare it against the actual collection. Testing the first possible starting number requires scanning all n items, checking the second starting number requires scanning n items again, and we repeat this process for every possible starting number among the n items. This leads to approximately n * n operations, which simplifies to O(n²).
Space Complexity
O(n) – To determine the auxiliary space complexity, we look at the data structures required to filter and store the unique elements from the original collection of size n. Specifically, removing duplicates and sorting the numbers requires storing up to n elements in a temporary array or list. As the input size n grows, this auxiliary storage scales linearly to hold the distinct values for our sliding window comparisons. Consequently, the total extra memory consumed by the algorithm is directly proportional to the number of input items, simplifying to Big O of n.

Optimal Solution

Approach

To make a collection of numbers continuous and unique, we can visualize the goal as sliding a fixed-size window of consecutive numbers across all the unique values we were given. The optimal strategy finds the position where this window already captures the maximum possible numbers, meaning we only need to change the remaining numbers that fall outside the window.

Here's how the algorithm would work step-by-step:

  1. First, remove any duplicate numbers from your collection since a continuous sequence requires all distinct values.
  2. Sort the remaining unique numbers from smallest to largest so they are neatly ordered in a line.
  3. Determine the total count of numbers you started with, which tells you the exact span or width your continuous sequence must have.
  4. Imagine a sliding window of that exact width and move it across your sorted numbers from left to right.
  5. Count how many of your sorted numbers naturally fall inside this sliding window at each position.
  6. Track the maximum number of original values you manage to capture inside the window at any single placement.
  7. Calculate your final answer by taking the total count of numbers you started with and subtracting that maximum captured amount.

Code Implementation

def min_operations(nums):
    total_elements_count = len(nums)
    
    # Removing duplicates ensures all numbers in our sequence are strictly unique.
    sorted_unique_numbers = sorted(list(set(nums)))
    
    max_captured_elements = 0
    window_start_index = 0
    
    for window_end_index in range(len(sorted_unique_numbers)):
        # We shift the window left boundary until the span fits the total element count.
        while sorted_unique_numbers[window_end_index] - sorted_unique_numbers[window_start_index] >= total_elements_count:
            window_start_index += 1
            
        current_window_size = (window_end_index - window_start_index) + 1
        max_captured_elements = max(max_captured_elements, current_window_size)
        
    # Subtracting the max retained elements from total gives the minimum replacements needed.
    return total_elements_count - max_captured_elements

Big(O) Analysis

Time Complexity
O(n log n) – First, removing duplicates and sorting the n unique numbers takes O(n log n) time. Next, a two-pointer sliding window iterates through the sorted unique numbers, visiting each element at most twice, which takes O(n) time. The total operations are dominated by the sorting step, approximately n log n operations, which simplifies to O(n log n).
Space Complexity
O(N) – The space complexity is driven by the preprocessing steps applied to the original collection of numbers of size N. First, removing duplicate numbers and storing the unique values in a sorted list requires auxiliary data structures that can hold up to N elements in the worst-case scenario where all original numbers are already distinct. Additionally, standard sorting algorithms utilize internal memory or recursion stacks that scale with N. Therefore, the total extra memory required grows linearly with the size of the input.

Edge Cases

Array with a single element
How to Handle:
Return zero because a single-element array is already continuous by definition.
Array where all elements are already distinct and form a continuous range
How to Handle:
Return zero because no operations are needed since the condition is already met.
Array containing all identical elements
How to Handle:
Deduplicate the array and return length minus one since only one unique element can be kept.
Array containing negative numbers and zeros
How to Handle:
Sorting and sliding window naturally handle negative ranges and zero crossings without extra offset logic.
Array with elements already sorted in ascending order
How to Handle:
The sliding window efficiently scans the sorted unique elements without requiring a preliminary sort step overhead.
Array with extremely large values spanning beyond standard integer limits
How to Handle:
Use 64-bit integers for window difference calculations to prevent potential overflow during subtraction.
Maximum-sized inputs up to ten to the fifth elements
How to Handle:
Apply an O(N log N) sorting plus O(N) sliding window approach to ensure it executes well within time limits.
Array with heavily duplicated values leaving very few unique elements
How to Handle:
Deduplicating the array first ensures the sliding window only evaluates valid unique starting points.
0/245 completed