✅✅Time O(N) || 100% Beats in C++ || Easy Solution With Explanation
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\nHere\'s an explanation of the approach:\n\n1. Initialization: Initializ
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nHere\'s an explanation of the approach:\n\n1. **Initialization**: Initialize an empty vector `ans` to store the resulting intervals. Also, initialize `i` to 0 for iterating through the existing intervals.\n\n2. **Merge Overlapping Intervals**:\n   - Iterate through the existing intervals.\n   - If the end of the current interval is before the start of the new interval (`newinterval[0] > intervals[i][1]`), it means there\'s no overlap, so push the current interval to the answer vector `ans`.\n   - If the start of the current interval is after the end of the new interval (`newinterval[1] < intervals[i][0]`), it means there\'s no overlap beyond this point, so break the loop.\n   - If there\'s overlap, update the new interval\'s start and end points to cover both the existing interval and the new interval.\n\n3. **Insert New Interval**: After the overlapping intervals are merged into the new interval, push this merged interval into the answer vector `ans`.\n\n4. **Append Remaining Intervals**: Finally, append any remaining intervals from the original list that were not merged with the new interval.\n\n5. **Return Result**: Return the modified answer vector `ans`.\n\nThis approach effectively merges any overlapping intervals with the new interval and ensures that the resulting intervals are sorted.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newinterval) {\n        int n=intervals.size();\n        vector<vector<int>> ans;\n        int i=0;\n\n        while(i<n){\n            if(newinterval[0]>intervals[i][1])\n            ans.push_back(intervals[i]);\n            else if(newinterval[1]<intervals[i][0])\n            break;\n            else {\n                newinterval[0]=min(newinterval[0],intervals[i][0]);\n                newinterval[1]=max(newinterval[1],intervals[i][1]);\n            }\n            i++;\n        }\n        ans.push_back(newinterval);\n\n        while(i<n){\n            ans.push_back(intervals[i]);\n            i++;\n        }\n\n        return ans;\n        \n    }\n};\n```\n\n\n#![Designer.png](https://assets.leetcode.com/users/images/def40eb5-2f11-4326-abbb-2623a553c1d5_1710672324.2541318.png)\n
['Array', 'C++']