← All patterns
Prefix / Range

Difference Array

0 practice questions|Medium

When to use it

Apply range additions in O(1) and reconstruct the final array via prefix sums.

Key Signals & Indicators

  • Requires multiple range increment/update operations
  • Queries only happen after all range additions complete
  • Requires performance optimization over repeated linear loops

Pattern Boilerplate

c++
// C++ Difference Array Template
#include <vector>

class DifferenceArray {
    std::vector<int> diff;
public:
    DifferenceArray(int size) : diff(size + 1, 0) {}
    
    void update(int left, int right, int val) {
        diff[left] += val;
        diff[right + 1] -= val;
    }
    
    std::vector<int> reconstruct() {
        std::vector<int> result(diff.size() - 1);
        int sum = 0;
        for (size_t i = 0; i < result.size(); ++i) {
            sum += diff[i];
            result[i] = sum;
        }
        return result;
    }
};

Problems using this pattern

Questions are being tagged

Questions for this pattern are currently being curated — check back soon.