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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int FindMaxLength(int[] nums) {
6 Dictionary<int, int> countMap = new Dictionary<int, int>{{0, -1}};
7 int maxLength = 0, count = 0;
8 for (int i = 0; i < nums.Length; i++) {
9 count += nums[i] == 1 ? 1 : -1;
10 if (countMap.ContainsKey(count)) {
11 maxLength = Math.Max(maxLength, i - countMap[count]);
12 } else {
13 countMap[count] = i;
14 }
15 }
16 return maxLength;
17 }
18}
19
This C# solution uses a Dictionary to register the first place each net count value appears during a single loop over the array. We adjust the counts for 0s and 1s and use this to determine the valid 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.
1#
This brute-force method iterates over each possible starting point and ending point of a subarray, counting the number of 0s and 1s and checking their equality. This gives a straightforward, albeit inefficient solution.