Typorithm · medium

Contiguous Array

contiguous-arrayprefix-sumsbalance-countfirst-seentransform
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Contiguous Array

0%

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.

01

Transform 0 → -1.

02

Repeated count = balanced span.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Empty at -1

Count 0 occurs before index 0, enabling from-start windows.

firstSeen.set(0, -1)

2. Map 0 to -1

Treat 0 as -1 so equal 0s and 1s cancel to count 0.

count += nums[i] === 1 ? 1 : -1

3. Equal stretch

A repeated running count means a balanced subarray between.

best = Math.max(best, i - firstSeen.get(count))

4. First index only

Store only the earliest index of each count for the longest span.

firstSeen.set(count, i)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Contiguous Array: Lesson & Practice · Typorithm | ApplyDjinn