Sponsored
Sponsored
The idea is to transform the array by converting 0s to -1s, which allows us to restate the problem as finding the longest contiguous subarray with a sum of 0. We can use a hash map to store the first occurrence of each prefix sum.
Time Complexity: O(n), where n is the length of the input array.
Space Complexity: O(n) for the hash map storage.
1class Solution:
2 def findMaxLength(self, nums):
3 count_map = {0: -1}
4 max_length = count = 0
5 for i, num in enumerate(nums):
6 count += 1 if num == 1 else -1
7 if count in count_map:
8 max_length = max(max_length, i - count_map[count])
9 else:
10 count_map[count] = i
11 return max_length
12
This Python solution employs a dictionary to hold the first occurrence of each count value. We increment or decrement count based on the value, and check whether we have seen this balance previously to evaluate maximum subarray length.
This simple approach checks every possible subarray and calculates its sum, verifying if it has an equal number of 0s and 1s. This method, while simple, serves as an exercise in understanding the problem better prior to using an optimized solution.
Time Complexity: O(n^2)
Space Complexity: O(1), as we do not use extra space other than primitive variables.
1public
Employing nested loops, this Java solution checks all possible pairs of start and end indices within the array, verifying when counts of 0s and 1s match, and computing the maximum observed length.