We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Operations to Make the Array Increasing

Number: 1938

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Deutsche Bank


Problem Description

Given an integer array nums, determine the minimum number of operations needed to make the array strictly increasing. In one operation, you can choose an element of the array and increment it by 1. The array is strictly increasing if for every 0 ≤ i < nums.length - 1, nums[i] < nums[i+1]. An array of size 1 is trivially strictly increasing.


Key Insights

  • The array must satisfy nums[i] < nums[i+1] for all valid indices.
  • When nums[i] is less than or equal to nums[i-1], it must be increased to nums[i-1] + 1.
  • A greedy approach can be used by iterating through the array and adjusting each element as needed.
  • The total number of operations is the sum of all the individual adjustments.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the nums array since we iterate through the array once. Space Complexity: O(1) because we only use a constant amount of extra space.


Solution

We iterate through the array starting from the second element. For each element, if it is less than or equal to its previous element, we calculate the necessary increment (i.e., nums[i-1] + 1 - nums[i]) to make it strictly greater. We add the calculated difference to the total operations count and update the element in the array. This greedy approach ensures that after processing each element, the array remains strictly increasing.


Code Solutions

# Function to calculate the minimum operations to make the array strictly increasing
def min_operations(nums):
    operations = 0
    # Iterate over the array starting from the second element
    for i in range(1, len(nums)):
        # If the current element is not greater than its previous element, adjust it
        if nums[i] <= nums[i - 1]:
            needed = nums[i - 1] + 1 - nums[i]  # Calculate required increments
            operations += needed              # Add to total operations
            nums[i] += needed                 # Update current element
    return operations

# Example usage:
print(min_operations([1, 1, 1]))  # Expected output: 3
← Back to All Questions