forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRangeSumQuery.java
More file actions
73 lines (68 loc) · 2.34 KB
/
RangeSumQuery.java
File metadata and controls
73 lines (68 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.thealgorithms.prefixsum;
/**
* Implements an algorithm to efficiently compute the sum of elements
* between any two indices in an integer array using the Prefix Sum technique.
*
* <p>
* Given an array nums, this algorithm precomputes the prefix sum array
* to allow O(1) sum queries for any range [left, right].
* </p>
*
* <p>
* Let prefixSum[i] be the sum of elements from index 0 to i-1.
* The sum of elements from left to right is:
*
* <pre>
* prefixSum[right + 1] - prefixSum[left]
* </pre>
* </p>
*
* <p>
* <strong>Time Complexity:</strong> O(N) for preprocessing, O(1) per query<br>
* <strong>Space Complexity:</strong> O(N)
* </p>
*
* @author Ruturaj Jadhav, <a href="https://github.com/ruturajjadhav07">ruturajjadhav07</a>
*/
public final class RangeSumQuery {
private RangeSumQuery() {
// Utility class; prevent instantiation
}
/**
* Computes the prefix sum array for efficient range queries.
*
* @param nums The input integer array.
* @return Prefix sum array where prefixSum[i+1] = sum of nums[0..i].
* @throws IllegalArgumentException if nums is null.
*/
public static int[] buildPrefixSum(int[] nums) {
if (nums == null) {
throw new IllegalArgumentException("Input array cannot be null");
}
int n = nums.length;
int[] prefixSum = new int[n + 1];
for (int i = 0; i < n; i++) {
prefixSum[i + 1] = prefixSum[i] + nums[i];
}
return prefixSum;
}
/**
* Returns the sum of elements from index left to right (inclusive)
* using the provided prefix sum array.
*
* @param prefixSum The prefix sum array computed using buildPrefixSum.
* @param left The start index (inclusive).
* @param right The end index (inclusive).
* @return The sum of elements in the range [left, right].
* @throws IllegalArgumentException if indices are invalid.
*/
public static int sumRange(int[] prefixSum, int left, int right) {
if (prefixSum == null) {
throw new IllegalArgumentException("Prefix sum array cannot be null");
}
if (left < 0 || right >= prefixSum.length - 1 || left > right) {
throw new IllegalArgumentException("Invalid range indices");
}
return prefixSum[right + 1] - prefixSum[left];
}
}