Repository containing solution for #SdeSheetChallenge by striver
Given an array of intervals where intervals[i] = [start i, end i], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
nextInterval
.currInterval[0]<=nextInterval[1]
.nextInterval
pair to max(nextInterval[1],currInterval[1])
.nextInterval
pair to result and change nextInterval
pair to currInterval
.// codestudio
vector<vector<int>> mergeIntervals(vector<vector<int>>& intervals)
{
int n = intervals.size();
vector<vector<int>> ans;
sort(intervals.begin(), intervals.end());
vector<int> nextInterval = intervals[0]; // first pair
for (auto& interval : intervals) {
if (interval[0] <= nextInterval[1]) {
nextInterval[1] = max(nextInterval[1], interval[1]);
} else {
ans.push_back(nextInterval);
nextInterval = interval;
}
}
ans.push_back(nextInterval);
return ans;
}
nextInterval
vector.vector.back()
and do the operations on it.class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals)
{
int n = intervals.size();
if (n <= 1) return intervals;
sort(intervals.begin(), intervals.end());
vector<vector<int>> ans;
ans.push_back(intervals[0]);
for (int i = 1; i < n; i++) {
if (intervals[i][0] <= ans.back()[1])
ans.back()[1] = max(ans.back()[1], intervals[i][1]);
else
ans.push_back(intervals[i]);
}
return ans;
}
};