A Prefix Sum (also known as a cumulative sum) is a powerful technique used to pre-process an array so that the sum of any subarray (a range of elements) can be calculated in constant time, $O(1)$.
Essentially, you create a new array where each element at index $i$ stores the sum of all elements from the original array starting from the beginning up to index $i$.
If you have an array $A$ of size $n$, the prefix sum array $P$ is defined as:
$P[i] = A[0] + A[1] + \dots + A[i]$
Or, more efficiently through recurrence:
Let’s take a sample array and build its prefix sum.
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Array A | 3 | 1 | 4 | 1 | 5 |
| Prefix Sum P | 3 | 4 | 8 | 9 | 14 |
Calculations:
The primary advantage is calculating the sum of elements between two indices $L$ and $R$ ($sum(L, R)$).
Instead of looping through the array every time—which takes $O(N)$—you can use the formula:
$\text{Sum}(L, R) = P[R] - P[L-1]$
(Note: If L=0, the sum is simply* *P[R]).
Example: Find the sum of elements from index 2 to 4 in the array above.
def build_prefix_sum(arr):
n = len(arr)
prefix_sum = [0] * n
prefix_sum[0] = arr[0]
for i in range(1, n):
prefix_sum[i] = prefix_sum[i-1] + arr[i]
return prefix_sum
# Usage
data = [3, 1, 4, 1, 5]
p_sum = build_prefix_sum(data) # [3, 4, 8, 9, 14]
public class PrefixSum {
public static int[] buildPrefixSum(int[] arr) {
int n = arr.length;
if (n == 0) return new int[0];
int[] prefixSum = new int[n];
prefixSum[0] = arr[0];
for (int i = 1; i < n; i++) {
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
return prefixSum;
}
// Usage example
public static void main(String[] args) {
int[] data = {3, 1, 4, 1, 5};
int[] pSum = buildPrefixSum(data); // [3, 4, 8, 9, 14]
for (int v : pSum) {
System.out.print(v + " ");
}
}
}
The Two Pointer Technique is one of the most efficient ways to search for pairs or subsegments in a linear data structure (like an array or linked list). It typically reduces a nested loop $O(n^2)$ solution down to a linear $O(n)$ solution.
It works by using two indices (the “pointers”) that move through the data independently based on specific conditions.
This is used when the array is sorted. You place one pointer at the start (left) and one at the end (right).
sum < target, move the left pointer forward to increase the sum.sum > target, move the right pointer backward to decrease the sum.sum == target, you found it!Both pointers start at the same side but move at different speeds or intervals.
fast pointer moves two steps while the slow pointer moves one. If they ever meet, there is a cycle.A specific type of two-pointer technique where the distance between the two pointers represents a “window.”
right pointer to expand the window and the left pointer to contract it when a condition is met.If you are given a sorted array, the two-pointer approach is more space-efficient ($O(1)$) than a Hash Map.
def two_sum_sorted(nums, target):
left = 0
right = len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1 # Need a larger sum
else:
right -= 1 # Need a smaller sum
return []
You should reach for this tool if you see these keywords:
The Sliding Window technique is a specific variation of the Two-Pointer approach. It is primarily used to convert nested loops ($O(n^2)$) into a single pass ($O(n)$) when dealing with subarrays or substrings.
Instead of recalculating everything from scratch for every possible range, you “slide” a window across the data, adding one element at the front and removing one from the back.
The window size $k$ remains constant. You move the window by adding the next element and subtracting the element that is no longer in the range.
[2, 1, 5, 1, 3, 2], $k=3$
[2, 1, 5] (Sum = 8)[1, 5, 1] (Sum = 7) — We added 1, subtracted 2.The window grows or shrinks dynamically based on a condition (like a target sum or a count of unique characters).
right pointer to add elements.
left pointer to find the “minimum” valid window.Here is a classic example: Maximum sum of a subarray of size $K$.
def max_sum_subarray(arr, k):
n = len(arr)
if n < k:
return -1
# Calculate sum of first window
window_sum = sum(arr[:k])
max_val = window_sum
# Slide the window
for i in range(n - k):
# Subtract the element leaving, add the element entering
window_sum = window_sum - arr[i] + arr[i + k]
max_val = max(max_val, window_sum)
return max_val
Look for these “green flags” in a problem description:
| Feature | Brute Force | Sliding Window |
|---|---|---|
| Time Complexity | $O(n \times k)$ or $O(n^2)$ | $O(n)$ |
| Space Complexity | $O(1)$ | $O(1)$ (usually) |
HashMaps (or Dictionaries) are the “cheat code” of array problems. They allow you to trade a little bit of Space ($O(n)$) for a massive gain in Time ($O(1)$ lookup).
If you see a problem asking about frequencies, existence, or pairs, a HashMap is likely the answer. Here are the most essential problem patterns you’ll encounter.
The most basic use: counting how many times each element appears.
{num: count}.Checking if a value (or its “partner”) has been seen before.
target - current is in the map. If not, add current to the map and move on.Using a sorted version or a property of the data as the “Key.”
["eat", "tea", "tan", "ate", "nat", "bat"]:
"eat" becomes "aet").{"aet": ["eat", "tea", "ate"], "ant": ["tan", "nat"], "abt": ["bat"]}.This is a high-level pattern that combines two techniques we’ve discussed.
current_sum.prefix_sum has occurred in a HashMap.current_sum - k exists in the map. If it does, those previous points are the “starts” of valid subarrays.Finding the length of the longest sequence of integers (e.g., [1, 2, 3, 4]) in an unsorted array.
[100, 4, 200, 1, 3, 2] $\rightarrow$ Result is 4 (for 1, 2, 3, 4).n-1 is not in the set (this ensures you only start at the “beginning” of a sequence).| Problem Type | HashMap Key | HashMap Value |
|---|---|---|
| Frequency | Element | Count |
| Two Sum | Element | Index |
| Anagrams | Sorted String | List of original strings |
| Subarray Sum | Prefix Sum | Occurrences |
| Longest Seq | Element | Boolean/Presence |