Leetcode 525. Contiguous Array

Problem Explanation

This problem provides a binary array which consists of 0s and 1s. The task is to find out the maximum length of a contiguous subarray that equals the number of 0s and 1s.

Example

Consider this example:

1
2python
3Input: [0,1,0,1,1,0]
4Output: 4
5Explanation: We can see [0, 1, 0, 1] has equal number of 0s and 1s. There are no longer subarrays with equal no. of 0s and 1s.

Solution Approach

In order to solve this problem, we'll be using a prefix sum along with a hash map. Initial prefix sum is set to zero, which we store in a hash map with index -1. We increment prefix sum if 1 is encountered while traversing, else decrement the sum.

Then we check if the calculated prefix sum is already present in the map. If it is present, we calculate the difference between current index and the index stored in map for that prefix sum. If the calculated difference is greater than current answer, we update the answer.

If prefix sum is not present in map, we store it with its index.

This basically means, if a certain sum is encountered twice, then the number of 1s and 0s are equal between these two indices.

Python Solution

1
2python
3class Solution:
4    def findMaxLength(self, nums):
5        
6        ans, prefix, prefixToIndex = 0, 0, {0: -1}
7        for i in range(len(nums)):
8            prefix += 2*nums[i] - 1
9            if prefix in prefixToIndex:
10                ans = max(ans, i - prefixToIndex[prefix])
11            else:
12                prefixToIndex[prefix] = i
13        return ans

Java Solution

1
2java
3class Solution {
4    public int findMaxLength(int[] nums) {
5        Map<Integer, Integer> map = new HashMap<>();
6        map.put(0, -1);
7        int maxlen = 0, count = 0;
8        for (int i = 0; i < nums.length; i++) {
9            count = count + (nums[i] == 1 ? 1 : -1);
10            if (map.containsKey(count)) {
11                maxlen = Math.max(maxlen, i - map.get(count));
12            } else {
13                map.put(count, i);
14            }
15        }
16        return maxlen;
17    }
18}

Javascript Solution

1
2javascript
3var findMaxLength = function (nums) {
4    let prefix = 0;
5    let ans = 0;
6    let map = new Map();
7    map.set(0, -1);
8    for (let i = 0; i < nums.length; i++) {
9        prefix += nums[i] == 0 ? -1 : 1;
10        if (map.has(prefix)) {
11            ans = Math.max(ans, i - map.get(prefix));
12        } 
13        else {
14            map.set(prefix, i);
15        }
16    }
17    return ans;
18};

C++ Solution

1
2c++
3class Solution {
4public:
5    int findMaxLength(vector<int>& nums) {
6    unordered_map<int, int> map;
7    int maxlen = 0, count = 0;
8    for (int i = 0; i < nums.size(); i++) {
9        count = count + (nums[i] == 1 ? 1 : -1);
10        if (map.count(count))
11            maxlen = max(maxlen, i - map[count]);
12        else
13            map[count] = i;
14    }
15    return maxlen;
16    }
17};

C# Solution

1
2csharp
3public class Solution {
4    public int FindMaxLength(int[] nums) {
5        Dictionary<int, int> map = new Dictionary<int, int>();
6        map[0] = -1;
7        int maxlen = 0, count = 0;
8        for(int i = 0; i < nums.Length; i++){
9            count = count + (nums[i]==1?1:-1);
10            if(map.ContainsKey(count)){
11               maxlen = Math.Max(maxlen, i - map[count]);
12            }
13            else{
14               map[count] = i;
15            }
16        }
17        return maxlen;
18    }
19}

Every solution referenced above follows the same basic approach of using a prefix sum and hash map data structure to compare sums and indices, adapting syntax and specific methods to the language in question. The syntax for each language does mean there are some slight differences in method names and the way structures like loops are expressed, but the underlying logic remains the same.

One of the most distinct differences is in type declaration. For instance, Java requires explicit type declaration. In Python, there's no need of that and everything is considered an object. JavaScript uses 'var' to declare type which is then inferred based on the value assigned to it.

Overall, the goal is to use the difference between current index and first occurrence of the computed prefix to find out the maximum length subarray with equal zeros and ones.

Remember to thoroughly understand the prompt and problem at hand before choosing the most appropriate language and solution for your specific use case. Understanding basic concepts such as loops, hash maps, and prefix sums are crucial to understanding and effectively solving this problem in all of these languages.


Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ