๐Ÿ—“๏ธ Day 5: Prefix Sum and Difference Arrays

๐Ÿง  Concept Deep Dive

Prefix Sum is a simple yet powerful technique used to quickly compute the sum of elements in a subarray.

๐Ÿ”น Prefix Sum Definition:

Given an array nums, the prefix sum array prefix is defined as:

prefix[i] = nums[0] + nums[1] + ... + nums[i-1]

(We usually add a 0 at the beginning for convenience.)

This helps us compute the sum of any subarray [i, j] in constant time:

sum(i, j) = prefix[j+1] - prefix[i]

๐Ÿ”น Difference Array Definition:

If you need to perform multiple range updates, a Difference Array lets you update entire subarrays efficiently:

diff[i] += val;
diff[j + 1] -= val;

Later, compute the final result with a prefix sum over the diff array.

๐Ÿ“– Prefix Sum Code Example

const nums = [2, 4, 5, 7];
const prefix: number[] = [0];

for (let i = 0; i < nums.length; i++) {
  prefix.push(prefix[i] + nums[i]);
}

// prefix = [0, 2, 6, 11, 18]
// Sum of elements from index 1 to 3 (4 + 5 + 7)
const sum = prefix[4] - prefix[1];
console.log(sum); // Output: 16

๐Ÿ”น Visualization

Original:      [ 2,  4,  5,  7 ]
Prefix Sum:    [ 0,  2,  6, 11, 18 ]
                         ^     ^
                       prefix[4] - prefix[1] = 16

๐Ÿค— Real-world Use Case: Rain Accumulation Tracker

Imagine you measure rainfall every day and want to calculate how much rain fell between Day 5 and Day 10. Instead of looping each time, prefix sums make it instantaneous!

๐Ÿšง Difference Array Code Example (Range Updates)

function applyRangeUpdates(length: number, updates: [number, number, number][]): number[] {
  const diff = new Array(length + 1).fill(0);

  for (const [start, end, val] of updates) {
    diff[start] += val;
    if (end + 1 < diff.length) diff[end + 1] -= val;
  }

  // Now compute the final array using prefix sum
  const result = new Array(length);
  result[0] = diff[0];
  for (let i = 1; i < length; i++) {
    result[i] = result[i - 1] + diff[i];
  }

  return result;
}

// Test
console.log(applyRangeUpdates(5, [ [1, 3, 2], [2, 4, 3] ]));
// Output: [0, 2, 5, 5, 3]

๐Ÿงฉ Use Cases

  • Querying sum of subarrays in constant time
  • Performing multiple range updates efficiently (instead of updating each index)
  • Problems involving cumulative totals, e.g. grades, scores, rainfall, distances

๐Ÿ”ฎ Big O Recap

Operation Time Complexity
Construct Prefix Sum O(n)
Range Sum Query (i to j) O(1)
Range Update using Difference O(1) per update
Final Array from Diff O(n)

๐Ÿงช Homework (LeetCode-style)

Problem: Range Sum Query

Function Signature:

function rangeSum(nums: number[], i: number, j: number): number;

Constraints:

  • 0 โ‰ค i โ‰ค j < nums.length
  • 1 โ‰ค nums.length โ‰ค 10^4

Example

Input: nums = [1, 3, 5, 7, 9], i = 1, j = 3
Output: 15 // 3 + 5 + 7

๐Ÿ” Hint: Precompute the prefix sum.

๐Ÿ“† Summary

  • Prefix Sum enables O(1) range sum queries.
  • Difference Arrays allow efficient bulk updates over a range.
  • Both are foundational tools in algorithmic optimization.

๐Ÿ”ฌ Coming Up

๐Ÿ”ผ Day 5: Binary Search Fundamentals Learn the divide-and-conquer powerhouse technique to search sorted arrays in logarithmic time.

This page was last edited on 2025-07-31 12:17

Powered by Wiki|Docs

This page was last edited on 2025-07-31 12:17

Tri Nguyen
No Copyright

Powered by Wiki|Docs