Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Merge Intervals

Posted on January 10, 2018July 26, 2020 by braindenny

Merge Intervals



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #interval, #mergelist

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/merge-intervals
## Basic Ideas: sorting
##   [1, 3]
##     [2, 6]
##             [8, 10]
## Complexity: Time O(n*log(n)), Space O(1)
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if not intervals: return []
        intervals.sort()
        res = []
        for interval in intervals:
            # need to extend or already covered
            if res and res[-1][1] >= interval[0]:
                res[-1][-1] = max(res[-1][-1], interval[1])
            else:
                # empty or seperated
                res.append(interval)
        return res
linkedin
github
slack

Post Views: 5
Posted in BasicTagged #interval, mergelist

Post navigation

LeetCode: Second Minimum Node In a Binary Tree
LeetCode: Combinations

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.