Back to Arrays
Q42Question 42 of 109

Contiguous Array (Equal Zeros and Ones): Convert Zero to Minus One, Prefix Sum Plus HashMap

Key Concepts
  • Replace every 0 with -1 so equal counts of 0s and 1s become a subarray summing to zero.
  • A subarray sums to zero when the running prefix sum repeats: the span between equal sums is balanced.
  • Store the first index of each prefix-sum value in a HashMap; when a sum repeats, compute the span length.
  • Seed the map with sum 0 at index -1 so balanced subarrays starting at index 0 are counted.
  • Store first occurrence only (never overwrite) because this is a longest-span problem and the earliest index maximizes length.
  • O(n) time and O(n) space for the map.
  • This contrasts with Subarray Sum Equals K, which stores counts for a counting problem.

Definition

Turn zeros into minus ones; equal counts mean the running sum repeats, so the gap between equal sums is a balanced subarray.
  • Transform – replace every 0 with -1 so equal zeros and ones become a subarray summing to zero.
  • Prefix-sum repetition – a subarray sums to zero when prefix[j] == prefix[i]; the span j - i is balanced.
  • HashMap – stores the first index at which each prefix-sum value appeared.
  • Seed – map.put(0, -1) handles balanced subarrays starting at index 0.
  • First-occurrence bookkeeping – store only the first index, never overwrite, to maximize span length.
  • O(n) time, O(n) space.

The National Bank of India logs each trading day for an index fund as an up day (1) or a down day (0) and wants the longest stretch where ups and downs perfectly balance. The clerk rewrites each down day as -1, keeps a running total, and notes the first day each total value appeared. Whenever the running total returns to a value it hit before, the stretch in between is balanced.

Understanding the Concepts

What is the Contiguous Array problem?

Given a binary array of 0s and 1s, find the length of the longest contiguous subarray that contains an equal number of 0s and 1s. For example, in [0, 1, 0, 1, 1, 0], the answer is 6 (the entire array has three 0s and three 1s).

What is the clever transformation?

Replace every 0 with -1. After this, a subarray has equal 0s and 1s exactly when its elements sum to zero: each 1 contributes +1 and each former 0 contributes -1, and they cancel only when counts are equal.

TEXT
Original: [0, 1, 0, 1, 1, 0]
Mapped:   [-1, 1, -1, 1, 1, -1]

Running sum: -1, 0, -1, 0, 1, 0
             ↑       ↑     ↑
          sum=-1   sum=-1  sum=0 (repeat!)

How does the prefix sum plus HashMap find the longest balanced span?

A subarray from index i+1 to j sums to zero when prefix[j] == prefix[i]. To maximize the span, store the first occurrence of each prefix-sum value. When the sum repeats at index j, the span j - firstIndex is balanced, and using the earliest first occurrence maximizes the length.

How do you implement it? (with code)

JAVA
package com.bank.analytics;

import java.util.HashMap;
import java.util.Map;

public class ContiguousArray {

    public static int findMaxLength(int[] tradingDays) {
        Map<Integer, Integer> firstSeen = new HashMap<>();
        firstSeen.put(0, -1);  // seed: sum 0 first seen at virtual index -1

        int sum = 0;
        int best = 0;

        for (int i = 0; i < tradingDays.length; i++) {
            sum += (tradingDays[i] == 1) ? 1 : -1;

            if (firstSeen.containsKey(sum)) {
                best = Math.max(best, i - firstSeen.get(sum));
            } else {
                firstSeen.put(sum, i);  // store first occurrence only
            }
        }
        return best;
    }

    public static void main(String[] args) {
        // 1 = up day, 0 = down day
        int[] days = {0, 1, 0, 1, 1, 0};
        System.out.println("Longest balanced stretch: " + findMaxLength(days));
    }
}
TEXT
Longest balanced stretch: 6

Why seed with sum 0 at index -1?

The seed handles balanced subarrays that start at index 0. If the running sum returns to zero at index j, the length is j - (-1) = j + 1, which correctly counts the entire prefix. Without the seed, these subarrays would be missed.

Why store first occurrence only?

This is a longest-span problem, not a count problem. Keeping the earliest index maximizes the gap between the first and current occurrence of the same prefix sum. Overwriting with a later index would shorten the potential span.

How is this different from Subarray Sum Equals K?

Both use prefix sums with a HashMap, but the bookkeeping differs.

| Problem | Goal | Map stores | Key insight |
|---|---|---|---|
| Subarray Sum Equals K | Count subarrays | Frequency of each prefix sum | Count matching prefixes |
| Contiguous Array | Longest balanced span | First index of each prefix sum | Maximize distance between matches |

What are the edge cases?

  • All 0s or all 1s – no balanced subarray exists; return 0.
  • Already balanced – the entire array is the answer.
  • Length 1 – cannot be balanced; return 0.
  • Alternating 0-1 – every even-length prefix is balanced.

What about the walkthrough with the map?

DIAGRAM
Array: [0, 1, 0, 1, 1, 0]
Map seed: {0: -1}

i=0: sum=-1, not in map → map={0:-1, -1:0}
i=1: sum=0, in map at -1 → span=1-(-1)=2, best=2
i=2: sum=-1, in map at 0 → span=2-0=2, best=2
i=3: sum=0, in map at -1 → span=3-(-1)=4, best=4
i=4: sum=1, not in map → map adds {1:4}
i=5: sum=0, in map at -1 → span=5-(-1)=6, best=6

Answer: 6

What are common interview follow-up questions?

  • What about equal counts of three symbols? – Reduce to two balance conditions and use a tuple as the map key.
  • Can you return the actual subarray? – Store bestStart and bestEnd when best is updated.
  • What about counting balanced subarrays? – Store frequency instead of first index.

Visual Overview

DIAGRAM
┌──────────────────────────────────────────────────────┐
│  Contiguous Array: Zero-to-MinusOne Transform        │
├──────────────────────────────────────────────────────┤
│                                                      │
│  Original: [0, 1, 0, 1, 1, 0]                       │
│  Mapped:   [-1, 1, -1, 1, 1, -1]                    │
│                                                      │
│  Running sum: -1, 0, -1, 0, 1, 0                    │
│                                                      │
│  Map (first index of each sum):                      │
│    sum  0 → index -1 (seed)                          │
│    sum -1 → index  0                                 │
│    sum  1 → index  4                                 │
│                                                      │
│  sum=0 repeats at i=1,3,5 → spans from -1:           │
│    i=1: 1-(-1) = 2                                   │
│    i=3: 3-(-1) = 4                                   │
│    i=5: 5-(-1) = 6  ← longest                       │
└──────────────────────────────────────────────────────┘

Key Takeaway

Finding the longest contiguous subarray with equal zeros and ones hinges on one transformation: replace every 0 with -1. After that, a subarray is balanced exactly when its elements sum to zero. You keep a running sum and a HashMap of the first index at which each sum appeared, seeded with sum 0 at index -1. When the sum repeats, the span between the first occurrence and the current index is balanced, and storing only the first occurrence maximizes the span.

The contrast with Subarray Sum Equals K is important. There you store frequencies because you are counting matches. Here you store first indices because you are maximizing a length. The prefix-sum-plus-map idea is the same, but the bookkeeping flips depending on whether the question asks how many or how long.

The seed of sum 0 at index -1 handles balanced subarrays starting from index 0, and is the usual bug source if omitted. Never overwrite a map entry, because a later index would shorten the potential span.

In a banking project at the National Bank of India, the analytics team tags each trading day as up or down and finds the longest sideways market period where ups exactly equal downs.

Remember one sentence: Transform 0 to -1, track the first index of each running sum, and the longest span between equal sums is the longest balanced subarray.

---

Share
Use ← → arrow keys to navigate