Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Intervals & Greedy
MediumLC 56

Merge Intervals (LeetCode 56)

Target Frequency:GoogleAmazonMicrosoft

You're given an array of intervals, each entry [start_i, end_i]. Fuse together every pair of intervals that overlap, then return the resulting array of non-overlapping intervals that together cover the exact same span as the original input.

Worked Examples

Example 1
Input:intervals = [[1,3],[2,6],[8,10],[15,18]]
Output:[[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2
Input:intervals = [[1,4],[4,5]]
Output:[[1,5]]
Explanation: [1,4] and [4,5] share the point 4, which counts as overlapping, so they merge into [1,5].
Example 3
Input:intervals = [[4,7],[1,4]]
Output:[[1,7]]
Explanation: [1,4] and [4,7] share the point 4, so they merge into [1,7]. The input does not have to be sorted.

⚖️Formal Constraints & Bounds

  • 1 <= intervals.length <= 104

  • intervals[i].length == 2

  • 0 <= start_i <= end_i <= 104

Deep-Dive & Conceptual Insights

Core Insight

Sorting by start coordinate ensures all potentially overlapping intervals are adjacent in the list.

Real-World Scenario & Production Applications

Calendar availability slot consolidation (Google Calendar free/busy scheduling) and memory buffer defragmentation.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Start-Time Sorting Invariant

Sort intervals strictly by start time (intervals.sort(key=lambda x: x[0])). Guarantees that any interval overlapping with the current cluster starts before or at the same time as subsequent intervals.

Mathematical Recurrence / Code Invariant
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]

Step-by-Step Execution Trace Table

StepAccumulated IntervalIncoming IntervalOverlap Check (curr.start <= prev.end)Action TakenResulting merged List
0[1, 3]——Seed merged with first interval[[1, 3]]
1[1, 3][2, 6]2 <= 3 (True)Overlap! Extend prev[1] = max(3, 6) = 6[[1, 6]]
2[1, 6][8, 10]8 <= 6 (False)Disjoint. Append [8, 10][[1, 6], [8, 10]]
3[8, 10][15, 18]15 <= 10 (False)Disjoint. Append [15, 18][[1, 6], [8, 10], [15, 18]]
Code Shape
Archetype Code Shape
Python
1intervals.sort(key=lambda iv: iv[0])
2merged = []
3accumulated = intervals[0]
4for incoming in intervals[1:]:
5 if incoming[0] <= accumulated[1]:
6 accumulated[1] = max(accumulated[1], incoming[1])
7 else:
8 merged.append(accumulated)
9 accumulated = incoming
10merged.append(accumulated)
11return merged

Conceptual Narrative

Checking every pair of intervals for overlap is O(N²). Sorting by start time turns the problem into a single linear scan, because overlapping intervals become guaranteed adjacent neighbors.

🧭 Conceptual Foundation & Pattern Intuition

An interval [s1,e1][s_1, e_1][s1​,e1​] overlaps with [s2,e2][s_2, e_2][s2​,e2​] if and only if max⁡(s1,s2)≤min⁡(e1,e2)\max(s_1, s_2) \le \min(e_1, e_2)max(s1​,s2​)≤min(e1​,e2​). In an unsorted list of intervals, two overlapping intervals can be located at opposite ends of the input array, requiring O(N2)O(N^2)O(N2) pairwise comparisons to discover. Sorting intervals by their start time establishes a fundamental invariant: If i<j, then intervals[i][0]≤intervals[j][0]\text{If } i < j, \text{ then } \text{intervals}[i][0] \le \text{intervals}[j][0]If i<j, then intervals[i][0]≤intervals[j][0] Because start times are non-decreasing, the next interval incoming can overlap with the currently accumulating interval accumulated if and only if: incoming[0]≤accumulated[1]\text{incoming}[0] \le \text{accumulated}[1]incoming[0]≤accumulated[1] If this condition holds, the intervals overlap, and we merge them by extending the end time: accumulated[1] = max(accumulated[1], incoming[1]). If the condition fails, then because all subsequent intervals will have even larger start times, accumulated is guaranteed to be disjoint from all future intervals—allowing us to finalize it (merged.append(accumulated)) and start a new interval from incoming. After the loop, the last open accumulated is appended too.

📅 The Analogy: Merging Overlapping Calendar Blocks

Imagine a messy calendar with dozens of scheduled appointments scattered across a desk. To find your free time, you don't cross-reference appointment cards at random. You line up all the cards chronologically by their start time. You pick up the earliest card (say, 9:00 AM - 10:30 AM). You look at the next card: if it starts at 10:00 AM, it overlaps, so you stretch your meeting block to end at whichever card ends later (say, 11:00 AM). If the next card starts at 1:00 PM, you know with 100% certainty that your morning block is finished—no remaining card in the pile can ever start earlier than 1:00 PM.

🔑 Why It Works

Sorting dominates the time complexity at O(Nlog⁡N)O(N \log N)O(NlogN); the subsequent consolidation pass runs in strictly linear O(N)O(N)O(N) time with O(N)O(N)O(N) output storage.

  • Sorting by start only: on [[1,4],[1,5]] a start-only sort keeps [1,4] first, so both are counted; the key (x[0], -x[1]) puts [1,5] first and [1,4] is seen as covered.

  • Using >= instead of >: [2,4] after [1,4] has end == prev_end and is covered; end >= prev_end would count it.

  • Returning the removals: the answer is how many intervals remain, count, not how many were covered.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Merge all overlapping intervals" into non-overlapping ones that cover the same ranges: ranges on one line that must be combined.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Decision rule: incoming[0] <= accumulated[1] means the two overlap (touching counts), so stretch accumulated; otherwise accumulated is finished and goes into merged.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Setting accumulated[1] = incoming[1] instead of max(accumulated[1], incoming[1]): a nested interval shrinks the end, so [[1,5],[2,3],[4,6]] returns [[1,3],[4,6]] instead of [[1,6]].

  • Skipping intervals.sort(key=lambda iv: iv[0]): on [[2,6],[1,3]], [1,3] is absorbed into [2,6] and the answer is [[2,6]] instead of [[1,6]].

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use Merge Intervals. I sort by start, then keep one open interval, accumulated. For each incoming interval, if it starts at or before accumulated's end, they overlap and I stretch the end; otherwise accumulated is finished, so I save it to merged and start again from the incoming one. That is correct because after sorting no later interval starts earlier, so once one starts past the end, nothing after it can reach back into accumulated. The trap is the end update: I take the max of both ends, because an interval nested inside another would otherwise shrink it. After the loop I save the last accumulated. Sorting makes it O(N log N) time, with O(N) space for the sort and the output."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N log N)

Look at the execution steps: Sorting N intervals by start time takes O(N log N). Single linear pass merges overlapping intervals in O(N). Total O(N log N) time.

SPACE COMPLEXITY

O(N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Sorting takes O(N) space; result list stores at most N merged intervals.

Formal Recurrence Relation

T(N) = O(N log N) + O(N) = O(N log N)

Derivation Progression

Start Time Sorting

O(N log N) sort

Orders intervals chronologically by start time.

Linear Coalescing

if incoming[0] <= accumulated[1]: accumulated[1] = max(accumulated[1], incoming[1])

Merges overlapping intervals in O(1) per interval.

Dominant Sort Cost

O(N log N)

Linear pass is strictly dominated by sorting.

Variable Definitions

NNN

Total number of intervals in the input list

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(N) Sort buffer

🟢 Output Space

O(N) Merged intervals list

Boundary Best / Worst Cases

Best Case

O(Nlog⁡N)O(N \log N)O(NlogN)

Average Case

O(Nlog⁡N)O(N \log N)O(NlogN)

Worst Case

O(Nlog⁡N)O(N \log N)O(NlogN)

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Key phrasing: "merge all overlapping intervals", "return non-overlapping intervals". In production the same merge coalesces calendar busy blocks, reserved time slots or overlapping address ranges.

CONSTRAINTS & BOUNDS

1≤intervals.length≤1041 \le intervals.length \le 10^41≤intervals.length≤104. Budget: O(Nlog⁡N)O(N \log N)O(NlogN) for the sort, then one O(N)O(N)O(N) pass.

FAANG PRODUCTION TRAPS & EDGE CASES

Unsorted, unbounded input (ranges arriving one at a time) cannot be sorted up front. Keep the disjoint intervals in a sorted map keyed by start and, on each insert, merge the new range with the neighbours it overlaps: O(log⁡N)O(\log N)O(logN) to find them plus the work of absorbing them.

Core Algorithmic State Invariants

  1. The Output Is Sorted Too

merged receives intervals in order of their starts, and each saved interval ends before the next one starts, so the result is sorted and disjoint with no second sort. A later step can binary-search it or walk it with two pointers.

  1. Counting Instead of Building

When only the number of merged intervals is needed, merged can be replaced by a counter that goes up where the loop would append: the same pass, with O(1) extra space besides the sort.

Theory Context•Intervals & Greedy
MediumLC 56

Merge Intervals (LeetCode 56)

Target Frequency:GoogleAmazonMicrosoft

You're given an array of intervals, each entry [start_i, end_i]. Fuse together every pair of intervals that overlap, then return the resulting array of non-overlapping intervals that together cover the exact same span as the original input.

Worked Examples

Example 1
Input:intervals = [[1,3],[2,6],[8,10],[15,18]]
Output:[[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2
Input:intervals = [[1,4],[4,5]]
Output:[[1,5]]
Explanation: [1,4] and [4,5] share the point 4, which counts as overlapping, so they merge into [1,5].
Example 3
Input:intervals = [[4,7],[1,4]]
Output:[[1,7]]
Explanation: [1,4] and [4,7] share the point 4, so they merge into [1,7]. The input does not have to be sorted.

⚖️Formal Constraints & Bounds

  • 1 <= intervals.length <= 104

  • intervals[i].length == 2

  • 0 <= start_i <= end_i <= 104

Deep-Dive & Conceptual Insights

Core Insight

Sorting by start coordinate ensures all potentially overlapping intervals are adjacent in the list.

Real-World Scenario & Production Applications

Calendar availability slot consolidation (Google Calendar free/busy scheduling) and memory buffer defragmentation.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Start-Time Sorting Invariant

Sort intervals strictly by start time (intervals.sort(key=lambda x: x[0])). Guarantees that any interval overlapping with the current cluster starts before or at the same time as subsequent intervals.

Mathematical Recurrence / Code Invariant
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]

Step-by-Step Execution Trace Table

StepAccumulated IntervalIncoming IntervalOverlap Check (curr.start <= prev.end)Action TakenResulting merged List
0[1, 3]——Seed merged with first interval[[1, 3]]
1[1, 3][2, 6]2 <= 3 (True)Overlap! Extend prev[1] = max(3, 6) = 6[[1, 6]]
2[1, 6][8, 10]8 <= 6 (False)Disjoint. Append [8, 10][[1, 6], [8, 10]]
3[8, 10][15, 18]15 <= 10 (False)Disjoint. Append [15, 18][[1, 6], [8, 10], [15, 18]]
Code Shape
Archetype Code Shape
Python
1intervals.sort(key=lambda iv: iv[0])
2merged = []
3accumulated = intervals[0]
4for incoming in intervals[1:]:
5 if incoming[0] <= accumulated[1]:
6 accumulated[1] = max(accumulated[1], incoming[1])
7 else:
8 merged.append(accumulated)
9 accumulated = incoming
10merged.append(accumulated)
11return merged

Conceptual Narrative

Checking every pair of intervals for overlap is O(N²). Sorting by start time turns the problem into a single linear scan, because overlapping intervals become guaranteed adjacent neighbors.

🧭 Conceptual Foundation & Pattern Intuition

An interval [s1,e1][s_1, e_1][s1​,e1​] overlaps with [s2,e2][s_2, e_2][s2​,e2​] if and only if max⁡(s1,s2)≤min⁡(e1,e2)\max(s_1, s_2) \le \min(e_1, e_2)max(s1​,s2​)≤min(e1​,e2​). In an unsorted list of intervals, two overlapping intervals can be located at opposite ends of the input array, requiring O(N2)O(N^2)O(N2) pairwise comparisons to discover. Sorting intervals by their start time establishes a fundamental invariant: If i<j, then intervals[i][0]≤intervals[j][0]\text{If } i < j, \text{ then } \text{intervals}[i][0] \le \text{intervals}[j][0]If i<j, then intervals[i][0]≤intervals[j][0] Because start times are non-decreasing, the next interval incoming can overlap with the currently accumulating interval accumulated if and only if: incoming[0]≤accumulated[1]\text{incoming}[0] \le \text{accumulated}[1]incoming[0]≤accumulated[1] If this condition holds, the intervals overlap, and we merge them by extending the end time: accumulated[1] = max(accumulated[1], incoming[1]). If the condition fails, then because all subsequent intervals will have even larger start times, accumulated is guaranteed to be disjoint from all future intervals—allowing us to finalize it (merged.append(accumulated)) and start a new interval from incoming. After the loop, the last open accumulated is appended too.

📅 The Analogy: Merging Overlapping Calendar Blocks

Imagine a messy calendar with dozens of scheduled appointments scattered across a desk. To find your free time, you don't cross-reference appointment cards at random. You line up all the cards chronologically by their start time. You pick up the earliest card (say, 9:00 AM - 10:30 AM). You look at the next card: if it starts at 10:00 AM, it overlaps, so you stretch your meeting block to end at whichever card ends later (say, 11:00 AM). If the next card starts at 1:00 PM, you know with 100% certainty that your morning block is finished—no remaining card in the pile can ever start earlier than 1:00 PM.

🔑 Why It Works

Sorting dominates the time complexity at O(Nlog⁡N)O(N \log N)O(NlogN); the subsequent consolidation pass runs in strictly linear O(N)O(N)O(N) time with O(N)O(N)O(N) output storage.

  • Sorting by start only: on [[1,4],[1,5]] a start-only sort keeps [1,4] first, so both are counted; the key (x[0], -x[1]) puts [1,5] first and [1,4] is seen as covered.

  • Using >= instead of >: [2,4] after [1,4] has end == prev_end and is covered; end >= prev_end would count it.

  • Returning the removals: the answer is how many intervals remain, count, not how many were covered.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Merge all overlapping intervals" into non-overlapping ones that cover the same ranges: ranges on one line that must be combined.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Decision rule: incoming[0] <= accumulated[1] means the two overlap (touching counts), so stretch accumulated; otherwise accumulated is finished and goes into merged.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Setting accumulated[1] = incoming[1] instead of max(accumulated[1], incoming[1]): a nested interval shrinks the end, so [[1,5],[2,3],[4,6]] returns [[1,3],[4,6]] instead of [[1,6]].

  • Skipping intervals.sort(key=lambda iv: iv[0]): on [[2,6],[1,3]], [1,3] is absorbed into [2,6] and the answer is [[2,6]] instead of [[1,6]].

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use Merge Intervals. I sort by start, then keep one open interval, accumulated. For each incoming interval, if it starts at or before accumulated's end, they overlap and I stretch the end; otherwise accumulated is finished, so I save it to merged and start again from the incoming one. That is correct because after sorting no later interval starts earlier, so once one starts past the end, nothing after it can reach back into accumulated. The trap is the end update: I take the max of both ends, because an interval nested inside another would otherwise shrink it. After the loop I save the last accumulated. Sorting makes it O(N log N) time, with O(N) space for the sort and the output."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N log N)

Look at the execution steps: Sorting N intervals by start time takes O(N log N). Single linear pass merges overlapping intervals in O(N). Total O(N log N) time.

SPACE COMPLEXITY

O(N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Sorting takes O(N) space; result list stores at most N merged intervals.

Formal Recurrence Relation

T(N) = O(N log N) + O(N) = O(N log N)

Derivation Progression

Start Time Sorting

O(N log N) sort

Orders intervals chronologically by start time.

Linear Coalescing

if incoming[0] <= accumulated[1]: accumulated[1] = max(accumulated[1], incoming[1])

Merges overlapping intervals in O(1) per interval.

Dominant Sort Cost

O(N log N)

Linear pass is strictly dominated by sorting.

Variable Definitions

NNN

Total number of intervals in the input list

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(N) Sort buffer

🟢 Output Space

O(N) Merged intervals list

Boundary Best / Worst Cases

Best Case

O(Nlog⁡N)O(N \log N)O(NlogN)

Average Case

O(Nlog⁡N)O(N \log N)O(NlogN)

Worst Case

O(Nlog⁡N)O(N \log N)O(NlogN)

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Key phrasing: "merge all overlapping intervals", "return non-overlapping intervals". In production the same merge coalesces calendar busy blocks, reserved time slots or overlapping address ranges.

CONSTRAINTS & BOUNDS

1≤intervals.length≤1041 \le intervals.length \le 10^41≤intervals.length≤104. Budget: O(Nlog⁡N)O(N \log N)O(NlogN) for the sort, then one O(N)O(N)O(N) pass.

FAANG PRODUCTION TRAPS & EDGE CASES

Unsorted, unbounded input (ranges arriving one at a time) cannot be sorted up front. Keep the disjoint intervals in a sorted map keyed by start and, on each insert, merge the new range with the neighbours it overlaps: O(log⁡N)O(\log N)O(logN) to find them plus the work of absorbing them.

Core Algorithmic State Invariants

  1. The Output Is Sorted Too

merged receives intervals in order of their starts, and each saved interval ends before the next one starts, so the result is sorted and disjoint with no second sort. A later step can binary-search it or walk it with two pointers.

  1. Counting Instead of Building

When only the number of merged intervals is needed, merged can be replaced by a counter that goes up where the loop would append: the same pass, with O(1) extra space besides the sort.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•