LeetCode 0370. Range Addition Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0370. Range Addition

Description

You are given an integer length and an array updates where updates[i] = [startIdxi, endIdxi, inci].

You have an array arr of length length with all zeros, and you have some operation to apply on arr. In the ith operation, you should increment all the elements arr[startIdxi], arr[startIdxi + 1], ..., arr[endIdxi] by inci.

Return arr after applying all the updates.

 

Example 1:

Input: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
Output: [-2,0,3,5,3]

Example 2:

Input: length = 10, updates = [[2,4,6],[5,6,8],[1,9,-4]]
Output: [0,-4,2,2,2,4,4,-4,-4,-4]

 

Constraints:

  • 1 <= length <= 105
  • 0 <= updates.length <= 104
  • 0 <= startIdxi <= endIdxi < length
  • -1000 <= inci <= 1000

Solutions

Solution 1: Difference Array

This is a template problem for difference arrays.

We define d as the difference array. To add c to each number in the interval [l,..r], we set d[l] += c and d[r+1] -= c. Finally, we compute the prefix sum of the difference array to obtain the original array.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array.

PythonJavaC++GoTypeScriptJavaScript
class Solution: def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: d = [0] * length for l, r, c in updates: d[l] += c if r + 1 < length: d[r + 1] -= c return list(accumulate(d))(code-box)

Solution 2: Binary Indexed Tree + Difference Array

The time complexity is O(n × log n).

A Binary Indexed Tree (BIT), also known as a Fenwick Tree, can efficiently perform the following two operations:

  1. Point Update update(x, delta): Add a value delta to the number at position x in the sequence.
  2. Prefix Sum Query query(x): Query the sum of the interval [1, ... , x] in the sequence, i.e., the prefix sum up to position x.

The time complexity for both operations is O(log n).

PythonJavaC++GoTypeScriptJavaScript
class BinaryIndexedTree: __slots__ = "n", "c" def __init__(self, n: int): self.n = n self.c = [0] * (n + 1) def update(self, x: int, delta: int) -> None: while x <= self.n: self.c[x] += delta x += x & -x def query(self, x: int) -> int: s = 0 while x: s += self.c[x] x -= x & -x return s class Solution: def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]: tree = BinaryIndexedTree(length) for l, r, c in updates: tree.update(l + 1, c) tree.update(r + 2, -c) return [tree.query(i + 1) for i in range(length)](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !