#525
Contiguous Array
MediumArrayHash TablePrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a hash map to track the cumulative count of 0s and 1s. By treating 0 as -1, we can find subarrays with equal counts by checking for the same cumulative sum at different indices.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a hash map to store the first occurrence of each cumulative sum.
- 2Step 2: Initialize variables for cumulative sum and maximum length.
- 3Step 3: Iterate through the array, updating the cumulative sum (increment for 1, decrement for 0).
- 4Step 4: If the cumulative sum has been seen before, calculate the length of the subarray and update the maximum length if it's longer.
- 5Step 5: If the cumulative sum hasn't been seen, store its index in the hash map.
- 6Step 6: Return the maximum length found.
solution.py13 lines
1# Full working Python code
2
3def findMaxLength(nums):
4 count_map = {0: -1}
5 max_length = 0
6 count = 0
7 for i, num in enumerate(nums):
8 count += 1 if num == 1 else -1
9 if count in count_map:
10 max_length = max(max_length, i - count_map[count])
11 else:
12 count_map[count] = i
13 return max_lengthℹ
Complexity note: The time complexity is O(n) because we traverse the array once. The space complexity is O(n) due to the hash map storing cumulative sums.
- 1Transforming the problem by treating 0 as -1 allows us to use cumulative sums effectively.
- 2Using a hash map to store indices of cumulative sums helps in quickly finding the lengths of subarrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.