File tree Expand file tree Collapse file tree
algos/range_queries/PrefixSum/soln/adityashirsatrao007 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ */
Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments