8. Contiguous Array

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

Example 1:

Input: nums = [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.

Example 2:

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

Solution: (Hashing)

class Solution
{
public:
    int findMaxLength(vector<int> &nums)
    {

        int count = 0;
        int res = 0;
        unordered_map<int, int> m;
        
        m[0] = -1;
        
        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] == 1)
            {
                count--;
            }
            else
            {
                count++;
            }

            if (m.find(count) != m.end())
            {
                int dif = i - m[count];
                res = max(res, dif);
            }
            else
            {
                m[count] = i;
            }
        }

        return res;
    }
};

Time Complexity: O(n)

Last updated