Merge Overlapping Intervals
Updated
Problem statement
Given an array intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return an array of the intervals that are left. Together they must cover exactly the same points as the input, and no two of them may overlap.
Each interval includes both of its ends. Two intervals overlap when they share at least one point, so intervals that only touch at an end also merge: [1,4] and [4,5] become [1,5]. Intervals such as [1,2] and [3,4] share no point and stay apart.
The input can be in any order. Return the merged intervals sorted by their start, from smallest to largest.
Function
merge(intervals: int[][]) → int[][]Examples
Example 1
intervals = [[1,4],[3,7],[9,12],[10,11]]return = [[1,7],[9,12]][1,4] and [3,7] share the points 3 and 4, so they merge into [1,7]. [10,11] lies inside [9,12], so together they cover [9,12]. Nothing joins [1,7] to [9,12], because 8 is not covered.
Example 2
intervals = [[6,8],[1,2],[2,5]]return = [[1,5],[6,8]]The input is not sorted. [1,2] and [2,5] touch at 2, so they merge into [1,5]. [6,8] starts after 5, so it stays on its own. The answer is sorted by start.
Example 3
intervals = [[3,5],[0,0],[6,9]]return = [[0,0],[3,5],[6,9]][0,0] covers only the point 0. [3,5] and [6,9] do not touch, since no point lies in both, so nothing merges. The three intervals are returned sorted by start.
Constraints
1 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i <= end_i <= 10^4
More Shnoor International Onsite Interview questions
Similar questions at other companies
- Count Winning Dice Face PairsGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Generate All Permutations of a NumberFleetx · ONSITE INTERVIEW
- Rank Word-Translation Hints from Sentence TranslationsDuolingo · PHONE SCREEN · ONSITE INTERVIEWDuolingo interview questions
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN · ONSITE INTERVIEW
- Fair Capped Money DistributionGusto · PHONE SCREEN · ONSITE INTERVIEWGusto interview questions
- Group AnagramsAmazon Web Services · ONSITE INTERVIEWAmazon Web Services interview questions
- Merge IntervalsApple · OA · PHONE SCREEN · ONSITE INTERVIEWApple interview questions
- Merge Sorted Squares of Two ArraysWhatNot · PHONE SCREEN · ONSITE INTERVIEWWhatNot interview questions
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Filter, Sort, and Deduplicate Scheduled TasksRippling · PHONE SCREEN · ONSITE INTERVIEWRippling interview questions