You are given an array of non-overlapping intervals intervals
where intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]
represent the start and the end of the i<sup>th</sup>
interval and intervals
is sorted in ascending order by start<sub>i</sub>
. You are also given an interval newInterval = [start, end]
that represents the start and end of another interval.
Insert newInterval
into intervals
such that intervals
is still sorted in ascending order by start<sub>i</sub>
and intervals
still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals
after the insertion.
Note that you don't need to modify intervals
in-place. You can make a new array and return it.
LeetCode Problem - 57
import java.util.HashMap;
import java.util.Map;
class Solution {
// Method to find the maximum length of a contiguous subarray with equal number of 0s and 1s
public int findMaxLength(int[] nums) {
// Convert 0s to -1s to simplify the problem
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0) nums[i] = -1;
}
// Create a map to store the running sum and its corresponding index
Map<Integer, Integer> hm = new HashMap<>();
int maxLen = 0; // Initialize the maximum length of subarray
int sum = 0; // Initialize the running sum
for (int i = 0; i < nums.length; i++){
sum += nums[i]; // Update the running sum
// If the running sum becomes 0, update maxLen to include the current subarray
if (sum == 0){
maxLen = Math.max(maxLen, (i + 1));
}
// If the running sum is encountered before, update maxLen accordingly
if (hm.containsKey(sum)){
maxLen = Math.max(maxLen, i - hm.get(sum));
} else {
// Otherwise, put the current sum and its index into the map
hm.put(sum, i);
}
}
// Return the maximum length of the subarray
return maxLen;
}
}