Leetcode

πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- a simplistic view of the problem is just comparing the last value of the previous element with the first value of the current element
- how can we do this efficiently with our array
- the input array isnt sorted when passed into our function

πŸ€”What Did I Struggle With?

i read the question / example cases incorrectly and thought were were combinind all elements, not just appending the range

πŸ’‘ Explanation of Solution

1. Sort the input array
2. create a results vector and push the first element of out input array into it
3. iterate through the input array and check the last element in our results vector
4. compare the second value in our last element to the first value in our current element in the intervals array
5. make the second value in our last element the max between the two
6. return the results vector

βŒ› Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)
- an additional results vector of size n

πŸ’» Implementation of Solution

class Solution {
public:
Β  Β  vector<vector<int>> merge(vector<vector<int>>& intervals) {
Β  Β  Β  Β  sort(intervals.begin(), intervals.end());
Β  Β  Β  Β  vector<vector<int>> result;
Β  Β  Β  Β  result.push_back(intervals[0]);
Β  Β  Β  Β  
Β  Β  Β  Β  for(int i=1; i < intervals.size(); i++) {
Β  Β  Β  Β  Β  Β  vector<int>& last = result.back();
Β  Β  Β  Β  Β  Β  
Β  Β  Β  Β  Β  Β  if(last[1] >= intervals[i][0]) last[1] = max(last[1], intervals[i][1]);
Β  Β  Β  Β  Β  Β  else result.push_back(intervals[i]);
Β  Β  Β  Β  }
Β  Β  Β  Β  return result;
Β  Β  }
};