1. Empty at -1
Count 0 occurs before index 0, enabling from-start windows.
firstSeen.set(0, -1)Typorithm · medium
Step 1 of 8 · intro card
Prefix Sums
Map 0 to -1 and track a running count; a repeated count marks a balanced subarray, with first-seen indices giving the longest.
An equal number of 0s and 1s means a running count (with 0 counted as -1) returns to a previous value.
Store the FIRST index at which each running count appears.
When a count repeats, the span between the two indices is balanced; keep the longest.
Transform 0 → -1.
Repeated count = balanced span.
Keep first-seen index for max length.
function findMaxLength(nums) {
const firstSeen = new Map();
firstSeen.set(0, -1);
let count = 0;
let best = 0;
for (let i = 0; i < nums.length; i += 1) {
count += nums[i] === 1 ? 1 : -1;
if (firstSeen.has(count)) {
best = Math.max(best, i - firstSeen.get(count));
} else {
firstSeen.set(count, i);
}
}
return best;
}Connect each part of the code to the concept before you type.
Count 0 occurs before index 0, enabling from-start windows.
firstSeen.set(0, -1)Treat 0 as -1 so equal 0s and 1s cancel to count 0.
count += nums[i] === 1 ? 1 : -1A repeated running count means a balanced subarray between.
best = Math.max(best, i - firstSeen.get(count))Store only the earliest index of each count for the longest span.
firstSeen.set(count, i)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.