Array Problem - 04
Array Problem - 04
Link : https://leetcode.com/problems/range-sum-query-immutable/description/
Problem Statement : Given an integer array nums, handle multiple queries of the
following types :
Example 1 :
Input :
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
Output :
[null, 9, null, 8]
Explanation :
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
Constraints :
Approach :
• We can use a prefix sum to store the total sum up until each index. We only need
O(N) TIme to actually create our prefixSum array and we can return the actual
sumRange in O(1) time.
• If you look at the array and prefixSum array you'll notice that if you try to subtract
the prefix sum range using i and j that you will end up with the wrong value every
time. If you subtract j - (i-1) then you will get the right value !
import java.util.*;
class Main {
// Precomputation: O(N)
// Time per query: O(1)
// Overall time: O(N + Q)
// Overall Space: O(N)
class NumArray {
int preSum[];
Submission On Leetcode :
Note : Further when you are comfortable with the topics like Segment Tree, then you can
solve this question with optimal approach using Segment Trees concept.
ROTATE ARRAY ( LEETCODE - 189 )
16 February 2024 16:41
Link : https://leetcode.com/problems/rotate-array/description/
Problem Statement : Given an integer array nums, rotate the array to the right by k
steps, where k is non-negative.
Example 1 :
Example 2:
Constraints :
Step 2: Shift n-k elements from the beginning by k position to the right
Step 3: Copy the elements into the main array from the temp array.
Output :
Complexity Analysis :
Space Complexity: O(k) since k array element needs to be stored in temp array
Step 3: Copy the elements into the main array from the temp array.
Output :
Complexity Analysis :
Space Complexity: O(k) since k array element needs to be stored in temp array
Output :
Complexity Analysis :
Submission On Leetcode :