logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›leetcode›medium

56. Merge Intervals

# Question

Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the original intervals.

# Solution

# Pattern

Sort and Sweep (Intervals) Sort the intervals based on their start times. Iterate through them, maintaining the "active" interval. If the next interval starts before the active one ends, extend the active interval's end time. Otherwise, finalize the active interval and start a new one.

# How to Identify

  • The input is a collection of start/end pairs (events, meetings, ranges).
  • The problem asks for overlapping, merging, or finding intersections.
  • A brute force comparison of every interval against every other interval would be O(N2)O(N^2)O(N2), hinting that sorting O(Nlog⁡N)O(N \log N)O(NlogN) will unlock a linear O(N)O(N)O(N) pass.

# Description

Step-by-step explanation:

  1. Sort: Sort the intervals primarily by their starting times in ascending order. This guarantees that as we iterate, we will never encounter an interval that starts before the ones we've already processed.
  2. Initialize: Create a dynamic List to hold our finalized intervals. Add the very first interval from our sorted array into this list. This becomes our "currently active" interval.
  3. Iterate: Loop through the remaining intervals starting from index 1.
  4. Compare: For each currentInterval, compare its start time to the end time of the last interval in our result list (lastMerged).
    • Overlap: If currentInterval.start <= lastMerged.end, they overlap. We merge them by updating lastMerged.end to be the maximum of lastMerged.end and currentInterval.end. (We must take the max because currentInterval could be completely engulfed by lastMerged).
    • No Overlap: If currentInterval.start > lastMerged.end, there is a gap. The lastMerged interval is completely finalized. We add currentInterval to the result list, and it now becomes the new lastMerged for future comparisons.
  5. Convert: Convert the dynamic List back into a 2D integer array and return.

# The Intuition

Imagine painting lines on a ruler. If the lines are given to you in random order, it's very hard to know if a new line connects to an old one without checking every single line you've already painted. But, if you sort the instructions so that you always paint starting from the left side of the ruler moving right, you only ever need to look at the very last stroke your paintbrush made. If the new instruction says "start painting at 5cm", and your brush just lifted off the ruler at 7cm, you know they overlap, so you just keep dragging the brush to the right. If the new instruction says "start at 10cm", there is a gap, so you finalize the old line and start a brand new one.

# Complexity

LabelWorstAverage
Time ComplexityO(Nlog⁡N)O(N \log N)O(NlogN)O(Nlog⁡N)O(N \log N)O(NlogN)
Space ComplexityO(N)O(N)O(N)O(N)O(N)O(N)

# Time Complexity

Sorting the array of intervals takes O(Nlog⁡N)O(N \log N)O(NlogN) time. The subsequent linear sweep touches each interval exactly once, taking O(N)O(N)O(N) time. The sorting step dominates the asymptotic complexity.

# Space Complexity

The returned array/list requires O(N)O(N)O(N) space to store the merged intervals. Additionally, the sorting algorithm itself requires O(log⁡N)O(\log N)O(logN) (or O(N)O(N)O(N) depending on language implementation) auxiliary stack space. Overall space complexity is O(N)O(N)O(N).

# Code

class Solution {
    public int[][] merge(int[][] intervals) {
        if (intervals == null || intervals.length <= 1) {
            return intervals;
        }
 
        // Sort intervals by their start times
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
 
        List&lt;int[]&gt; merged = new ArrayList<>();
        
        // Initialize the list with the first interval
        merged.add(intervals[0]);
 
        for (int i = 1; i &lt; intervals.length; i++) {
            int[] currentInterval = intervals[i];
            // Get the last merged interval's reference
            int[] lastMerged = merged.get(merged.size() - 1);
 
            // If the current interval overlaps with the last merged one, extend the end
            if (currentInterval[0] <= lastMerged[1]) {
                lastMerged[1] = Math.max(lastMerged[1], currentInterval[1]);
            } else {
                // No overlap, add the current interval as a new independent interval
                merged.add(currentInterval);
            }
        }
 
        return merged.toArray(new int[merged.size()][]);
    }
}

# Caveats

  • Complete Subsumption: A common mistake is to write lastMerged[1] = current[1] when an overlap is found. This fails if lastMerged = [1, 10] and current = [2, 5]. The Math.max() is mathematically required because the new interval might end before the active interval ends.
  • Reference Mutation: In the refined code, lastMerged[1] = ... actually mutates the array sitting inside the List. This is highly efficient but requires an understanding that Java passes object references by value.

# Concepts to Think About

  • Sorting Constraints: Always clarify if the start time is guaranteed to be ≤\le≤ the end time. Usually it is, but if [10, 2] is a valid input, you must normalize the intervals before sorting.
  • Data Stream: If the intervals arrive continuously in a data stream and you must query the merged intervals at any time, sorting is impossible. You would need to use a TreeMap or a specialized Interval Tree to insert and merge in O(log⁡N)O(\log N)O(logN) time per element.
  • Connected Components: Conceptually, this problem is equivalent to finding the Connected Components in a 1D graph where edges exist between overlapping nodes.

# Logical Follow-up

Question: Given a set of non-overlapping intervals, insert a newInterval into the intervals (merge if necessary). (LeetCode 57: Insert Interval) Solution: Since the initial array is already sorted and non-overlapping, we do not need to sort (O(Nlog⁡N)O(N \log N)O(NlogN)), we can do it in O(N)O(N)O(N) time. We iterate through the array.

  1. If the current interval ends before newInterval starts, add the current to results.
  2. If the current interval starts after newInterval ends, add newInterval to results, and then append all remaining intervals.
  3. If they overlap, mutate newInterval to be [min(starts), max(ends)] and do not add it yet (wait until the overlap is finished).

Question: Given an array of meeting time intervals, return the minimum number of conference rooms required. (LeetCode 253: Meeting Rooms II) Solution: Merging intervals tells us if things overlap, but not the maximum depth of overlap. We must separate the start times and end times into two separate sorted arrays. Use a two-pointer approach: if starts[i] < ends[j], a meeting is starting before the oldest meeting ends, so we need a new room (rooms++, i++). If starts[i] &gt;= ends[j], a meeting ended, freeing a room (rooms--, j++). Keep track of the max_rooms. Time: O(Nlog⁡N)O(N \log N)O(NlogN). Space: O(N)O(N)O(N).

Previous54. Spiral MatrixNext61. Rotate List
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-up