Difference Array
Lesson 12Beginner43 minAssessment-backed

Difference Array

Represent many bulk range updates compactly, then reconstruct final values with one prefix pass.

What you will be able to do

Explain difference arrays as boundary markers for bulk range updates.
Apply many range increments in O(1) each before one O(n) reconstruction pass.
Use the pattern in scheduling, promotions, capacity planning, and offline simulations.
Know when difference arrays fail because reads and updates are interleaved.

Difference arrays are the mirror image of prefix sums. Prefix sums make repeated range reads cheap. Difference arrays make repeated range writes cheap when you can delay reading the final result.

Boundary Markers Instead of Repeated Writes

If you need to add +5 to every item from index l to r, updating each cell costs O(r-l+1). A difference array marks where the change starts and where it stops: diff[l] += 5 and diff[r + 1] -= 5. Later, a prefix pass reconstructs the final values.

Difference array range update flow
The pattern is powerful when many range updates happen before final values are needed.

Scenario: Promotion Calendar

An ecommerce platform plans hundreds of overlapping promotional boosts across 365 days. Each campaign adds a score boost to a day range. Updating every day for every campaign is unnecessary. Mark campaign starts and stops in a difference array, then run one prefix pass to compute final daily boost.

ApproachCost for k updates over n positionsFits when
Direct updateO(total covered length)Few small ranges.
Difference arrayO(k + n)Many range updates, final read after updates.
Segment tree laterO(log n) updates and queriesUpdates and queries interleave online.

Same Pattern in Java, Python, and JavaScript

class DifferenceArray {
    static int[] apply(int length, int[][] updates) {
        int[] diff = new int[length + 1];
        for (int[] update : updates) {
            int left = update[0];
            int right = update[1];
            int delta = update[2];
            diff[left] += delta;
            if (right + 1 < diff.length) diff[right + 1] -= delta;
        }
        int[] result = new int[length];
        int running = 0;
        for (int i = 0; i < length; i++) {
            running += diff[i];
            result[i] = running;
        }
        return result;
    }
}

Assessment trap

Difference arrays are usually offline. If the product needs the current range value immediately after every update, you need a different data structure.

Field judgmentEngineering Notes

  • Use difference arrays for many range updates followed by final reconstruction.
  • Mark both the start and the stop boundary.
  • Allocate one extra slot to simplify r + 1 handling.
  • State O(k + n) total cost for k updates and n positions.
  • Do not use this pattern blindly for online query/update workloads.

Interview signalFrequently Asked Interview Questions

These are canonical interview patterns for this topic, phrased as concrete problem statements. They avoid vague theory questions and prepare you for the exact reasoning interviewers expect: invariant, edge cases, complexity, and trade-off.

  • Apply many updates of the form add delta to every index from left to right, then return the final array.
  • Each booking adds seats to every flight number in a range. Return seats booked per flight.
  • Campaigns add score boosts to day ranges. Return final daily boost after all campaigns.

Production practiceCompany-Style Practice Examples

These are not claimed as exact company-specific questions. They are the interview patterns repeatedly used by product companies to test whether you can move from brute force to a defensible implementation.

ExampleBrute-force approachStronger solutionProduction notes
Range increment updatesUpdate every position in every range.Mark start and stop in diff, reconstruct once.Best for many offline range updates.
Flight bookings / capacityApply every booking to every affected day/seat bucket.Use difference array by boundary markers.Final prefix pass gives actual capacity.
Promotion calendarRecompute every day after each campaign change.Batch campaigns into diff markers then materialize.Not ideal if reads must happen after every update.

Solved modelInterview Question Solutions

Question 1: Range Increment Updates

Apply many updates of the form add delta to every index from left to right, then return the final array. Each update becomes two boundary writes. One prefix pass converts boundaries into final values.

class RangeUpdates {
    static int[] apply(int length, int[][] updates) {
        int[] diff = new int[length + 1];
        for (int[] update : updates) {
            int left = update[0], right = update[1], delta = update[2];
            diff[left] += delta;
            if (right + 1 < diff.length) diff[right + 1] -= delta;
        }
        int[] result = new int[length];
        int running = 0;
        for (int i = 0; i < length; i++) {
            running += diff[i];
            result[i] = running;
        }
        return result;
    }
}

Question 2: Flight Bookings Capacity

Each booking adds seats to every flight number in a range. Return seats booked per flight. Treat bookings as range updates over flight indexes. Difference array gives O(bookings + flights).

class FlightBookings {
    static int[] seats(int flightCount, int[][] bookings) {
        int[] diff = new int[flightCount + 1];
        for (int[] booking : bookings) {
            int first = booking[0] - 1;
            int last = booking[1] - 1;
            int seats = booking[2];
            diff[first] += seats;
            if (last + 1 < diff.length) diff[last + 1] -= seats;
        }
        int[] result = new int[flightCount];
        int running = 0;
        for (int i = 0; i < flightCount; i++) {
            running += diff[i];
            result[i] = running;
        }
        return result;
    }
}

Question 3: Promotion Calendar

Campaigns add score boosts to day ranges. Return final daily boost after all campaigns. This is an offline range-update workload. Mark each campaign boundary, then reconstruct daily values once.

class PromotionCalendar {
    static int[] boosts(int days, int[][] campaigns) {
        int[] diff = new int[days + 1];
        for (int[] campaign : campaigns) {
            int start = campaign[0];
            int end = campaign[1];
            int boost = campaign[2];
            diff[start] += boost;
            if (end + 1 < diff.length) diff[end + 1] -= boost;
        }
        int[] result = new int[days];
        int running = 0;
        for (int day = 0; day < days; day++) {
            running += diff[day];
            result[day] = running;
        }
        return result;
    }
}

Solved modelWorked Interview Answer

Apply many range increment updates and return the final array. Mark only the start and stop boundaries for each update, then reconstruct with one prefix pass.

class RangeUpdates {
    static int[] apply(int length, int[][] updates) {
        int[] diff = new int[length + 1];
        for (int[] update : updates) {
            int left = update[0], right = update[1], delta = update[2];
            diff[left] += delta;
            if (right + 1 < diff.length) diff[right + 1] -= delta;
        }
        int[] result = new int[length];
        int running = 0;
        for (int i = 0; i < length; i++) {
            running += diff[i];
            result[i] = running;
        }
        return result;
    }
}

Hands-on drillTry It Yourself

Practice task

Given length 8 and updates [1, 4, +3], [2, 6, +2], and [0, 2, -1], build the diff array and reconstruct the final values.

Failure patternsCommon Mistakes to Avoid

  • Forgetting the stop marker at r + 1.
  • Not allocating an extra diff slot.
  • Using difference arrays when the system needs immediate online reads after each update.

Execution guardrailQuick-Start Checklist

  • Create diff with length n + 1.
  • Mark diff[left] plus equals delta.
  • Mark diff[right + 1] minus equals delta when in bounds.
  • Run one prefix pass.
  • State O(k + n) for k updates and n positions.

Recall drillKnowledge Check

QuestionStrong answer
What does the start marker mean?The delta begins affecting values at left.
What does the stop marker mean?The delta stops affecting values after right.
When is the pattern best?Many range updates are known before final values are read.

VocabularyKey Terms

TermMeaning
Difference arrayA boundary-marker array whose prefix reconstructs final values.
Range updateApplying a change to every position in a contiguous range.
Offline algorithmAn approach that processes known work before answering final output.

Next practiceFurther Reading

  • Compare difference arrays with lazy propagation.
  • Study booking, calendar, and capacity simulation problems.
  • Review prefix sums because reconstruction uses a prefix pass.