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 57

Insert Interval (LeetCode 57)

Target Frequency:MetaAmazonGoogleApple

You're handed an already-sorted, already-disjoint list of intervals intervals (each entry [start_i, end_i], ordered ascending by start_i), plus one more interval newInterval = [start, end] to drop into that list. Two intervals overlap the instant they share even a single point in common. Splice newInterval in, merging it with anything it touches, so the returned list is still start-sorted and still has no two entries overlapping. You may build and return a brand-new array instead of mutating intervals in place.

Worked Examples

Example 1
Input:intervals = [[1,3],[6,9]], newInterval = [2,5]
Output:[[1,5],[6,9]]
Explanation: [2,5] overlaps [1,3], so they merge into [1,5]; [6,9] stays as it is.
Example 2
Input:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output:[[1,2],[3,10],[12,16]]
Explanation: [4,8] touches [3,5], [6,7] and [8,10], so all four merge into [3,10].

⚖️Formal Constraints & Bounds

  • 0 <= intervals.length <= 104

  • intervals[i].length == 2

  • 0 <= start_i <= end_i <= 105

  • intervals is sorted by start_i in ascending order

  • newInterval.length == 2

  • 0 <= start <= end <= 105

Deep-Dive & Conceptual Insights

Core Insight

Single-pass three-phase partitioning eliminates the need to re-sort after insertion.

Real-World Scenario & Production Applications

Calendar scheduling engine appointment insertion, CPU task timeslot allocation.

Step-by-Step Execution Trace Table

PhaseProcessing IntervalActionResult List
Phase 1 (Before)[1, 3]Overlaps [2, 5]: skip append[]
Phase 2 (Overlap)[1, 3] with [2, 5]Fuse -> newInterval = [1, 5]-
Append Fused[1, 5]Append fused interval[[1, 5]]
Phase 3 (After)[6, 9]Starts after 5 -> append[[1, 5], [6, 9]]
Code Shape
Archetype Code Shape
Python
11. Append intervals ending before newInterval starts
22. Fuse all intervals overlapping with newInterval
33. Append remaining intervals starting after newInterval ends

Conceptual Narrative

Insert Interval splices a new interval into an already-sorted, non-overlapping list. A single-pass 3-phase partition merges overlapping spans in linear O(N) time with zero re-sorting.

🧭 Conceptual Foundation & Pattern Intuition

Unlike Merge Intervals where input is unsorted (O(Nlog⁡N)O(N \log N)O(NlogN)), Insert Interval provides an array that is already sorted by start time and completely non-overlapping. Appending the new interval and re-sorting would waste the pre-existing order and cost O(Nlog⁡N)O(N \log N)O(NlogN). Exploiting the sorted, disjoint property allows a strict O(N)O(N)O(N) single-pass solution that partitions the timeline into three chronological phases:

  1. Phase 1 (Pre-Collision Disjoint): While intervals[i][1] < newInterval[0], intervals end strictly before newInterval begins. They cannot overlap; append them verbatim.
  2. Phase 2 (Overlapping Fusion): While intervals[i][0] <= newInterval[1], intervals intersect newInterval. Continually absorb them by expanding newInterval to [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])].
  3. Phase 3 (Post-Collision Disjoint): Append the single consolidated newInterval, then append all remaining intervals verbatim (since they start strictly after newInterval ends).
📥 The Analogy: Squeezing an Urgent Delivery Truck into a Train Schedule

Imagine a freight train schedule where every train has its own reserved track window and no two trains conflict. An emergency delivery train (newInterval) needs a window. You walk down the schedule: all morning trains that clear the station before your emergency train arrives run as normal (Phase 1). Any trains that would occupy the station while your train is present are consolidated into one unified priority block spanning the earliest arrival and latest departure (Phase 2). Once that unified block is locked in, all afternoon trains departure slots remain completely untouched (Phase 3).

🔑 Why It Works

Three simple non-nested while loops iterate through the list exactly once: each interval is inspected and appended at most once, guaranteeing optimal O(N)O(N)O(N) time and O(N)O(N)O(N) auxiliary space.

  • Re-sorting pre-sorted intervals: Appending newInterval and calling .sort() takes O(Nlog⁡N)O(N \log N)O(NlogN) time, failing the O(N)O(N)O(N) time optimality constraint.

  • Boundary condition on interval touch: Intervals that touch at a single point (e.g. [1, 2] and [2, 5]) ARE overlapping. Overlap condition is intervals[i][0] <= newInterval[1], not <.

  • Inserting at end or empty input: Forgetting to handle intervals = [] or when newInterval goes at the very end of the list after all existing intervals.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Inserting a new range into an already sorted list of non-overlapping ranges.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: intervals are partitioned into strictly-before, overlapping, and strictly-after sets.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Index out of bounds on empty input.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"Since intervals are sorted, I execute three linear phases: 1) append all intervals ending before newInterval[0]; 2) while intervals overlap (start <= newInterval[1]), expand newInterval bounds; 3) append newInterval and all remaining intervals. Runs in O(N) time and O(N) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: Since intervals are already sorted, single linear pass adds all intervals ending before newInterval, merges overlapping intervals with newInterval, and appends remaining intervals. Total N steps.

SPACE COMPLEXITY

O(N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Result array storing up to N + 1 merged intervals in O(N) space.

Formal Recurrence Relation

T(N)=N comparisons=O(N)T(N) = N \text{ comparisons} = O(N)T(N)=N comparisons=O(N)

Derivation Progression

Left Non-Overlapping Sweep

while intervals[i].end < new.start: res.append()

Appends pre-insertion intervals in O(1) each.

Overlapping Merge

new = [min(starts), max(ends)]

Absorbs overlapping intervals into newInterval in O(1) each.

Right Non-Overlapping Sweep

res.append(remaining)

Appends post-insertion intervals in O(1) each.

Variable Definitions

NNN

Total number of existing non-overlapping intervals

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Scalar pointers (output array excluded)

🟢 Output Space

O(N) Merged interval list

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) if prepended or appended outside range.

Average Case

O(N)O(N)O(N).

Worst Case

O(N)O(N)O(N) overlapping all intervals.

Recurrence Tree Topology

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "insert newInterval into non-overlapping sorted intervals", "merge if necessary". The input is already sorted and disjoint! Junior candidates re-sort after inserting (O(Nlog⁡N)O(N \log N)O(NlogN)). A Senior SWE preserves sorted structure in O(N)O(N)O(N) Linear Time via a 3-Phase Sweep: 1. Disjoint left intervals (end<newStartend < newStartend<newStart) 2. Overlapping intervals (start≤newEndstart \le newEndstart≤newEnd) 3. Disjoint right intervals (start>newEndstart > newEndstart>newEnd).

CONSTRAINTS & BOUNDS

0≤intervals.length≤1040 \le intervals.length \le 10^40≤intervals.length≤104. Time budget is strictly O(N)O(N)O(N). Memory budget is O(N)O(N)O(N) auxiliary to build the output array.

FAANG PRODUCTION TRAPS & EDGE CASES

Single-loop pointer management must cleanly transition between phases.

Theory Context•Intervals & Greedy
MediumLC 57

Insert Interval (LeetCode 57)

Target Frequency:MetaAmazonGoogleApple

You're handed an already-sorted, already-disjoint list of intervals intervals (each entry [start_i, end_i], ordered ascending by start_i), plus one more interval newInterval = [start, end] to drop into that list. Two intervals overlap the instant they share even a single point in common. Splice newInterval in, merging it with anything it touches, so the returned list is still start-sorted and still has no two entries overlapping. You may build and return a brand-new array instead of mutating intervals in place.

Worked Examples

Example 1
Input:intervals = [[1,3],[6,9]], newInterval = [2,5]
Output:[[1,5],[6,9]]
Explanation: [2,5] overlaps [1,3], so they merge into [1,5]; [6,9] stays as it is.
Example 2
Input:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output:[[1,2],[3,10],[12,16]]
Explanation: [4,8] touches [3,5], [6,7] and [8,10], so all four merge into [3,10].

⚖️Formal Constraints & Bounds

  • 0 <= intervals.length <= 104

  • intervals[i].length == 2

  • 0 <= start_i <= end_i <= 105

  • intervals is sorted by start_i in ascending order

  • newInterval.length == 2

  • 0 <= start <= end <= 105

Deep-Dive & Conceptual Insights

Core Insight

Single-pass three-phase partitioning eliminates the need to re-sort after insertion.

Real-World Scenario & Production Applications

Calendar scheduling engine appointment insertion, CPU task timeslot allocation.

Step-by-Step Execution Trace Table

PhaseProcessing IntervalActionResult List
Phase 1 (Before)[1, 3]Overlaps [2, 5]: skip append[]
Phase 2 (Overlap)[1, 3] with [2, 5]Fuse -> newInterval = [1, 5]-
Append Fused[1, 5]Append fused interval[[1, 5]]
Phase 3 (After)[6, 9]Starts after 5 -> append[[1, 5], [6, 9]]
Code Shape
Archetype Code Shape
Python
11. Append intervals ending before newInterval starts
22. Fuse all intervals overlapping with newInterval
33. Append remaining intervals starting after newInterval ends

Conceptual Narrative

Insert Interval splices a new interval into an already-sorted, non-overlapping list. A single-pass 3-phase partition merges overlapping spans in linear O(N) time with zero re-sorting.

🧭 Conceptual Foundation & Pattern Intuition

Unlike Merge Intervals where input is unsorted (O(Nlog⁡N)O(N \log N)O(NlogN)), Insert Interval provides an array that is already sorted by start time and completely non-overlapping. Appending the new interval and re-sorting would waste the pre-existing order and cost O(Nlog⁡N)O(N \log N)O(NlogN). Exploiting the sorted, disjoint property allows a strict O(N)O(N)O(N) single-pass solution that partitions the timeline into three chronological phases:

  1. Phase 1 (Pre-Collision Disjoint): While intervals[i][1] < newInterval[0], intervals end strictly before newInterval begins. They cannot overlap; append them verbatim.
  2. Phase 2 (Overlapping Fusion): While intervals[i][0] <= newInterval[1], intervals intersect newInterval. Continually absorb them by expanding newInterval to [min(newInterval[0], intervals[i][0]), max(newInterval[1], intervals[i][1])].
  3. Phase 3 (Post-Collision Disjoint): Append the single consolidated newInterval, then append all remaining intervals verbatim (since they start strictly after newInterval ends).
📥 The Analogy: Squeezing an Urgent Delivery Truck into a Train Schedule

Imagine a freight train schedule where every train has its own reserved track window and no two trains conflict. An emergency delivery train (newInterval) needs a window. You walk down the schedule: all morning trains that clear the station before your emergency train arrives run as normal (Phase 1). Any trains that would occupy the station while your train is present are consolidated into one unified priority block spanning the earliest arrival and latest departure (Phase 2). Once that unified block is locked in, all afternoon trains departure slots remain completely untouched (Phase 3).

🔑 Why It Works

Three simple non-nested while loops iterate through the list exactly once: each interval is inspected and appended at most once, guaranteeing optimal O(N)O(N)O(N) time and O(N)O(N)O(N) auxiliary space.

  • Re-sorting pre-sorted intervals: Appending newInterval and calling .sort() takes O(Nlog⁡N)O(N \log N)O(NlogN) time, failing the O(N)O(N)O(N) time optimality constraint.

  • Boundary condition on interval touch: Intervals that touch at a single point (e.g. [1, 2] and [2, 5]) ARE overlapping. Overlap condition is intervals[i][0] <= newInterval[1], not <.

  • Inserting at end or empty input: Forgetting to handle intervals = [] or when newInterval goes at the very end of the list after all existing intervals.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Inserting a new range into an already sorted list of non-overlapping ranges.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: intervals are partitioned into strictly-before, overlapping, and strictly-after sets.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Index out of bounds on empty input.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"Since intervals are sorted, I execute three linear phases: 1) append all intervals ending before newInterval[0]; 2) while intervals overlap (start <= newInterval[1]), expand newInterval bounds; 3) append newInterval and all remaining intervals. Runs in O(N) time and O(N) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: Since intervals are already sorted, single linear pass adds all intervals ending before newInterval, merges overlapping intervals with newInterval, and appends remaining intervals. Total N steps.

SPACE COMPLEXITY

O(N) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Result array storing up to N + 1 merged intervals in O(N) space.

Formal Recurrence Relation

T(N)=N comparisons=O(N)T(N) = N \text{ comparisons} = O(N)T(N)=N comparisons=O(N)

Derivation Progression

Left Non-Overlapping Sweep

while intervals[i].end < new.start: res.append()

Appends pre-insertion intervals in O(1) each.

Overlapping Merge

new = [min(starts), max(ends)]

Absorbs overlapping intervals into newInterval in O(1) each.

Right Non-Overlapping Sweep

res.append(remaining)

Appends post-insertion intervals in O(1) each.

Variable Definitions

NNN

Total number of existing non-overlapping intervals

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Scalar pointers (output array excluded)

🟢 Output Space

O(N) Merged interval list

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) if prepended or appended outside range.

Average Case

O(N)O(N)O(N).

Worst Case

O(N)O(N)O(N) overlapping all intervals.

Recurrence Tree Topology

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "insert newInterval into non-overlapping sorted intervals", "merge if necessary". The input is already sorted and disjoint! Junior candidates re-sort after inserting (O(Nlog⁡N)O(N \log N)O(NlogN)). A Senior SWE preserves sorted structure in O(N)O(N)O(N) Linear Time via a 3-Phase Sweep: 1. Disjoint left intervals (end<newStartend < newStartend<newStart) 2. Overlapping intervals (start≤newEndstart \le newEndstart≤newEnd) 3. Disjoint right intervals (start>newEndstart > newEndstart>newEnd).

CONSTRAINTS & BOUNDS

0≤intervals.length≤1040 \le intervals.length \le 10^40≤intervals.length≤104. Time budget is strictly O(N)O(N)O(N). Memory budget is O(N)O(N)O(N) auxiliary to build the output array.

FAANG PRODUCTION TRAPS & EDGE CASES

Single-loop pointer management must cleanly transition between phases.

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