Solved Range Sum Query in Java using Prefix Sum technique

Day 85 of #100DaysOfCode Solved Range Sum Query - Immutable (NumArray) in Java ➕ Approach Today's problem was a classic that demonstrates the power of pre-computation: finding the sum of a range in an array many times. The optimal solution is the Prefix Sum technique. Pre-computation: In the constructor, I built a prefixSum array where prefixSum[i] holds the sum of all elements from index 0 up to index $i-1$ in the original array. This takes $O(N)$ time. $O(1)$ Query: The magic happens in the sumRange(left, right) method. The sum of any range $[left, right]$ is found instantly by calculating prefixSum[right + 1] - prefixSum[left]. The cost of a single $O(N)$ setup is outweighed by the ability to perform every subsequent query in $O(1)$ time! #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Arrays #PrefixSum #Optimization #ProblemSolving

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories