Subarray Sum TwoSum
This pattern solves a huge class of problems: “Find two elements that combine to form a Target”. Instead of checking every pair (O(N2)), we use a Hash Map to “remember” what we’ve seen so far, allowing us to find the complement in O(1).
Problem 1: Two Sum (LeetCode 1)
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Brute Force: Check every pair. O(N2). Hash Map:
- As we iterate through
x, we needysuch thatx + y = target. - Rewrite:
y = target - x. - Check if
yis already in our map.
Interactive Visualizer
Step through the algorithm to see how the map helps us find the answer in one pass.
Two Sum Explorer
Problem 2: Subarray Sum Equals K (LeetCode 560)
Given an array nums and integer k, find the total number of continuous subarrays whose sum equals k.
The Logic:
The sum of a subarray nums[i...j] is PrefixSum[j] - PrefixSum[i-1].
We want this to equal k.
PrefixSum[j] - PrefixSum[i-1] = k
Rearranging: PrefixSum[i-1] = PrefixSum[j] - k
So, as we iterate and calculate the running sum (current<sub>sum</sub>), we check: “How many times have I seen a prefix sum equal to current<sub>sum</sub> - k?”
Example Walkthrough
nums = [1, 1, 1], k = 2
- Init:
prefixSums = {0: 1},res = 0,curSum = 0 - i=0, n=1:
curSum= 1diff= 1 - 2 = -1 (Not in map)- Add 1 to map:
{0: 1, 1: 1}
- i=1, n=1:
curSum= 2diff= 2 - 2 = 0 (Found 1 in map!) →res+= 1- Add 2 to map:
{0: 1, 1: 1, 2: 1}
- i=2, n=1:
curSum= 3diff= 3 - 2 = 1 (Found 1 in map!) →res+= 1- Add 3 to map:
{0: 1, 1: 1, 2: 1, 3: 1}
Result: 2. (Subarrays: [1, 1] at start, [1, 1] at end).