PrefixSum

437. Path Sum III

Maintain a local max and global max, update the max with current value (starting a new array) or max + current value (continuous array).

T: O(n) S: O(1)

    public int maxSubArray(int[] nums) {
        int max = nums[0], curtmax = nums[0];
        for (int i = 1; i < nums.length; i++) {
            curtmax = Math.max(curtmax + nums[i], nums[i]);
            max = Math.max(max, curtmax);
        }
        return max;
    }

Solution 2: Divide and Conquer

Solution 3: DP

def maxSubArray(self, nums: List[int]) -> int:
    dp = [0 for i in range(len(nums))]
    dp[0] = nums[0]
    maxx = nums[0]
    for i in range(1, len(nums)):
        dp[i] = max(dp[i - 1] + nums[i], nums[i])
        maxx = max(dp[i], maxx)
    return maxx

Use prefix sum and store the count of sum in a hashmap. When map.containsKey(sum - k), it indicates that there is a subarray sum which equals k, add it to the result.

Add a record to map (map.put(0, 1)), this give the count between any number 0, in case that number equals k.

T: O(n) S: O(n)

Addition to LC560, store the minimum subarray lens before i which sums to target in a min array. When the previous minimum prevMin exists, it means there is a subarray sums to sum - target. That lens is i - prevMin. The result is the current min and previous min, which is i - prevMin + min[prevMin].

523. Continuous Subarray Sum

Prefix + HashMap and get the maximum interval.

Maintain both positive and negative values in two arrays, update with current min/max.

Maintain a prefix product. When encounter 0, reset the prefix product list.

Add: T: O(1), GetProduct: T: O(1)

974. Subarray Sums Divisible by K

1413. Minimum Value to Get Positive Step by Step Sum

724. Find Pivot Index

Range Add Queries 2D: Difference Array Optimization

Problem Overview

Given an n × n matrix initialized to zeros, efficiently process multiple range update queries where each query adds 1 to all cells in a rectangular region [r1,c1] to [r2,c2].

Visual Demo

Example: n = 4, Queries: [[1,1,2,2], [0,0,1,1]]


Step 1: Process Query 1 - Add 1 to region [1,1] to [2,2]

Apply Difference Array Technique:

Step 2: Process Query 2 - Add 1 to region [0,0] to [1,1]

Accumulate difference markers:

Step 3: Apply Prefix Sum (Row-wise)

Convert difference array to actual values:

Final Result Matrix:


Algorithm Breakdown

Phase 1: Difference Array Setup

For each query [r1, c1, r2, c2]:

Visual for Query [1,1,2,2]:

Phase 2: Prefix Sum Restoration

Row-by-row transformation:


Key Insights

Difference Array Magic

  • Range increment [L, R] becomes two point updates: +1 at L, -1 at R+1

  • Prefix sum converts difference markers back to actual incremented values

  • Time complexity drops from O(Q × R × C) to O(Q × R + R × C)

Why This Works

  1. Lazy marking: Instead of updating every cell immediately, mark range boundaries

  2. Batch processing: Apply all difference markers first, then compute final values

  3. Cumulative effect: Multiple queries naturally accumulate at marked positions

Time Complexity: O(Q × R + R × C) where Q = queries, R = rows, C = columns Space Complexity: O(1) extra space (in-place on result matrix)

This technique is particularly powerful when the number of queries is large, transforming what would be expensive range updates into efficient boundary marking operations.

Last updated

Was this helpful?