Range Addition

MediumArrays & Hashingprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Start with an array of length zeros. You are given a list updates where each entry [start, end, inc] means: add inc to every element whose index lies in the inclusive range [start, end]. Apply all updates and return the final array. Aim for O(length + k) time, where k is the number of updates, rather than touching every index of every range.

Examples

Input: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
Output: [-2,0,3,5,3]
After the first update: [0,2,2,2,0]. After the second: [0,2,5,5,3]. After the third: [-2,0,3,5,3].
Input: length = 3, updates = []
Output: [0,0,0]
No updates, so the zeros are unchanged.

Constraints

  • 1 <= length <= 10^5
  • 0 <= updates.length <= 10^4
  • 0 <= start <= end < length
  • -1000 <= inc <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems