56. Merge Intervals
Asked at 100Bloomberg88Meta85Apple84Amazon76Microsoft72Google65Tesla100Ozon96IBM95Walmart Labs93eBay86Visa84Atlassian84TikTok82Yandex78Morgan Stanley77Coupang76BNY Mellon75Palo Alto Networks74Stripe74MongoDB71General Motors65Infosys63Goldman Sachs61Salesforce59tcs57American Express53Capital One53Uber50Darwinbox100Grammarly100Grubhub100Ripple100Tesco100X97SAP96Nutanix96Zoho96Yelp94Nextdoor93Adobe91Chewy89Citadel89IXL88Wix87Sigmoid87GoDaddy87Millennium87Netflix85EarnIn84Siemens83Expedia79Hubspot78Wells Fargo75CrowdStrike74Patreon74ByteDance71PayPal71Okta71Remitly70Zalando69Verkada69AMD69Oracle69Twitch69athenahealth68VK68Geico66Deloitte65MakeMyTrip65razorpay65Zeta64Anduril63Wipro63Zomato62Snap62Barclays61Accenture61EPAM Systems60Nvidia60Autodesk59Swiggy59Dropbox58LinkedIn58Squarespace56Turing55ServiceNow55Sprinklr54Rippling54Moveworks53Samsung53Flipkart52Intuit52Applied Intuition48Juspay47Cisco45Roblox45DoorDash41Databricks37Pinterest36
Problem
Merge all overlapping intervals (intervals that merely touch, like [1,4] and [4,5], overlap too) and return the non-overlapping intervals that cover the same ranges.
Example: [[1,3],[2,6],[8,10],[15,18]] → [[1,6],[8,10],[15,18]]
Constraints: up to 10⁴ intervals.
Sort by start; if an interval starts before the last merged one ends, extend; otherwise start a new block.
Complexity: O(n log n).
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
res = []
for s, e in sorted(intervals):
if res and s <= res[-1][1]:
res[-1][1] = max(res[-1][1], e)
else:
res.append([s, e])
return res
assert Solution().merge([[1, 3], [2, 6], [8, 10], [15, 18]]) == [[1, 6], [8, 10], [15, 18]]
assert Solution().merge([[1, 4], [4, 5]]) == [[1, 5]]
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> res = new ArrayList<>();
for (int[] iv : intervals) {
if (!res.isEmpty() && iv[0] <= res.get(res.size() - 1)[1])
res.get(res.size() - 1)[1] = Math.max(res.get(res.size() - 1)[1], iv[1]);
else res.add(new int[]{iv[0], iv[1]});
}
return res.toArray(new int[0][]);
}
}
func merge(intervals [][]int) [][]int {
sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
res := [][]int{}
for _, iv := range intervals {
if n := len(res); n > 0 && iv[0] <= res[n-1][1] { // overlaps the last merged interval
res[n-1][1] = max(res[n-1][1], iv[1])
} else {
res = append(res, []int{iv[0], iv[1]})
}
}
return res
}