Data Structures19 sections · 729 units
Open in Course

Range Addition - Implementation

Complete solution

Here's the full solution:

function getModifiedArray(length, updates)
    diff := array of size length, all zeros

    // Phase 1: Apply all updates to difference array
    for each (start, end, val) in updates
        diff[start] += val
        if end + 1 < length
            diff[end + 1] -= val

    // Phase 2: Compute prefix sum to get final array
    for i from 1 to length - 1
        diff[i] += diff[i - 1]

    return diff

Time: O(k+n)O(k + n). Space: O(n)O(n).