Contiguous Array - Problem

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0s and 1s.

A contiguous subarray is a sequence of adjacent elements in the array.

Example: For array [0,1,0,0,1,1,0], the subarray [0,1,0,0,1,1] has 3 zeros and 3 ones, so the maximum length is 6.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,1]
Output: 2
💡 Note: The entire array has 1 zero and 1 one, so the maximum length is 2
Example 2 — Longer Array
$ Input: nums = [0,1,0,0,1,1,0]
Output: 6
💡 Note: The subarray [0,1,0,0,1,1] from index 0 to 5 has 3 zeros and 3 ones, length = 6
Example 3 — All Same
$ Input: nums = [0,0,0,0]
Output: 0
💡 Note: No subarray has equal number of 0s and 1s, so return 0

Constraints

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

Visualization

Tap to expand
Contiguous Array - Hash Map Approach INPUT Binary Array nums: 0 index 0 1 index 1 Find longest subarray with equal 0s and 1s Input Values: nums = [0, 1] Goal: Max length subarray count(0) == count(1) ALGORITHM STEPS 1 Replace 0 with -1 Convert: [0,1] to [-1,1] 2 Track Running Sum Sum = 0 means equal counts 3 Use Hash Map Store sum:first_index 4 Find Max Length If sum seen, calc length Hash Map Trace: idx val sum map - - 0 {0:-1} 0 0(-1) -1 {0:-1,-1:0} 1 1(+1) 0 Found! 1-(-1)=2 FINAL RESULT Maximum Contiguous Subarray: 0 1 Length = 2 Output: 2 OK - Verified! 1 zero + 1 one = equal Key Insight: By treating 0 as -1, finding equal 0s and 1s becomes finding subarrays with sum = 0. When the same cumulative sum appears twice, the subarray between those indices has equal counts. Time: O(n) | Space: O(n) for hash map storage TutorialsPoint - Contiguous Array | Hash Map Approach
Asked in
Facebook 45 Google 35 Amazon 30
180.0K Views
Medium Frequency
~25 min Avg. Time
3.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen