🤖
Data Structures and Algorithms
  • CS Theory And Problems
  • Big O
    • Big O Notation
  • Algorithms
    • Binary Search
    • Breadth First Search (BFS)
    • Depth First Search (DFS)
    • Dynamic Programming
    • Kadane's Algorithm
    • Kahn's Algorithm
    • Quickselect
    • Recursion
    • Sorting Algorithms
    • Sliding Window
  • Data Structures
    • Binary Heap
    • Graph
    • Linked List
    • Trees
  • Problems
    • LeetCode
      • 1. Two Sum
      • 3. Longest Substring Without Repeating Characters
      • 5. Longest Palindromic Substring
      • 11. Container With Most Water
      • 15. 3 Sum
      • 19. Remove Nth Node From End of List
      • 20. Valid Parentheses
      • 33. Search in Rotated Sorted Array
      • 49. Group Anagrams
      • 53. Maximum Subarray
      • 55. Jump Game
      • 56. Merge Intervals
      • 76. Minimum Window Substring
      • 98. Validate Binary Search Tree
      • 105. Construct Binary Tree from Preorder and Inorder Traversal
      • 121. Best Time to Buy and Sell Stock
      • 133. Clone Graph
      • 141. Linked List Cycle
      • 152. Maximum Product Subarray
      • 153. Find Minimum in Rotated Sorted Array
      • 200. Number of Islands
      • 206. Reverse Linked List
      • 207. Course Schedule
      • 217. Contains Duplicate
      • 226. Invert Binary Tree
      • 238. Product of Array Except Self
      • 242. Valid Anagram
      • 297. Serialize and Deserialize Binary Tree
      • 347. Top K Frequent Elements
      • 417. Pacific Atlantic Water Flow
      • 424. Longest Repeating Character Replacement
      • 435. Non-overlapping Intervals
      • 647. Palindromic Substrings
Powered by GitBook
On this page
  • Description
  • Solution
  • LeetCode's solution
  • My Solution
  1. Problems
  2. LeetCode

56. Merge Intervals

Description

See: https://leetcode.com/problems/merge-intervals/

Solution

LeetCode's solution

https://leetcode.com/problems/merge-intervals/solution/

Note: the merge may occur on more than two items. For example:

[[1,3], [1,2], [3,4], [6,10]] -> [[1,4], [6,10]]

My Solution

Strategy

Sort the array, this will put the intervals in ascending order.

Example: [[1,3], [6,10], [3,4], [1,2]] -> [[1,2], [1,3], [3,4], [6,10]]

This allows us to compare adjacent cells to see if they overlap.

So, if we have two pairs [x1, y1] and [x2, y2], we need to compare x1 and y2. If x1 <= y2 then the two pairs overlap and can be merged. The merge interval will be x1 and then the max of y1 and y2: [x1,max(y1,y2)]

Otherwise, the pairs do not overlap and the pair can just be appended to the result array. We always need to compare against the tail of the array as we merge the pairs into the tail of the result array.

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        result = []
        intervals.sort(key=lambda x:(x[0], x[1]))
        result.append(intervals[0])
        for i in range(1, len(intervals)):
            if intervals[i][0] <= result[-1][1]:
                result[-1] = [result[-1][0], max(intervals[i][1], result[-1][1])]
            else:
                result.append(intervals[i])
        return result

Time complexity: O(n log n) - this is from the sort operation. There is one loop which is O(n), so the above code is O(n log n) + O(n), but this reduces to O(n log n).

Space complexity: worst case is O(n) which is from the Timsort sorting algorithm used by Python.

What I learned

To merge items, add the first item to the result array. Then iterate through the list and either update the tail item in the result array or append a the item to the result array.

This is easier than trying to handle the merge by taking two items from the array, merging them and then inserting into the array. This was convoluted when I needed to then compare the merged item to the next item in the array. I figured out that I needed to sort the array in order to compare the items.

Previous55. Jump GameNext76. Minimum Window Substring

Last updated 1 year ago