Prefix Sum

๐Ÿ“‘ Prefix Sum Pattern

๐Ÿ”Ž What is Prefix Sum?

A prefix sum is the cumulative sum of elements in an array up to a certain index.
It allows us to compute range sums and solve subarray problems efficiently.

Example:
Array = [1, 2, 3, 4]
Prefix Sum = [1, 3, 6, 10]


โš™๏ธ Algorithm

  1. Initialize an array prefix of the same length as input.
  2. Set prefix[0] = arr[0].
  3. For each i from 1 to n-1:
    prefix[i] = prefix[i-1] + arr[i]
  4. Use the prefix array to answer queries in O(1).

โฑ Complexity Analysis


โ“ Why Use Prefix Sums?

Without prefix sums โ†’ range sum query [i, j] takes O(n).
With prefix sums โ†’ range sum query [i, j] takes O(1).


๐Ÿงฎ Example: Range Sum Query

Problem: Given an array arr and indices i, j, compute the sum between them.

class Solution:
    def compute_prefix_sum(self, arr):
        prefix = [0] * len(arr)
        prefix[0] = arr[0]
        for i in range(1, len(arr)):
            prefix[i] = prefix[i - 1] + arr[i]
        return prefix

    def range_sum_query(self, prefix, i, j):
        if i == 0:
            return prefix[j]
        return prefix[j] - prefix[i - 1]

# Example usage
arr = [1, 2, 3, 4]
sol = Solution()
prefix_sum = sol.compute_prefix_sum(arr)
print(sol.range_sum_query(prefix_sum, 1, 3))  # Output: 9

๐Ÿ›  Applications

  1. Range Sum Queries โ€“ O(1) retrieval of subarray sum.
  2. Subarray Problems โ€“ find subarrays with given sum, max subarray sum, etc.
  3. 2D Prefix Sums โ€“ efficient sum queries in submatrices.
  4. Frequency Counting โ€“ cumulative counts for data analysis.
  5. Load Balancing โ€“ distribute workloads evenly in systems.

๐Ÿงพ Key Formula

For subarray sum from i to j:


๐Ÿ“Œ Common Problems Solved Using Prefix Sum

1. Range Sum Query (LeetCode 303)

2. Subarray Sum Equals K (LeetCode 560)

3. Maximum Subarray Sum (Kadaneโ€™s Alternative)

4. Equilibrium Index

5. Count of Subarrays Divisible by K

6. 2D Prefix Sum Problems (LeetCode 304)

7. Balanced Parentheses / Matching Problems