oneby7

Range Queries Lazy propagation

613. Range Add, Range Sum

Hard

You are given an array of integers nums and a list of queries. Each query is one of two kinds:

  • [1, l, r, v] adds v to every element from nums[l] to nums[r].
  • [2, l, r] asks for the sum of the elements from nums[l] to nums[r].

Both ends are included, and positions count from 0. The queries run in order, so a sum sees every add that comes before it, and none that come after.

Return the answers to the sum queries, in the order they appear. If there are no sum queries, return an empty list.

Example 1

Input: nums = [3, -1, 4, 0, 2] queries = [[2, 0, 4], [1, 1, 3, 5], [2, 0, 2], [1, 0, 1, -2], [2, 1, 4], [2, 3, 3]]

Output: [8,16,18,5]

Explanation: The first sum covers the whole array: 3 − 1 + 4 + 0 + 2 = 8. Adding 5 to positions 1 to 3 gives [3,4,9,5,2], so positions 0 to 2 add up to 16. Adding −2 to positions 0 and 1 gives [1,2,9,5,2]. Positions 1 to 4 then add up to 18, and position 3 alone holds 5.

Example 2

Input: nums = [1000000000, 1000000000, 1000000000] queries = [[1, 0, 2, 10000], [2, 0, 2], [1, 1, 1, -10000], [2, 1, 2]]

Output: [3000030000,2000010000]

Explanation: After the first add every element is 1,000,010,000, and the three add up to 3,000,030,000. The second add takes position 1 back to 109, so positions 1 and 2 add up to 2,000,010,000.

Example 3

Input: nums = [-7] queries = [[2, 0, 0], [1, 0, 0, -3], [1, 0, 0, -3], [2, 0, 0]]

Output: [-7,-13]

Explanation: The two adds pile up on the same element: −7 − 3 − 3 = −13. Each sum query gets one answer, and the adds get none.

Check your understanding

Work out the answer for this input before you write any code.

nums = [2, 5, 1, 7] queries = [[1, 0, 2, 3], [2, 1, 3]]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ queries.length ≤ 105
  • Each query is [1, l, r, v] or [2, l, r].
  • 0 ≤ l ≤ r < nums.length
  • -104 ≤ v ≤ 104

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.