MediumNo. 0525
Contiguous Array — LeetCode 525 Python Solution
- Pattern
- Prefix Sum
- Topics
- Array, Hash Table, Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Example
- Input
- nums = [0,1]
- Output
- 2
- Explanation
- [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
Python solution
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
d = {0: -1}
ans = s = 0
for i, x in enumerate(nums):
s += 1 if x else -1
if s in d:
ans = max(ans, i - d[s])
else:
d[s] = i
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)where n is the length of the array
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 525. Contiguous Array is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0523 | Continuous Subarray Sum | Medium |
| 0560 | Subarray Sum Equals K | Medium |
| 0930 | Binary Subarrays With Sum | Medium |
| 0974 | Subarray Sums Divisible by K | Medium |
| 1074 | Number of Submatrices That Sum to Target | Hard |
| 1124 | Longest Well-Performing Interval | Medium |
Frequently asked questions
- How hard is LeetCode 525. Contiguous Array?
LeetCode 525. Contiguous Array is rated Medium on LeetCode.
- What is the time complexity of LeetCode 525. Contiguous Array?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 525. Contiguous Array?
The Python solution on this page uses O(n), where n is the length of the array auxiliary space.
- What topics does LeetCode 525. Contiguous Array cover?
LeetCode 525. Contiguous Array is tagged Array, Hash Table and Prefix Sum on LeetCode.