BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features39 of 54 in topic

778. Merge overlapping time intervals

EasyData processing and features

GPU reservations, log windows and annotated text spans all reduce to the same task: merge ranges that overlap so you can measure total covered time.

Write merge_intervals(intervals) for a list of [start, end] pairs with start <= end, in any order. Merge any intervals that overlap or touch (end of one equals start of the next). Return the merged list sorted by start.

Functiondef merge_intervals(intervals)

Example 1

Input: merge_intervals([[5, 8], [1, 3], [2, 4], [8, 9]])

Output: [[1, 4], [5, 9]]

Example 2

Input: intervals = []

Output: []

Example 3

Input: intervals = [[1, 10], [2, 3], [4, 5]]

Output: [[1, 10]]

Constraints

  • At most 100,000 intervals.
  • Integers, start <= end.
Hint 1

Sort first.

Hint 2

Compare with the last merged interval only.

Hint 3

Extend with max, not with the new end.

Common mistakes
  • Overwriting the end instead of taking the max, which shrinks blocks.
  • Treating touching intervals as separate when the task says to merge them.
Understand the idea

Merging intervals is a sort then sweep. Once intervals are sorted by start, you only ever compare the next interval with the last merged one. If it starts before that one ends, they overlap and you extend; if not, there is a gap and you start a new block. [1, 3] and [2, 4] become [1, 4]; [5, 8] and [8, 9] touch and become [5, 9]. The same sweep computes total GPU hours booked, merges overlapping entity spans in NER labels, and finds free slots in a calendar.

Topics
Data processing and features
Similar questions
  • Standardise features without leaking test dataEasy
  • Scale features with the median and IQR so outliers do not dominateEasy
  • Encode hour of day and day of week as sine and cosine featuresEasy
  • Clip outliers using percentiles learned on the training set onlyEasy
All Data processing and features problems
Report
778 / 903
Python 3solution.pyPython idle
1
2
3
4
def merge_intervals(intervals):
# return merged intervals sorted by start
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 5 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS