Contiguous Array — LeetCode 525 Python Solution

MediumArrayHash TablePrefix Sum
Problem
#525
Pattern
Prefix Sum
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview