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

Range Addition

Number: 370

Difficulty: Medium

Paid? Yes

Companies: Salesforce, Google


Problem Description

Given an integer length and an array updates where each update is of the form [startIdx, endIdx, inc], start with an array of zeros of that length. For each update, increment all elements from startIdx to endIdx by the value inc. Return the modified array after all updates are applied.


Key Insights

  • Use a difference array (prefix sum technique) to update ranges efficiently.
  • Instead of updating every element for each range (which could be slow), update the start index and subtract after the end index.
  • Compute the final array by taking the cumulative sum of the difference array.
  • This approach reduces the time complexity from potentially O(n * number_of_updates) to O(n + number_of_updates).

Space and Time Complexity

Time Complexity: O(n + k), where n is the length of the array and k is the number of updates.
Space Complexity: O(n) for the difference array (and output array).


Solution

We use a difference array to efficiently perform range updates. The idea is to add the increment at the start index and subtract the increment just after the end index. After processing all updates, a single pass of cumulative sum across the array gives the final result. This method avoids updating every element within the range for each query, making it efficient for large inputs.


Code Solutions

# Python solution for Range Addition

def getModifiedArray(length, updates):
    # Initialize the result list with zeros
    result = [0] * length
    
    # Process each update by marking the start and end+1 positions
    for update in updates:
        start, end, inc = update
        result[start] += inc  # Add inc at the start index
        if end + 1 < length:
            result[end + 1] -= inc  # Subtract inc just after the end index
    
    # Convert the difference array to the final result using a running sum
    for i in range(1, length):
        result[i] += result[i - 1]

    return result

# Example usage:
length = 5
updates = [[1, 3, 2], [2, 4, 3], [0, 2, -2]]
print(getModifiedArray(length, updates))  # Output: [-2, 0, 3, 5, 3]
← Back to All Questions