Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/Given a list of intervals, merge the overlaps. How do you optimize it?

Given a list of intervals, merge the overlaps. How do you optimize it?

Python/Codingeasy2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

To merge overlapping intervals efficiently, first sort the intervals by their start times. Then, iterate through the sorted list, merging intervals that overlap with the last merged interval. This…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
Microsoft

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like Microsoft. While less common, it tests deeper understanding that distinguishes strong candidates.

How to Approach This

Start by clearly defining the core concept being asked about. Interviewers want to see that you understand the fundamentals before diving into implementation details. Structure your answer with a definition, then explain the practical application with a concise example. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
425 wordsIncludes code

To merge overlapping intervals efficiently, first sort the intervals by their start times. Then, iterate through the sorted list, merging intervals that overlap with the last merged interval. This approach yields a time complexity of O(N log N) due to the sorting step, and O(N) space complexity in the worst case for the result.

The core principle is that sorting by start time guarantees that any potential overlap for the current interval must occur with an interval that has already been processed or is the next in the sorted sequence. After initializing a result list with the first interval, we iterate through the remaining intervals:

  • If the current interval's start time is less than or equal to the end time of the last interval in our merged list, an overlap exists. We then update the end time of that last merged interval to be the maximum of its current end time and the current interval's end time.

  • Otherwise, there is no overlap, and the current interval is appended to our merged list as a new, distinct interval.
  • Example:
    Input: [[1,3], [2,6], [8,10], [15,18]]

  • Sort: [[1,3], [2,6], [8,10], [15,18]] (already sorted)

  • Initialize merged = [[1,3]]

  • Process [2,6]: 2 <= 3 (overlap). Update merged[-1] to [1, max(3,6)] = [1,6]. merged = [[1,6]]

  • Process [8,10]: 8 > 6 (no overlap). Append [8,10]. merged = [[1,6], [8,10]]

  • Process [15,18]: 15 > 10 (no overlap). Append [15,18]. merged = [[1,6], [8,10], [15,18]]

  • Output: [[1,6], [8,10], [15,18]]

    def merge_intervals(intervals):
        if not intervals:
            return []
        intervals.sort(key=lambda x: x[0]) # Sort by start time
        
        merged = [intervals[0]]
        for current_start, current_end in intervals[1:]:
            last_merged_end = merged[-1][1]
            
            if current_start <= last_merged_end: # Overlap
                merged[-1][1] = max(last_merged_end, current_end)
            else: # No overlap
                merged.append([current_start, current_end])
                
        return merged
    

    In a production data engineering context, this pattern is highly relevant for tasks like consolidating time windows (e.g., event logs, sensor data validity periods, or sessionization) or merging data ranges within a data warehouse. For extremely large datasets that don't fit in memory, the sorting step becomes the primary challenge. Distributed processing frameworks like Apache Spark would require a distributed sort (e.g., using sortBy or sortByKey, which involves shuffles across partitions) before a linear scan can be performed. If intervals are already naturally grouped by a key (e.g., customer ID or device ID), then merging can occur independently within each group after a groupBy operation, significantly reducing the global sorting overhead.

    In the interview, also mention handling edge cases like an empty input list or a list with a single interval.

    ⚡
    Pro Tip

    Pro-Move: In-place merge. Red Flag: O(n²) comparison.

    Want all answers as a PDF for offline study?
    Seven focused volumes with 750+ in-depth answers — Answer Vault →

    Related Python/Coding Questions

    easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

    Level up your prep

    Recommended
    Educative
    Educative Unlimited

    800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

    Start learning →

    Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

    According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

    ← Back to all questionsMore Python/Coding questions →
    Categories
    All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
    By Company
    AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
    Interview Guides
    All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
    Products
    AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
    Company
    About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
    © 2026 DataEngPrep.tech. All rights reserved.
    AboutBlogContactDisclaimer