Arrays and Hashing Prefix sums

78. Contiguous Array

Medium

You are given an array nums in which every element is either 0 or 1. Return the length of the longest subarray that holds as many 0s as 1s. If no such subarray exists, return 0.

A subarray is a contiguous sequence of elements from nums.

Example 1

Input: nums = [0, 1, 1, 1, 0, 0, 1, 1]

Output: 6

Explanation: The first six elements, [0, 1, 1, 1, 0, 0], hold three 0s and three 1s. A balanced subarray always has an even length, and the only longer one to try is the whole array, which holds five 1s and three 0s.

Example 2

Input: nums = [1, 0]

Output: 2

Explanation: The whole array holds one 0 and one 1, so the answer is its full length.

Example 3

Input: nums = [0, 1, 1, 1, 0]

Output: 2

Explanation: [0, 1] at the start and [1, 0] at the end are both balanced. Any longer stretch that holds both 0s also holds all three 1s, so the two 0s never fit in one balanced subarray.

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.