VOOZH about

URL: https://www.geeksforgeeks.org/dsa/computing-point-counts-from-a-set-of-intervals/

⇱ Computing Point Counts from a Set of Intervals - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Computing Point Counts from a Set of Intervals

Last Updated : 10 Mar, 2026

Given n points on a line numbered from 1 to n, and a list of intervals, where each interval [l, r, count] adds count to every point from l to r (inclusive). Compute the total count at each point after processing all intervals.

Examples:

Input : n = 5, intervals[] = [[1, 2, 9], [2, 4, 5], [3, 5, 7]]
Output : [9, 14, 12, 12, 7]
Explanation:
Points: 1 2 3 4 5
Interval [1,2,9]: 9 9
Interval [2,4,5]: 5 5 5
Interval [3,5,7]: 7 7 7
Total count: 9 14 12 12 7

Input : n = 4, intervals[] = [[1, 3, 2], [2, 4, 3]]
Output : [2, 5, 5, 3]
Explanation:
Points: 1 2 3 4
Interval [1,3,2]: 2 2 2
Interval [2,4,3]: 3 3 3
Total count: 2 5 5 3

[Naive Approach] Updating Every Point in Each Interval – O(m × n) Time and O(n) Space

Process each interval [l, r, count] and add count to every point from l to r in the result array. Initialize an array of size n with 0 and update all elements within each interval.


Output
9 14 12 12 7 

[Optimized Approach] Using Prefix Contribution – O(n + m) Time and O(n) Space

For each interval [l, r, count], add count at index l − 1 and subtract count at index r (if it is within bounds). After processing all intervals, compute the prefix sum of the array to propagate the contributions and obtain the final count at each point.


Output
9 14 12 12 7 


Comment
Article Tags:
Article Tags: