Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the longest subarray with equal 0s and 1s

Given a binary array, return the length of the longest contiguous subarray with equal numbers of 0s and 1s.

Python practice28 minHashing & SetsAdvancedLast updated March 26, 2026

Problem statement

Given an array containing only 0s and 1s, find the length of the longest contiguous subarray that contains an equal number of 0s and 1s. Convert 0s to -1s and track prefix sums; the longest distance between identical prefix sums indicates a balanced subarray.

Task

Use prefix sums and hashing to detect subarrays with equal counts efficiently (O(n) time, O(n) space).

Examples

Example 1

Input

longest_equal_subarray([0, 1, 0, 1, 1, 0])

Output

6

The whole array has three 0s and three 1s, so length is 6.

Input format

A list of integers containing only 0 and 1

Output format

An integer representing the maximum length of a contiguous subarray with equal 0s and 1s

Constraints

0 <= len(arr) <= 10^5; arr[i] in {0,1}; target O(n) time using hashmap of prefix sums

Samples

Sample 1

Input

[0,1,0,1,1,0]

Output

6

Full array balances to length 6