Contiguous Array

Medium Arrays & Hashing Prefix Sum Strategy Original on LeetCode

Contiguous Array is a medium arrays & hashing problem solved with the prefix sum strategy pattern. The best approach, optimal (prefix balance + first-seen map), runs in O(n) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (every start, extend right) up.

Problem

You are given a binary array nums (every element is 0 or 1). Find the length of the longest contiguous subarray that contains the same number of 0s and 1s.

If no such subarray exists, return 0.

Examples

Example 1

Input
nums = [1, 1, 0, 1, 0, 0, 1]
Output
6
Why
The window [1, 0, 1, 0, 0, 1] (indices 1 to 6) has three 0s and three 1s; no window of length 7 is balanced because 7 is odd.

Example 2

Input
nums = [0, 0, 0, 1]
Output
2
Why
Only the last two elements [0, 1] are balanced.

Example 3

Input
nums = [1, 1, 1]
Output
0
Why
There is no 0 at all, so no balanced subarray exists.

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (every start, extend right)O(n²)O(1)
Optimal (prefix balance + first-seen map)O(n)O(n)

1Brute force (every start, extend right)

TimeO(n²)Every pair (i, j) is visited once.
SpaceO(1)Only two counters.

Fix a start index and grow the window to the right, keeping a running count of zeros and ones. Every time the two counts match, the window is balanced and its length is a candidate.

  1. For each start i, set zeros = ones = 0.
  2. For each end j >= i, increment zeros or ones for nums[j].
  3. If zeros == ones, update best with j - i + 1.
  4. Return best.
class Solution {
    public int findMaxLength(int[] nums) {
        int n = nums.length, best = 0;
        for (int i = 0; i < n; i++) {
            int zeros = 0, ones = 0;
            for (int j = i; j < n; j++) {
                if (nums[j] == 0) zeros++; else ones++;
                if (zeros == ones) best = Math.max(best, j - i + 1);
            }
        }
        return best;
    }
}

2Optimal (prefix balance + first-seen map)

TimeO(n)One pass with O(1) map operations per element.
SpaceO(n)The balance ranges over at most 2n + 1 values, each stored once.

Walk the array keeping a balance: +1 for a 1 and -1 for a 0. If the balance at index j equals the balance at an earlier index i, the elements between them contain as many 0s as 1s. Store the first index at which each balance appears (balance 0 at index -1), so the window for a repeated balance is as long as possible.

  1. Create a map with balance 0 -> index -1.
  2. For each index j, add +1 for a 1 or -1 for a 0 to balance.
  3. If balance is already in the map, update best with j - map[balance].
  4. Otherwise store balance -> j (only the first occurrence is kept).
  5. Return best.
class Solution {
    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> first = new HashMap<>();
        first.put(0, -1);
        int balance = 0, best = 0;
        for (int j = 0; j < nums.length; j++) {
            balance += nums[j] == 1 ? 1 : -1;
            Integer i = first.get(balance);
            if (i != null) best = Math.max(best, j - i);
            else first.put(balance, j);
        }
        return best;
    }
}

Edge cases to test

  • All zeros or all ones: the answer is 0
  • The whole array is balanced
  • A single element
  • The best window starts at index 0 (prefix balance returns to 0)

Hints

Hint 1

Replace every 0 with -1. A balanced subarray is then a subarray whose sum is 0.

Hint 2

A subarray i+1..j sums to 0 exactly when the prefix sums at i and j are equal.

Hint 3

Remember the first index where each prefix sum appeared; the longest window for that sum ends at the latest index.

FAQ

What is the best time complexity for Contiguous Array?

Optimal (prefix balance + first-seen map) runs in O(n) time and O(n) extra space. One pass with O(1) map operations per element.

Which pattern does Contiguous Array use?

It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Range Sum Query - Immutable.

Is there a brute force solution for Contiguous Array?

Yes. Brute force (every start, extend right) takes O(n²) time and O(1) space. Fix a start index and grow the window to the right, keeping a running count of zeros and ones.

Which edge cases should I test for Contiguous Array?

All zeros or all ones: the answer is 0; The whole array is balanced; A single element; The best window starts at index 0 (prefix balance returns to 0).