Skip to content

Commit c0b812d

Browse files
committed
leetcode
1 parent bb2a91a commit c0b812d

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,17 @@
11
package main
2+
3+
type NumArray struct {
4+
sums []int
5+
}
6+
7+
func Constructor(nums []int) NumArray {
8+
sums := make([]int, len(nums)+1)
9+
for i, v := range nums {
10+
sums[i+1] += v + sums[i]
11+
}
12+
return NumArray{sums}
13+
}
14+
15+
func (this *NumArray) SumRange(left int, right int) int {
16+
return this.sums[right+1] - this.sums[left]
17+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# 🔥 Range Sum Query - Immutable 🔥 || 3 Solutions || Simple Fast and Easy || with Explanation
2+
3+
## Solution - 1
4+
5+
```dart
6+
class NumArray {
7+
late List<int> prefixSum;
8+
9+
NumArray(List<int> nums) {
10+
if (nums == 0) {
11+
throw ArgumentError("Panic: Input is Empty");
12+
}
13+
14+
this.prefixSum = List.filled(nums.length + 1, 0);
15+
16+
for (int i = 1; i <= nums.length; i++) {
17+
prefixSum[i] = prefixSum[i - 1] + nums[i - 1];
18+
}
19+
}
20+
21+
int sumRange(int left, int right) {
22+
if (left < 0 || right >= prefixSum.length - 1) {
23+
throw RangeError("Panic: Input indices are out of bounds");
24+
}
25+
26+
// Here both left and right are inclusive.
27+
// right maps to right+1 in prefixSum. left maps to left+1 in prefixSum.
28+
// To get the result subtract the prefixSum before left index from prefixSum at
29+
// right index.
30+
return prefixSum[right + 1] - prefixSum[left];
31+
}
32+
}
33+
```
34+
35+
## Solution - 2
36+
37+
```dart
38+
class NumArray {
39+
late List<int> nums;
40+
late List<int> prefixSum;
41+
NumArray(List<int> nums) {
42+
this.nums = nums;
43+
this.prefixSum = getPrefixSum();
44+
}
45+
46+
int sumRange(int left, int right) {
47+
if (left == 0) return prefixSum[right];
48+
return prefixSum[right] - prefixSum[left - 1];
49+
}
50+
51+
List<int> getPrefixSum() {
52+
int sum = 0;
53+
List<int> ans = List.filled(nums.length, 0);
54+
55+
for (int i = 0; i < nums.length; i++) {
56+
sum += nums[i];
57+
ans[i] = sum;
58+
}
59+
60+
return ans;
61+
}
62+
}
63+
```
64+
65+
## Solution - 3
66+
67+
```dart
68+
69+
class NumArray {
70+
List<int> arr = [];
71+
NumArray(List<int> nums) {
72+
this.arr = nums;
73+
}
74+
75+
int sumRange(int left, int right) {
76+
int sum = 0;
77+
for (int i = left; i <= right; i++) sum += this.arr[i];
78+
return sum;
79+
}
80+
}
81+
```

0 commit comments

Comments
 (0)