Skip to content

Prefix Sum — Corporate Flight Bookings ​

↗ LeetCode: Corporate Flight Bookings · Medium · pattern chapter →

Asked atAmazonMeta

Given n flights and bookings [first, last, seats], return an array where index i = total seats booked on flight i+1.

Example 1 — bookings=[[1,2,10],[2,3,20],[2,5,25]], n=5 → [10,55,45,25,25]Example 2 — bookings=[[1,2,10],[2,2,15]], n=2 → [10,25]Example 3 — bookings=[[1,1,5]], n=3 → [5,0,0]

Constraints — 1 ≤ n ≤ 2·10⁴; 1 ≤ bookings.length ≤ 2·10⁴. Brute applies each booking to a range — O(bookings·n) = 10⁵·2·10⁴ = 2·10⁹ ops (TLE). Difference-array + prefix sum is O(bookings + n) = 3·10⁵ ops = <5 ms.

Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
---
⏱️Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.

Approach 1 — Direct fill ​

For each booking, add seats to every index in [first-1, last-1]. O(n · m).

Approach 2 — Difference array (canonical) ​

Insight. Range-add on many disjoint queries is O(1) per query on a difference array: +seats at first-1, -seats at last. Prefix sum recovers the totals.

java
int[] corpFlightBookings(int[][] bookings, int n) {
    int[] diff = new int[n + 1];
    for (int[] b : bookings) {
        diff[b[0] - 1] += b[2];
        diff[b[1]] -= b[2];
    }
    for (int i = 1; i < n; i++) diff[i] += diff[i - 1];
    return Arrays.copyOf(diff, n);
}
Execution Trace
Diff array — bookings=[[1,2,10],[2,3,20],[2,5,25]], n=5
i0001020304diff = [10,20+25,-10,-20,25,-25]
Step 1 / 2record deltas

Complexity — Time O(n + m); Space O(n).


Try it yourself ​

Complexity summary ​

ApproachTimeSpaceGrade
Direct fillO(n·m)O(n)baseline
Difference arrayO(n+m)O(n)optimum

When to use which ​

  • Many range-add queries, one final read → difference array + one prefix sum.
  • Queries interleaved with reads → segment tree with lazy propagation.
  • Range assignment (not add) → different structure — sweep line or seg tree.
✨AI Study CompanionBeta
Was this page helpful?

Released under MIT license.

💡 Quick shortcuts
H HintsR Run JavaA AI Help