Skip to content

Commit c3a55c0

Browse files
medium java array hashmap BEST QUESTION
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. Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1.
1 parent e7f6ac7 commit c3a55c0

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

contiguous-array.java

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Approach
2+
// Initialize a hash map to store prefix sums along with their indices.
3+
// Initialize variables for sum, maximum subarray length, and iterate through the input array.
4+
// For each element in the array, update the sum according to the element (decrement by 1 for 0, increment by 1 for 1).
5+
// If the sum becomes zero at any index, update the maximum length to the current index plus one.
6+
// If the sum is encountered again (which means there is a subarray with equal 0s and 1s between the previous occurrence and the current index), update the maximum length if the current subarray length is greater than the previously stored maximum length.
7+
// Return the maximum subarray length.
8+
// Complexity Analysis
9+
// Time complexity: (O(n)), where (n) is the length of the input array. We traverse the array only once.
10+
// Space complexity: (O(n)), in the worst case, when all elements are distinct and the sum becomes distinct for each index, we would need to store all prefix sums in the hash map.
11+
12+
class Solution {
13+
public int findMaxLength(int[] nums) {
14+
int n=nums.length;
15+
Map<Integer,Integer> mp = new HashMap<>();
16+
int sum=0;
17+
int subarr=0;
18+
for(int i=0;i<n;i++){
19+
sum += nums[i] == 0 ? -1 : +1;
20+
if(sum==0){
21+
subarr=i+1;
22+
}
23+
else if(mp.containsKey(sum)){
24+
subarr=Math.max(subarr,i-mp.get(sum));
25+
}
26+
else{
27+
mp.put(sum,i);
28+
}
29+
}
30+
return subarr;
31+
}
32+
}

0 commit comments

Comments
 (0)