Skip to content

Commit 1d8cb3b

Browse files
Added solutions for Range Sum Query Immutable and Running Sum of 1d Array
1 parent 61e387f commit 1d8cb3b

2 files changed

Lines changed: 88 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Problem: Range Sum Query - Immutable (LeetCode 303)
3+
Link: https://leetcode.com/problems/range-sum-query-immutable/
4+
5+
Approach: Prefix Sum Array
6+
We can precompute the prefix sums of the array such that:
7+
prefix[i] = nums[0] + nums[1] + ... + nums[i]
8+
9+
Then, the sum of the range [left, right] can be calculated as:
10+
sumRange(left, right) = prefix[right] - prefix[left - 1]
11+
12+
Time Complexity:
13+
- Constructor: O(N) to build the prefix sum array.
14+
- sumRange: O(1) per query.
15+
16+
Space Complexity: O(N) to store the prefix sum array.
17+
*/
18+
19+
#include <vector>
20+
#include <iostream>
21+
22+
using namespace std;
23+
24+
class NumArray {
25+
private:
26+
vector<int> prefix;
27+
28+
public:
29+
NumArray(vector<int>& nums) {
30+
int n = nums.size();
31+
prefix.resize(n);
32+
if (n == 0) return;
33+
34+
prefix[0] = nums[0];
35+
for (int i = 1; i < n; i++) {
36+
prefix[i] = prefix[i - 1] + nums[i];
37+
}
38+
}
39+
40+
int sumRange(int left, int right) {
41+
if (left == 0) {
42+
return prefix[right];
43+
}
44+
return prefix[right] - prefix[left - 1];
45+
}
46+
};
47+
48+
/**
49+
* Your NumArray object will be instantiated and called as such:
50+
* NumArray* obj = new NumArray(nums);
51+
* int param_1 = obj->sumRange(left,right);
52+
*/
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Problem: Running Sum of 1d Array (LeetCode 1480)
3+
Link: https://leetcode.com/problems/running-sum-of-1d-array/
4+
5+
Approach: Prefix Sum (In-place)
6+
We can iterate through the array and update each element to be the sum of itself and the previous element.
7+
nums[i] += nums[i-1] for i > 0.
8+
9+
This creates the running sum array in-place without using extra space (excluding the output vector).
10+
11+
Time Complexity: O(N) where N is the number of elements.
12+
Space Complexity: O(1) if we ignore the output array space, or O(N) if we create a new vector.
13+
(This implementation returns a new vector to be clean, but modifies logic similar to in-place)
14+
*/
15+
16+
#include <vector>
17+
#include <iostream>
18+
19+
using namespace std;
20+
21+
class Solution {
22+
public:
23+
vector<int> runningSum(vector<int>& nums) {
24+
int n = nums.size();
25+
if (n == 0) return {};
26+
27+
vector<int> result(n);
28+
result[0] = nums[0];
29+
30+
for (int i = 1; i < n; i++) {
31+
result[i] = result[i - 1] + nums[i];
32+
}
33+
34+
return result;
35+
}
36+
};

0 commit comments

Comments
 (0)