Leetcode 525. Contiguous Array
Given a binary array nums
, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
To solve the problem, we need to find the longest contiguous subarray with an equal number of 0s and 1s. To achieve this, we can use a hashmap to track the first occurrence of each count difference we encounter as we iterate through the array.
Here’s the detailed approach:
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int, int> count_map;
count_map[0] = -1; // To handle the case when subarray starts from index 0
int max_length = 0;
int count = 0;
for (int i = 0; i < nums.size(); ++i) {
count += (nums[i] == 1) ? 1 : -1;
if (count_map.find(count) != count_map.end()) {
max_length = max(max_length, i - count_map[count]);
} else {
count_map[count] = i;
}
}
return max_length;
}
};
The time complexity of this solution is O(n), where n is the length of the array. This is because we make a single pass through the array, with constant time operations for each element using the hashmap.
The space complexity is O(n) as we might store up to n entries in the hashmap in the worst case.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?