525. Contiguous Array
Explanation:
We can solve this problem by keeping track of the running sum of zeros and ones encountered while iterating through the array. We store the running sum in a hashmap where the key is the running sum and the value is the index at which that running sum was encountered. If we encounter the same running sum again, it means that the subarray between the two occurrences has equal numbers of zeros and ones. We calculate the length of this subarray and update the maximum length found so far.
Algorithm:
- Initialize a hashmap
map
with key 0 and value -1. - Initialize variables
maxLen
to store the maximum length found so far andcount
to keep track of the running sum (count of ones - count of zeros). - Iterate through the input array.
- For each element, update the
count
variable accordingly (increment by 1 if it is 1, decrement if it is 0). - If
count
is already present in themap
, calculate the length of the subarray and updatemaxLen
if needed. - If
count
is not in themap
, add it with the current index. - Return
maxLen
as the result.
Time Complexity:
The time complexity of this approach is O(n), where n is the length of the input array.
Space Complexity:
The space complexity of this approach is O(n), where n is the length of the input array.
class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int maxLen = 0, count = 0;
for (int i = 0; i < nums.length; i++) {
count += nums[i] == 1 ? 1 : -1;
if (map.containsKey(count)) {
maxLen = Math.max(maxLen, i - map.get(count));
} else {
map.put(count, i);
}
}
return maxLen;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.