Merge Intervals Pattern: The Complete Guide to Solving Interval Problems in Product Company Interviews
Master the Merge Intervals DSA pattern — covering 6 interval problem variants asked at Google, Amazon and Flipkart in India with Python code and complexity analysis.

Posted by
Shahar Banu

Reviewed by
Divyansh Dubey
Published
You've made it to the DSA round at Google India twice. Both times, you've left the interview room knowing exactly what you did wrong — not because you couldn't code, but because you didn't recognise the pattern fast enough under pressure. The merge intervals problem is one of those patterns. It looks like a scheduling question. It looks like an array question. It looks different every single time — until you see the framework underneath. Once you do, six different LeetCode problems suddenly feel like one problem wearing different clothes.
This guide breaks down the complete interval pattern for merge intervals interview India preparation: what it is, when to reach for it, how to implement it in Python and Java, and — most importantly — how to recognise its disguised variants the moment an interviewer at Amazon India or Flipkart starts reading the problem statement.
By the end of this guide, you'll know exactly how to identify, solve, and explain every major interval problem variant in a live interview setting.
The Interval Pattern Framework: When Do You Reach for This?
The interval pattern is a specific family of problems. Recognising the family is the first skill. An interval problem is any problem where the input is a list of ranges (pairs of start and end values) and the goal involves detecting, removing, counting, or merging relationships between those ranges.
The core question you should ask yourself when you read a problem: *"Is the input a list of pairs where order and overlap matter?"* If yes, you're likely in interval territory.
Quotable Definition: The Merge Intervals pattern is an algorithm technique that processes a sorted list of `[start, end]` pairs to identify and merge overlapping ranges — applicable any time a problem involves scheduling, resource allocation, or timeline analysis over discrete intervals.
These problems appear consistently across Google India, Amazon India, and Flipkart interviews. According to patterns tracked on LeetCode discuss threads and engineering blogs from Swiggy and Razorpay, interval-type questions appear in roughly 1 in 5 medium-difficulty DSA rounds at Indian product companies in 2024–2025.
The interval family has a consistent setup signal. You'll see: a list of `[start, end]` arrays, a question about overlap or gaps, and constraints around time, rooms, or scheduling. That triple signal is your trigger. Stop and sort the input by start time — that single step unlocks the entire pattern.
For context on how interval problems sit within the broader DSA landscape, see this breakdown of array interview questions for product companies India — intervals build directly on array fundamentals.
Key takeaway: If the input is a list of `[start, end]` pairs and the question involves overlap, merging, or counting — it's an interval problem. Sort by start time and apply the appropriate interval sub-pattern.
Merge Intervals — Step-by-Step with Code (Python + Java)
The canonical Merge Intervals problem (LeetCode 56) asks: given a list of intervals, merge all overlapping intervals and return the result. This is the foundation. Every other interval variant is a derivative of this logic.
Step-by-step approach:
1. Sort the input array by start value — `O(n log n)` 2. Initialise a result list and add the first interval 3. Iterate through remaining intervals 4. Compare the current interval's start with the last merged interval's end 5. Merge if overlapping (update end to `max(last.end, current.end)`) 6. Append if non-overlapping (add current interval directly)
Two intervals `[a, b]` and `[c, d]` overlap if and only if `c <= b`. That single condition drives the entire algorithm.
# Python — Merge Intervals
def merge(intervals):
if not intervals:
return []
# Step 1: Sort by start time
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
# Step 2: Check overlap
if current[0] <= last[1]:
# Merge: extend end
last[1] = max(last[1], current[1])
else:
# No overlap: add new interval
merged.append(current)
return merged
# Example
print(merge([[1,3],[2,6],[8,10],[15,18]]))
# Output: [[1,6],[8,10],[15,18]]
Try It Live
// Java — Merge Intervals
import java.util.*;
public class MergeIntervals {
public int[][] merge(int[][] intervals) {
// Step 1: Sort by start time
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
List<int[]> merged = new ArrayList<>();
merged.add(intervals[0]);
for (int i = 1; i < intervals.length; i++) {
int[] current = intervals[i];
int[] last = merged.get(merged.size() - 1);
// Step 2: Overlap check
if (current[0] <= last[1]) {
last[1] = Math.max(last[1], current[1]);
} else {
merged.add(current);
}
}
return merged.toArray(new int[0][]);
}
}
Try It Live
One thing a textbook won't tell you: Amazon interviewers in India specifically check whether you handle the `max(last.end, current.end)` case correctly — not just `current.end`. A fully contained interval like `[2, 3]` inside `[1, 6]` must not shrink the merged result. This is a known trap in Amazon India's SDE-2 rounds.
Key takeaway: Sort by start, compare current start to last merged end, and always use `max` when updating the merged end. These three rules handle every core merge scenario.
The 6 Interval Problems That Actually Appear in MAANG Interviews
This is where pattern recognition pays off. Each of these six problems is a variation of the merge intervals core. Once you see the transformation, you stop treating them as separate problems.
1. Meeting Rooms I (LeetCode 252)
Problem: Given a list of meeting intervals, can one person attend all meetings?
This is the simplest variant. Sort by start time. If any `intervals[i].start < intervals[i-1].end`, return `false`. No merging needed — just overlap detection. Time: `O(n log n)`.
2. Meeting Rooms II (LeetCode 253)
Problem: What is the minimum number of meeting rooms required?
This is the most frequently asked interval problem in meeting rooms LeetCode India searches — and one of the most commonly asked at Flipkart, Swiggy, and Google India. Use a min-heap to track the earliest ending meeting. For each new meeting, if its start ≥ heap top, reuse that room (pop and push new end). Otherwise, allocate a new room (push new end). Result: heap size at the end.
import heapq
def minMeetingRooms(intervals):
if not intervals:
return 0
intervals.sort(key=lambda x: x[0])
heap = [] # min-heap of end times
for start, end in intervals:
if heap and heap[0] <= start:
heapq.heapreplace(heap, end)
else:
heapq.heappush(heap, end)
return len(heap)
Try It Live
3. Insert Interval (LeetCode 57)
Problem: Insert a new interval into a sorted, non-overlapping list and merge if necessary.
For the insert interval interview variant, split into three phases: add all intervals that end before the new interval starts, merge all overlapping intervals with the new one, then add the rest. Time: `O(n)` — no sort needed since input is already sorted.
For deeper context on how this problem maps to broader array manipulation techniques, the top 100 LeetCode problems for MAANG interviews tracks its frequency and difficulty tier across recent interview cycles.
4. Non-Overlapping Intervals (LeetCode 435)
Problem: Find the minimum number of intervals to remove to make the rest non-overlapping.
This is the classic interval scheduling algorithm interview problem — essentially a greedy approach. Sort by end time. Greedily keep the interval with the earliest end. When overlap is found, discard the interval with the later end. Count removals. Time: `O(n log n)`.
5. Minimum Meeting Rooms (Heap-Extended Variant)
This is an extended form of Meeting Rooms II with additional constraints — sometimes asking for which meetings to reschedule or tracking room IDs. The heap approach from Meeting Rooms II extends directly. In Bengaluru-based Google India interviews, this variant appears with an added constraint around a priority queue of room labels.
6. Employee Free Time (LeetCode 759)
Problem: Given a list of schedules for each employee (each a list of intervals), find the free time common to all employees.
Flatten all intervals into a single list, sort by start, then apply the merge intervals logic. Gaps between merged intervals are the free times. This requires an extra mental step — the flattening — but the core algorithm is identical. Time: `O(n log n)`.
Key takeaway: All six variants share the same skeleton — sort by start or end time, then apply a greedy scan with a heap or pointer. Memorise the skeleton; adapt the condition.
Only 6 Seats Left — Cohort 3
How to Identify an Interval Problem in a Live Interview
This is the section that matters most when you're 10 minutes into a 45-minute round at Amazon India and an interviewer is watching you think on a shared screen. You need a mental trigger — not a memorised solution.
Three-signal detection framework:
1. Input shape: The input is a list of pairs — `[start, end]`, `[from, to]`, `[arrival, departure]`, `[open, close]`. Any pair of numbers representing a range is the first signal.
2. Question type: The question asks for overlap count, merged list, minimum containers, or gap detection. If it involves *relationships between ranges* rather than values, it's interval territory.
3. Constraint vocabulary: Words like "meetings", "rooms", "schedules", "tasks", "timeslots", "free time", "conflicts", or "booking" are domain signals for interval problems.
When you spot all three signals, say this out loud to the interviewer: *"This looks like an interval problem. I'll sort by start time first and then check for overlaps using a greedy scan."* That statement alone signals pattern fluency — which is exactly what MAANG interviewers at the SDE-2 level are screening for.
A common mistake in live interviews: jumping to code without establishing whether the input is already sorted. Always ask. If sorted, the Insert Interval variant applies (`O(n)`). If unsorted, sorting costs `O(n log n)` and the classic merge applies.
Direct Answer Block: How do you identify an interval problem in a live interview? Look for three signals: a list of `[start, end]` pairs as input, a question about overlap or merging, and domain keywords like "meetings", "rooms", or "schedules". When all three appear, sort by start time — that single step is the foundation of every interval solution.
The ability to recognise patterns under pressure — not just implement them at your desk — is the gap between engineers who get to the HR round and engineers who get the offer. For a structured approach to building this recognition speed, this DSA study plan for working engineers maps interval problems into a daily practice schedule that fits around a full-time job.
Key takeaway: Pattern recognition in a live interview requires a verbal framework, not just a mental one. Naming the pattern out loud — "this is an interval problem" — before writing code demonstrates structured thinking, which MAANG interviewers score explicitly.
Complexity Analysis for All Interval Variants
Understanding time and space complexity for every variant is non-negotiable at the SDE-2 and above level. Interviewers at Google India and Amazon India will ask you to justify your complexity claims — not just state them.
| Problem | Time Complexity | Space Complexity | Key Reason |
|---|---|---|---|
| Merge Intervals | O(n log n) | O(n) | Sort dominates; output list O(n) |
| Meeting Rooms I | O(n log n) | O(1) | Sort + single pass; no extra space |
| Meeting Rooms II | O(n log n) | O(n) | Heap stores up to n end times |
| Insert Interval | O(n) | O(n) | Input pre-sorted; single pass |
| Non-Overlapping Intervals | O(n log n) | O(1) | Greedy sort by end; counter only |
| Employee Free Time | O(n log n) | O(n) | Flatten all intervals then sort |
Direct Answer Block: What is the time complexity of Merge Intervals? The Merge Intervals algorithm runs in `O(n log n)` time because the dominant operation is sorting the input by start value. The subsequent linear scan to merge overlapping intervals is `O(n)`, making the total `O(n log n)`. Space complexity is `O(n)` for the output list.
One nuance worth flagging: Insert Interval is `O(n)` — but only because the input is already sorted. If an interviewer gives you an unsorted input and calls it "Insert Interval", you must sort first, which changes the complexity to `O(n log n)`. This distinction signals real understanding versus pattern-matching on problem names.
For problems like Employee Free Time involving nested lists (each employee has a list of intervals), the `n` in `O(n log n)` refers to the *total* number of intervals across all employees — not the number of employees. Stating this explicitly in an interview is an insider signal that you've worked with the problem at depth, not just read a solution.
If you want to see how complexity analysis applies across related patterns — particularly for problems involving stacks and queues — this guide on the Monotonic Stack pattern covers the adjacent technique family.
Key takeaway: The sort step dominates all interval variants at `O(n log n)` — except Insert Interval, which is `O(n)` on pre-sorted input. Know which is which, and state the reason, not just the notation.
How DSA & System Design with AI Program Can Help You
You're already building distributed systems at your startup. You understand scale. You've seen what real product engineering looks like. The gap isn't experience — it's the ability to demonstrate that experience under 45 minutes of structured interview pressure. That's a trainable skill, and it's exactly what the FutureJobs DSA & System Design with AI Program is built for.
The program is designed specifically for engineers at your level — not bootcamp beginners, not fresh graduates. It assumes you know what a linked list is. It starts where you actually are: advanced DSA patterns, system design at scale, and the specific communication skills that turn a correct solution into an accepted offer.
What the program covers: - 240+ hours of live classes structured around patterns — not problem lists - DSA + HLD/LLD + Prompt Engineering in one curriculum - 1:1 FAANG mentor throughout the program — engineers who've cleared the exact rounds you're preparing for at Google India, Amazon India, and Meta India - Evening and weekend schedule — zero conflict with your current role - Dual Assessment System that simulates real MAANG interview conditions before you sit in them
The financial structure removes the biggest barrier engineers at your stage face. The Pay-After-Placement model means ₹1.75 lakh upfront — and the remaining payment comes only after you land the role. At ₹25 LPA, that's trivial. EMI is ₹4,999/month during the program. Compare that to Scaler's ₹5 lakh upfront and the math is straightforward.
FutureJobs is structurally different from Scaler or AlmaBetter in one key way: the pay-after-placement model means the program's incentive is aligned with your outcome, not your enrollment. Over 700 engineers enrolled this month — engineers who, like you, already have product experience and need interview translation, not Arrays 101.
Does DSA Still Matter in 2026 When GitHub Copilot Exists?
In 2026, some engineers ask whether grinding interval problems on LeetCode matters when GitHub Copilot can generate a merge intervals solution in 10 seconds. The answer is yes — and the bar is actually higher now.
MAANG interviewers at Google India and Amazon India have adapted. They now ask follow-ups specifically designed to probe understanding, not just output. "Why did you sort by start and not end?" "What breaks if the input contains negative integers?" "How would you modify this for a streaming input where intervals arrive in real time?" GitHub Copilot cannot answer those questions for you in an interview room. Pattern fluency — the ability to recognise, adapt, and explain — is the actual skill being screened.
Post-2024 hiring cycles at Indian product companies have, if anything, raised the DSA bar. With fewer open roles and more candidates preparing with AI assistance, the differentiation happens at explanation depth. Engineers who understand *why* the algorithm works beat engineers who only know *that* it works.
Understanding this connects directly to the broader question of why engineers fail MAANG DSA rounds — pattern recognition and explanation fluency are the two most cited gaps in post-interview feedback.
Only 11 Seats Left — Cohort 3
Frequently Asked Questions
How long does it take to get comfortable with interval problems for MAANG interviews?
With focused daily practice of 1–1.5 hours, most engineers reach interview-ready proficiency on the complete interval pattern family in 2–3 weeks. That includes all six variants covered in this guide. The key is pattern drilling — not solving 50 random problems, but solving the 6 core variants 3–4 times each until the decision logic is automatic. Engineers in structured prep programs typically solidify this in 10–15 sessions.
I've already done Merge Intervals on LeetCode. Do I actually need to revisit it?
Yes — and specifically for the explanation layer. Solving it at your desk is different from explaining your approach under pressure in 45 minutes. If you can't immediately articulate why you use `max(last.end, current.end)` instead of `current.end`, why you sort by start and not end, and what breaks with an unsorted input, you haven't prepared it for a live interview. MAANG interviewers at the SDE-2 level probe this depth explicitly.
Can I prepare for MAANG DSA rounds while working full-time in India?
Yes — 15–20 hours per week across evenings and weekends is sufficient for a structured 5-month preparation. The FutureJobs DSA & System Design with AI Program is built specifically around working professional schedules, with live classes in the evenings and session recordings available for the sessions you miss. Engineers at Indian product startups consistently complete this preparation without career interruption.
What is the difference between Meeting Rooms I and Meeting Rooms II in interviews?
Meeting Rooms I asks whether one person can attend all meetings — a simple overlap detection problem solved with a sort and a single-pass comparison in `O(n log n)` time and `O(1)` space. Meeting Rooms II asks for the minimum number of rooms required — a resource allocation problem solved with a min-heap tracking end times in `O(n log n)` time and `O(n)` space. Meeting Rooms II appears far more frequently in actual MAANG interviews in India and is the harder, more instructive problem to master.
Is the FutureJobs DSA program worth it if I'm already at a product startup?
If you've failed the DSA round at MAANG after reaching the interview stage, the gap is almost never knowledge — it's structured pattern recognition and interview-condition practice. The program's value for engineers already in product roles is specifically the 1:1 FAANG mentor feedback and mock interview simulation under timed conditions. The pay-after-placement model removes the financial risk: ₹4,999/month during the program, remainder only after placement.
Final Thoughts
The merge intervals pattern is one of the cleanest examples of how DSA interviews actually work at MAANG level in India. The problem isn't hard. The algorithm isn't obscure. What's hard is recognising it in three seconds under camera pressure, naming it confidently to the interviewer, and then executing the sort + scan + merge logic without second-guessing yourself.
You now have the complete framework: when to trigger the pattern, how to implement the core algorithm in Python and Java, how all six variants transform from the same skeleton, and how to think about complexity in a way that holds up under follow-up questions.
The next step is repetition under realistic conditions — not at your desk with no timer, but with a mock interviewer who's done the Amazon SDE-2 loop and can tell you exactly where your explanation lost them. That's the preparation gap that separates the engineers who make it to the offer from the ones who make it to the HR screen.
If interval problems are part of your pattern library, explore how they connect to the full picture of dynamic programming pattern matching for product interviews — the two pattern families often appear together in multi-part interview questions.
