> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Contiguous Array Python Solution with Tests

> Tested Python solution for LeetCode 525 with 17 pytest cases. Generate a practice environment with lcpy.

LeetCode 525, Medium. Topics: Array, Hash Table, Prefix Sum. [View on LeetCode](https://leetcode.com/problems/contiguous-array/description/).

Generate this problem as a practice environment: tested reference solution, 17 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 525   # by problem number
lcpy gen -s contiguous_array   # by problem name
```

## Problem

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

### Examples

```
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.
```

### Constraints

* `1 <= nums.length <= 10^5`
* `nums[i]` is either `0` or `1`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/contiguous_array/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/contiguous_array/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
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
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(n)  |

## Tags

[Grind](/catalog/grind), [NeetCode All](/catalog/neetcode).
