Skip to content

Commit 7eb3826

Browse files
committed
Sync LeetCode submission Runtime - 3 ms (76.10%), Memory - 21.6 MB (6.28%)
1 parent d733dc1 commit 7eb3826

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p>
2+
3+
<ol>
4+
<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li>
5+
</ol>
6+
7+
<p>Implement the <code>NumArray</code> class:</p>
8+
9+
<ul>
10+
<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>
11+
<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>
12+
</ul>
13+
14+
<p>&nbsp;</p>
15+
<p><strong class="example">Example 1:</strong></p>
16+
17+
<pre>
18+
<strong>Input</strong>
19+
[&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;]
20+
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
21+
<strong>Output</strong>
22+
[null, 1, -1, -3]
23+
24+
<strong>Explanation</strong>
25+
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
26+
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
27+
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
28+
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
29+
</pre>
30+
31+
<p>&nbsp;</p>
32+
<p><strong>Constraints:</strong></p>
33+
34+
<ul>
35+
<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
36+
<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
37+
<li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li>
38+
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li>
39+
</ul>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Approach 3: Prefix Sum
2+
3+
# Time: O(1)
4+
# Space: O(n)
5+
6+
class NumArray:
7+
8+
def __init__(self, nums: List[int]):
9+
self.prefix_sum = [0] * (len(nums) + 1)
10+
for i in range(len(nums)):
11+
self.prefix_sum[i + 1] = self.prefix_sum[i] + nums[i]
12+
13+
def sumRange(self, left: int, right: int) -> int:
14+
return self.prefix_sum[right + 1] - self.prefix_sum[left]
15+
16+
17+
18+
# Your NumArray object will be instantiated and called as such:
19+
# obj = NumArray(nums)
20+
# param_1 = obj.sumRange(left,right)

0 commit comments

Comments
 (0)