Taro Logo

Minimum Operations to Make the Array Increasing

#146 Most AskedEasy
0 views
Topics:
ArraysGreedy Algorithms

You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.

  • For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].

Return the minimum number of operations needed to make nums strictly increasing.

An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.

Example 1:

Input: nums = [1,1,1]
Output: 3
Explanation: You can do the following operations:
1) Increment nums[2], so nums becomes [1,1,2].
2) Increment nums[1], so nums becomes [1,2,2].
3) Increment nums[2], so nums becomes [1,2,3].

Example 2:

Input: nums = [1,5,2,4,1]
Output: 14

Example 3:

Input: nums = [8]
Output: 0

Constraints:

  • 1 <= nums.length <= 5000
  • 1 <= nums[i] <= 104

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 expected behavior and return value for an empty array or an array with a single element?
  2. Can the array contain negative numbers and zeros, or are we strictly dealing with positive integers?
  3. What is the maximum size (length) of the input array `nums`, and what are the value ranges for the elements inside it?
  4. Are duplicate values allowed in the input array, and how should they be handled to satisfy the strictly increasing condition?
  5. Could the total number of operations exceed the capacity of a standard 32-bit integer, and should I use 64-bit integers (longs) for the return value?

Brute Force Solution

Approach

Imagine you have a line of numbered items and you want to make sure every single item is strictly larger than the one right before it by changing their values. The brute force approach involves going through the line step by step and manually adding to smaller items until the whole line strictly increases, while exhaustively checking and trying every possible adjustment.

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

  1. Begin by looking at the very first item in the line.
  2. Move to the next item and check if it is already strictly bigger than the item immediately preceding it.
  3. If the current item is smaller than or equal to the previous item, keep adding to its value until it becomes just barely larger than the previous one.
  4. Count every single addition you make as a move.
  5. Repeat this checking and adjusting process for every subsequent item all the way to the end of the line.
  6. Keep a running total of all the adjustments you had to make across the entire line.
  7. Once you reach the final item and every single item is strictly larger than its predecessor, your total count of adjustments is the answer.

Code Implementation

def min_operations(nums):
    total_operations = 0
    
    # We start from the second element because the first element has no predecessor to compare against
    for current_index in range(1, len(nums)):
        if nums[current_index] <= nums[current_index - 1]:
            difference = nums[current_index - 1] - nums[current_index]
            adjustment = difference + 1
            nums[current_index] += adjustment
            total_operations += adjustment
            
        # We exhaustively step through each potential adjustment to simulate the brute force process
        while nums[current_index] <= nums[current_index - 1]:
            nums[current_index] += 1
            total_operations += 1
            
    # Once we iterate through the entire sequence, the total operations accumulated represents our final answer
    return total_operations

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single pass through the array of size n to check and adjust each item relative to its predecessor. For each of the n elements, we perform a constant number of comparison and arithmetic operations. This linear scan across the entire line results in approximately n operations. Therefore, the total time complexity simplifies to O(n).
Space Complexity
O(1) – The algorithm only requires a few primitive variables, such as a running total to count the adjustments and a variable to track the value of the previous item. These variables occupy a constant amount of memory regardless of the input array size N. There are no auxiliary arrays, recursive calls, or data structures whose size scales with the input. Therefore, the extra memory usage remains strictly constant as N grows.

Optimal Solution

Approach

The optimal strategy is a straightforward walk-through that ensures every item is strictly larger than the one before it. By inspecting adjacent items one by one, we can instantly figure out how much we need to boost a lagging item to maintain a strictly increasing sequence.

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

  1. Begin at the very start of the line of items and look at the first two items side by side.
  2. Check if the second item is greater than the first one. If it is already larger, you do not need to change anything.
  3. If the second item is smaller than or equal to the first one, calculate the exact difference needed to make the second item just barely larger than the first.
  4. Count those required changes and mentally update the value of the second item so that future items have a higher bar to beat.
  5. Shift your focus to the next pair down the line and repeat the same comparison and adjustment process.
  6. Keep a running total of every single adjustment you had to make along the way.
  7. Once you reach the very end of the line, your running total represents the absolute minimum adjustments needed to achieve a strictly increasing sequence.

Code Implementation

def min_operations(array_elements):
    total_operations = 0
    
    # We need a baseline to compare subsequent elements against the preceding one.
    previous_element_value = array_elements[0]

    for current_index in range(1, len(array_elements)):
        current_element_value = array_elements[current_index]

        # If the current element is not strictly greater, we must increment it.
        if current_element_value <= previous_element_value:
            deficit = (previous_element_value - current_element_value) + 1
            total_operations += deficit
            current_element_value += deficit

        # Update the previous value so future elements compare against the new height.
        previous_element_value = current_element_value

    return total_operations

Big(O) Analysis

Time Complexity
O(n) – To find the minimum operations, we perform a single linear scan through the array of size n, checking adjacent pairs side by side. During this traversal, we compute the required difference and update the item value in constant time for each step. Since we iterate through the entire array exactly once from start to finish, the work scales directly with the input size n. This linear progression results in approximately n operations, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only maintains a running total of the adjustments and a few primitive tracking variables for the current and previous items. It processes the input in place without allocating any dynamic data structures, such as temporary lists or hash maps, that scale with the input size N. Therefore, the extra memory usage remains entirely constant regardless of how many items are in the array.

Edge Cases

Array with a single element
How to Handle:
The loop will not execute and the function will correctly return zero operations.
Array already strictly increasing
How to Handle:
Each element is already greater than the previous so the condition fails and zero operations are added.
Array with all identical elements
How to Handle:
Each subsequent element will be incremented enough times to strictly exceed the newly updated previous element.
Array containing negative numbers and zeros
How to Handle:
The greedy comparison works for any integers because strictly greater logic applies uniformly across all ranges.
Array with descending or heavily skewed values
How to Handle:
The running maximum tracker forces each element to at least match the previous plus one, accumulating the correct difference.
Maximum possible constraint sizes with large integers
How to Handle:
Iterating through the array in linear time ensures optimal performance without exceeding time or memory limits.
Integer overflow from continuous increments
How to Handle:
Using standard 32-bit or 64-bit integer types prevents overflow since the total operations fit well within standard numeric limits.
0/257 completed