Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Amazon
Google
Contiguous Array

Find the longest contiguous subarray with the same number of 0s and 1s.

Acceptance 0%
Problem Statement

Given a binary array, return the length of the longest contiguous subarray that contains an equal number of 0s and 1s.

A subarray must be contiguous and non-empty. If no such subarray exists, return 0.

Input Format

  • An integer array nums consisting only of 0 and 1.
  • The array length is n.

Output Format

  • Return a single integer: the maximum length of a contiguous subarray with equal numbers of 0 and 1.

Constraints

  • 1n1 \le n
  • nums[i] \in {0, 1}
  • Return 0 if no balanced subarray exists.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [0,1]

Output

2

Explanation

The whole array has one 0 and one 1, so the longest balanced subarray has length 2.

Example 2

Input

nums = [0,1,0]

Output

2

Explanation

The subarrays [0,1] and [1,0] are balanced, both with length 2.

Show 1 more example

Example 3

Input

nums = [0,0,1,0,0,0,1,1]

Output

6

Explanation

One longest balanced subarray is [0,1,0,0,0,1] after transforming 0 to -1 and finding a repeated prefix sum distance of 6.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.