75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

56. Merge Intervals (Medium)

O(N^2) Time Solution

O(NlogN) Time O(N) Space Solution

class Solution{
public:
	vector<vector<int>> merge(vector<vector<int>> &intervals){
		int n = intervals.size();
		vector<vector<int>> ans;
		if (n == 0) return ans;

		sort(intervals.begin(), intervals.end());
		vector<int> temp = intervals[0]; // first pair

		for (auto &x : intervals){
			if (temp[1] >= x[0]){
				temp[1] = max(temp[1], x[1]);
			}
			else{
				ans.push_back(temp);
				temp = x;
			}
		}
		ans.push_back(temp);
		return ans;
	}
};

O(NlogN) Time O(1) Space Solution

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 (ans.back()[1] >= intervals[i][0])
				ans.back()[1] = max(ans.back()[1], intervals[i][1]);
			else
				ans.push_back(intervals[i]);
		}
		return ans;
	}
};