Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

525. Contiguous Array 🌟🌟

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

Brute Force (TLE)

Code

class Solution {
public:
    int findMaxLength(vector<int>& nums)
    {
        int n = nums.size();
        int zeros = 0, ones = 0, mx = 0;
        for (int i = 0; i < n; i++) {
            zeros = 0, ones = 0;
            for (int j = i; j < n; j++) {
                nums[j] == 0 ? zeros++ : ones++;
                if (zeros == ones) mx = max(mx, j - i + 1);
            }
        }
        return mx;
    }
};

hashmap (AC)

Code

class Solution {
public:
    int findMaxLength(vector<int>& nums)
    {
        int n = nums.size();
        int mx = 0, sm = 0;
        unordered_map<int, int> mp;
        mp[0] = -1; // for first element there is no answer
        for (int i = 0; i < n; i++) {
            sm += (nums[i] == 0 ? -1 : 1);
            if (mp.count(sm)) mx = max(mx, i - mp[sm]);
            else mp[sm] = i;
        }
        return mx;
    }
};

READ MORE