Skip to content

Latest commit

 

History

History
78 lines (59 loc) · 1.9 KB

LC525.md

File metadata and controls

78 lines (59 loc) · 1.9 KB

Problem: Contiguous Array

Difficulty: Medium

Description:

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Examples:

Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Constraints:

The length of the given binary array will not exceed 50,000.

Solutions:

The naive appraoch is always to produce all of the subarrays and find the one that meets the objective. This approach has a time complexity of O(N^3) and space complexity of O(N) where N is the size of array.

def findMaxLength(nums):
    """
    :type nums: List[int]
    :rtype: int
    :Time Complexity: O(N^3)
    :Space Complexity: O(N)
    """
    maxLen = 0

    for i in range(len(nums)):
        for j in range(i, len(nums)):
            sub = nums[i : j + 1]
            if len(sub) == 2 * sum(sub):
                maxLen = max(maxLen, len(sub))

    return maxLen

For the optimal solution, we can instead solve the maximum subarray problem with the given sum of 0. In this case, we need to update the 0 in nums with -1. To do this, we can use the Prefix-Sum algorithm. This approach has a time complexity of O(N) and space complexity of O(N) where N is the size of array.

def findMaxLength(nums):
    """
    :type nums: List[int]
    :rtype: int
    :Time Complexity: O(N)
    :Space Complexity: O(1)
    """
    for i in range(len(nums)):
        if nums[i] == 0:
            nums[i] = -1

    current_sum = 0
    maxLen = 0
    seen = {0: -1}

    for i in range(len(nums)):
        current_sum += nums[i]

        if current_sum not in seen:
            seen[current_sum] = i

        maxLen = max(maxLen, i - seen[current_sum])

    return maxLen