Range Queries Lazy propagation
613. Range Add, Range Sum
You are given an array of integers nums and a list of queries. Each query is one of two kinds:
[1, l, r, v]addsvto every element fromnums[l]tonums[r].[2, l, r]asks for the sum of the elements fromnums[l]tonums[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]]
[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]]
[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]]
[-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.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1091 ≤ 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.