Limited Time Offer:Up to 0% off Hello Interview Premium
Up to 0% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Intervals

Insert Interval

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Given a list of intervals intervals and an interval newInterval, write a function to insert newInterval into a list of existing, non-overlapping, and sorted intervals based on their starting points. The function should ensure that after the new interval is added, the list remains sorted without any overlapping intervals, merging them if needed.

Two intervals are considered overlapping if they share any common time, including if one ends exactly when another begins (e.g., [1,4] and [4,7] overlap and should be merged into [1,7]).

Input:

intervals = [[1,3],[6,9]]
newInterval = [2,5]

Output:

[[1,5],[6,9]]

Explanation: The new interval [2,5] overlaps with [1,3], so they are merged into [1,5].

Input:

intervals = [[1,2],[3,5],[6,7],[8,10]]
newInterval = [5,6]

Output:

[[1,2],[3,7],[8,10]]

Explanation: The new interval [5,6] touches [3,5] and [6,7], so all three are merged into [3,7].

Explanation

We first want to create a new list merged to store the merged intervals we will return at the end.
This solution operates in 3 phases:
  1. Add all the intervals ending before newInterval starts to merged.
  2. Merge all overlapping intervals with newInterval and add that merged interval to merged.
  3. Add all the intervals starting after newInterval to merged.
Phase 1
In this phase, we add all the intervals that end before newInterval starts to merged. This involves iterating through the intervals list until the current interval no longer ends before newInterval starts (i.e. intervals[i][1] >= newInterval[0]).
Visualization
Python
Language
def insertIntervals(intervals, newInterval):
merged = []
i = 0
n = len(intervals)
while i < n and intervals[i][1] < newInterval[0]:
merged.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(intervals[i][0], newInterval[0])
newInterval[1] = max(intervals[i][1], newInterval[1])
i += 1
merged.append(newInterval)
for j in range(i, n):
merged.append(intervals[j])
return merged
][31][64][76][108][1511newInterval][85merged

initialize variables

0 / 1

Phase 2
In this phase, we merge all the intervals that overlap with newInterval together into a single interval by updating newInterval to be the minimum start and maximum end of all the overlapping intervals. This includes intervals that merely "touch" newInterval (e.g. [1,4] and [4,7] should merge into [1,7]). We iterate through the intervals list until the current interval starts after newInterval ends (i.e. intervals[i][0] > newInterval[1]). When that condition is met, we add newInterval to merged and move onto phase 3.
Visualization
Python
Language
def insertIntervals(intervals, newInterval):
merged = []
i = 0
n = len(intervals)
while i < n and intervals[i][1] < newInterval[0]:
merged.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(intervals[i][0], newInterval[0])
newInterval[1] = max(intervals[i][1], newInterval[1])
i += 1
merged.append(newInterval)
for j in range(i, n):
merged.append(intervals[j])
return merged
][31][64][76][108][1511newInterval][85merged][31

add intervals before newInterval

0 / 4

Phase 3
Phase 3 involves adding all the intervals starting after newInterval to merged. This involves iterating through the intervals list until the end of the list, and adding each interval to merged.
After completing these 3 phases, we return merged as the final result.
Visualization
Python
Language
def insertIntervals(intervals, newInterval):
merged = []
i = 0
n = len(intervals)
while i < n and intervals[i][1] < newInterval[0]:
merged.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(intervals[i][0], newInterval[0])
newInterval[1] = max(intervals[i][1], newInterval[1])
i += 1
merged.append(newInterval)
for j in range(i, n):
merged.append(intervals[j])
return merged
][31][64][76][108][1511newInterval][104merged][31][104

j = 4

0 / 2

Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(n) where n is the number of intervals. We iterate through all intervals once to merge them.

Space Complexity: O(n) where n is the number of intervals. We need space for the merged output array.

Solution

Visualization
Python
Language
Try these examples:
def insertIntervals(intervals, newInterval):
merged = []
i = 0
n = len(intervals)
while i < n and intervals[i][1] < newInterval[0]:
merged.append(intervals[i])
i += 1
while i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(intervals[i][0], newInterval[0])
newInterval[1] = max(intervals[i][1], newInterval[1])
i += 1
merged.append(newInterval)
for j in range(i, n):
merged.append(intervals[j])
return merged
][31][64][76][108][1511newInterval][85

insert interval

0 / 9

Mark as read

Next: Non-Overlapping Intervals

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Solution

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsAnthropic SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress