Problem
Given a binary arraynums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Examples
Constraints
1 <= nums.length <= 10^5nums[i]is either0or1.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 525 with 17 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 525 # by problem number
lcpy gen -s contiguous_array # by problem name
nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
Input: nums = [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Input: nums = [0,1,1,1,1,1,0,0,0]
Output: 6
Explanation: [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1.
1 <= nums.length <= 10^5nums[i] is either 0 or 1.class Solution:
# Time: O(n)
# Space: O(n)
def find_max_length(self, nums: list[int]) -> int:
count_map = {0: -1}
count = 0
max_len = 0
for i, num in enumerate(nums):
count += 1 if num == 1 else -1
if count in count_map:
max_len = max(max_len, i - count_map[count])
else:
count_map[count] = i
return max_len
| Time | Space |
|---|---|
| O(n) | O(n) |