Skip to content
advancedPhase 7 · Advanced Topics

Difference Array

Use difference arrays for efficient range updates.

45m
3 problems
Topic Progress0%

Difference Array Fundamentals

What is a Difference Array?

A Difference Array is a technique that allows performing multiple range update operations efficiently. Instead of updating each element individually (O(n) per update), we can mark the start and end of each update and process them all at once.

Key Idea

Given array arr[0..n-1], create a difference array diff[0..n] where:

  • diff[0] = arr[0]
  • diff[i] = arr[i] - arr[i-1] for i > 0

To add val to range [l, r]:

  • diff[l] += val
  • diff[r+1] -= val

After all updates, reconstruct original array: arr[i] = arr[i-1] + diff[i]

Example

Initial array: arr = [0, 0, 0, 0, 0, 0, 0, 0]

Operation 1: Add 5 to range [2, 5]
Operation 2: Add 3 to range [4, 7]
Operation 3: Add 2 to range [0, 3]

Difference array approach:
1. diff[2] += 5, diff[6] -= 5
2. diff[4] += 3, diff[8] -= 3
3. diff[0] += 2, diff[4] -= 2

diff = [2, 0, 5, 0, 1, 0, -5, 0, -3]

Reconstruct:
arr[0] = 2
arr[1] = 2 + 0 = 2
arr[2] = 2 + 5 = 7
arr[3] = 7 + 0 = 7
arr[4] = 7 + 1 = 8
arr[5] = 8 + 0 = 8
arr[6] = 8 + (-5) = 3
arr[7] = 3 + 0 = 3

Final array: [2, 2, 7, 7, 8, 8, 3, 3]

Implementation

public class DifferenceArray {
    private int[] diff;
    private int n;
    
    public DifferenceArray(int size) {
        n = size;
        diff = new int[size + 1];
    }
    
    public DifferenceArray(int[] arr) {
        n = arr.length;
        diff = new int[n + 1];
        diff[0] = arr[0];
        for (int i = 1; i < n; i++) {
            diff[i] = arr[i] - arr[i - 1];
        }
    }
    
    // Add val to range [l, r] (0-indexed, inclusive)
    public void rangeUpdate(int l, int r, int val) {
        diff[l] += val;
        if (r + 1 <= n) {
            diff[r + 1] -= val;
        }
    }
    
    // Reconstruct the original array
    public int[] getArray() {
        int[] result = new int[n];
        result[0] = diff[0];
        for (int i = 1; i < n; i++) {
            result[i] = result[i - 1] + diff[i];
        }
        return result;
    }
    
    // Get prefix sum (sum of elements from 0 to i)
    public int getPrefixSum(int i) {
        int sum = 0;
        for (int j = 0; j <= i; j++) {
            sum += diff[j];
        }
        return sum;
    }
}

Time Complexity

  • Range Update: O(1) per operation
  • Reconstruct Array: O(n)
  • Total for k updates: O(n + k)

Difference Array Applications

Common Applications

1. Flight Range Bookings

// Book n flights from first to last, each booking[i] = [first, last, seats]
public int[] corpFlightBookings(int[][] bookings, int n) {
    int[] diff = new int[n + 1];
    
    for (int[] booking : bookings) {
        diff[booking[0] - 1] += booking[2]; // 1-indexed to 0-indexed
        diff[booking[1]] -= booking[2];
    }
    
    int[] result = new int[n];
    result[0] = diff[0];
    for (int i = 1; i < n; i++) {
        result[i] = result[i - 1] + diff[i];
    }
    
    return result;
}

2. Car Pooling with Difference Array

public boolean carPooling(int[][] trips, int capacity) {
    int[] diff = new int[1001]; // Max location is 1000
    
    for (int[] trip : trips) {
        diff[trip[1]] += trip[0];  // Passengers get on
        diff[trip[2]] -= trip[0];  // Passengers get off
    }
    
    int currentPassengers = 0;
    for (int i = 0; i <= 1000; i++) {
        currentPassengers += diff[i];
        if (currentPassengers > capacity) {
            return false;
        }
    }
    
    return true;
}

3. Range Addition with Final Query

// After all updates, answer multiple queries
public int[] getModifiedArray(int length, int[][] updates) {
    int[] diff = new int[length + 1];
    
    for (int[] update : updates) {
        diff[update[0]] += update[2];
        diff[update[1] + 1] -= update[2];
    }
    
    int[] result = new int[length];
    result[0] = diff[0];
    for (int i = 1; i < length; i++) {
        result[i] = result[i - 1] + diff[i];
    }
    
    return result;
}

4. Difference Array with Prefix Sum

// 2D Difference Array for matrix updates
public void updateMatrix(int[][] matrix, int r1, int c1, int r2, int c2, int val) {
    int m = matrix.length, n = matrix[0].length;
    int[][] diff = new int[m + 1][n + 1];
    
    diff[r1][c1] += val;
    diff[r1][c2 + 1] -= val;
    diff[r2 + 1][c1] -= val;
    diff[r2 + 1][c2 + 1] += val;
    
    // Reconstruct using 2D prefix sums
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            diff[i + 1][j + 1] += diff[i + 1][j] + diff[i][j + 1] - diff[i][j];
            matrix[i][j] += diff[i + 1][j + 1];
        }
    }
}

Practice Problems

0/1solved
Range Addition
Difference Array

Given an length array initialized with zeros and a list of updates where each update is [start, end, inc], apply each update to increment all elements from start to end by inc. Return the final modified array.

Example:

Input: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]

Output: -20353

After [1,3,2]: [0,2,2,2,0]. After [2,4,3]: [0,2,5,5,3]. After [0,2,-2]: [-2,0,3,5,3]

Solution
```java
public int[] getModifiedArray(int length, int[][] updates) {
    int[] diff = new int[length + 1];
    
    // Apply all updates to difference array
    for (int[] update : updates) {
        diff[update[0]] += update[2];
        if (update[1] + 1 < length) {
            diff[update[1] + 1] -= update[2];
        }
    }
    
    // Reconstruct the array
    int[] result = new int[length];
    result[0] = diff[0];
    for (int i = 1; i < length; i++) {
        result[i] = result[i - 1] + diff[i];
    }
    
    return result;
}
```

Edge Cases:

  • No updates (all zeros)
  • Updates cover entire array
  • Negative increments
  • Overlapping updates at boundaries

Quiz

1. What is the time complexity of a single range update using a difference array?

Question 1 options

2. When is a difference array preferred over a Segment Tree?

Question 2 options

3. What is the primary purpose of Difference Array?

Question 3 options

4. What is a common mistake when implementing Difference Array?

Question 4 options

Flashcards

Question

How do you apply a range update [l, r] with value val using a difference array?

Answer

Set diff[l] += val and diff[r+1] -= val. This marks the start and end of the increment. After all updates, reconstruct by computing prefix sums of the difference array.

Question

What is the main limitation of difference arrays?

Answer

Difference arrays only support offline processing - you must complete all updates before reconstructing the array. They don't support online queries or intermediate state queries.

Question

What is Difference Array?

Answer

Difference Array is a key concept in software engineering.

Question

When to use Difference Array?

Answer

Use Difference Array when building production systems that require reliability, scalability, and maintainability.

Question

Difference Array best practices

Answer

Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.

Revision Notes

Key Takeaways

  • 1.Difference arrays enable O(1) range updates by marking boundaries
  • 2.Reconstruct the array using prefix sums of the difference array
  • 3.Perfect for batch updates where only the final state matters
  • 4.Can be extended to 2D for matrix operations
  • 5.Simpler and more space-efficient than Segment Trees for this use case

Interview Tips

  • Use difference arrays when you see multiple range update operations
  • Remember: diff[l] += val, diff[r+1] -= val
  • After all updates, reconstruct with a single pass (prefix sum)
  • Great for problems like Flight Range Bookings, Car Pooling
  • For 2D problems, extend the concept to 2D difference arrays

Cheat Sheet

Difference Array Cheat Sheet

Core Concept

Mark range boundaries instead of updating each element:

diff[l] += val      // Start of range
diff[r+1] -= val    // End of range

Reconstruct Array

int[] result = new int[n];
result[0] = diff[0];
for (int i = 1; i < n; i++) {
    result[i] = result[i-1] + diff[i];
}

Time Complexity

  • Range Update: O(1)
  • Reconstruct: O(n)
  • Total for k updates: O(n + k)

2D Difference Array

diff[r1][c1] += val;
diff[r1][c2+1] -= val;
diff[r2+1][c1] -= val;
diff[r2+1][c2+1] += val;

Applications

  1. Flight Range Bookings
  2. Car Pooling
  3. Range Addition
  4. Matrix Range Updates

When to Use

  • Multiple range updates
  • Only final array needed
  • No intermediate queries
  • Simpler than Segment Tree