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•Priority Queue / Heap
HardLC 23

Merge k Sorted Lists (LeetCode 23)

Target Frequency:MetaAmazonGoogleApple

You're given lists, an array holding k linked lists, where each individual list is already sorted from smallest to largest.

Combine every node from all k lists into a single linked list that is itself sorted from smallest to largest, and return its head.

Worked Examples

Example 1
Input:lists = [[1,4,5],[1,3,4],[2,6]]
Output:[1,1,2,3,4,4,5,6]
Explanation: Reading the three input lists as 1->4->5, 1->3->4, and 2->6, folding every node from all three into ascending order produces 1->1->2->3->4->4->5->6.
Example 2
Input:lists = []
Output:[]
Explanation: There are no lists, so the result is empty.
Example 3
Input:lists = [[]]
Output:[]
Explanation: The one list is empty, so the result is empty.

⚖️Formal Constraints & Bounds

  • k == lists.length

  • 0 <= k <= 104

  • 0 <= lists[i].length <= 500

  • -104 <= lists[i][j] <= 104

  • lists[i] is sorted in ascending order.

  • The sum of lists[i].length will not exceed 104.

Deep-Dive & Conceptual Insights

Core Insight

The min-heap always contains at most K items, reducing the cost of finding the next minimum element from O(K) to O(log K).

Real-World Scenario & Production Applications

External merge sort in database query engines (PostgreSQL/DuckDB spilling to disk) and distributed log stream aggregation.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Head Node Priority Queue Seeding

Push the head node of each of the K sorted linked lists into a min-heap (node.val, list_idx, node) in O(K log K) time.

Mathematical Recurrence / Code Invariant
min_heap = []
for i, head in enumerate(lists):
    if head:
        heappush(min_heap, (head.val, i, head))

Step-by-Step Execution Trace Table

StepHeap Frontier (val, list, index)Popped ElementMerged List OutputNext Refilled Element
1(1,A,0), (1,B,0), (2,C,0)(1, A, 0)[1](4, A, 1)
2(1,B,0), (2,C,0), (4,A,1)(1, B, 0)[1, 1](3, B, 1)
3(2,C,0), (3,B,1), (4,A,1)(2, C, 0)[1, 1, 2](6, C, 1)
4(3,B,1), (4,A,1), (6,C,1)(3, B, 1)[1, 1, 2, 3](4, B, 2)
5(4,A,1), (4,B,2), (6,C,1)(4, A, 1)[1, 1, 2, 3, 4](5, A, 2)
6(4,B,2), (5,A,2), (6,C,1)(4, B, 2)[1, 1, 2, 3, 4, 4]List B exhausted →\to→ None
7(5,A,2), (6,C,1)(5, A, 2)[1, 1, 2, 3, 4, 4, 5]List A exhausted →\to→ None
8(6,C,1)(6, C, 1)[1, 1, 2, 3, 4, 4, 5, 6]All lists exhausted →\to→ Done
Code Shape
Archetype Code Shape
Python
1heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
2dummy = ListNode(0)
3curr = dummy
4while heap:
5 val, i, node = heappop(heap)
6 curr.next = node
7 curr = curr.next
8 if node.next:
9 heappush(heap, (node.next.val, i, node.next))
10return dummy.next

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition
Code / Blueprint
Merging $K$ pre-sorted linked lists generalizes the 2-way merge from Merge Sort. Rather than comparing all $K$ list heads on every step in $O(K)$ time, we place the active head node of each list into a min-heap of size $K$. Extracting the root yields the globally smallest unmerged node in $O(\log K)$ time. Appending its successor `curr.next` back to the heap maintains the multi-way stream frontier until all lists are exhausted in $O(N \log K)$ total time.
 
🃏 The Analogy: Merging k Decks of Cards

Imagine k separate decks of cards, each already sorted face-up. To merge them into one sorted pile, you only ever need to look at the top card of each deck — the smallest visible card across all k decks is guaranteed to be the smallest card not yet placed anywhere. Take it, place it on your output pile, then flip over the next card in whichever deck you just took from. Repeat until every deck is empty.

🔑 The Key Idea in the Code

The heap never holds more than k nodes at once — it's not merging all N nodes at once, only ever comparing the current "frontier" (one candidate per list), which is what keeps this O(N log K) instead of O(N·K).

  • Python 3 TypeError on duplicate node values: Storing (node.val, node) in Python's heapq raises TypeError: '<' not supported between instances of 'ListNode' when two nodes have identical .val. Store (node.val, index, node) as a unique tie-breaker.

  • Empty input list or list with null heads: Guarding lists = [] and filtering out empty list heads (None) before seeding the min-heap.

  • Advancing node pointer without pushing node.next: After extracting minimum node, you must push node.next into the heap if node.next is not None.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Merge K independently sorted linked lists.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Decision rule: pop (val, i, node), link it after curr, and push node.next from the same list i. A list advances only when its own head is used, so the output stays sorted.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Node comparison failure in Python heap: store tuple (node.val, list_index, node) to prevent comparing ListNode objects.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use a K-Way Merge. The smallest node left overall is always the head of one of the lists, so I keep just one head per list in a min-heap, as value, list index and node. I pop the smallest, link it after my tail, and push the next node from that same list, so each list advances only when its own head is used and the output stays sorted. A dummy head means the first node needs no special case, and I skip empty lists. The trap is ties: I put the list index in each tuple, so equal values never make Python compare two nodes, which would crash. Every node is pushed and popped once, so time is O(N log K) for N nodes in total, and the heap needs O(K) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N log K)

Look at the execution steps: Min-heap stores current head of each of the K sorted linked lists. At each step, extracts min node in O(log K) and pushes next node in that list in O(log K). Total N nodes processed.

SPACE COMPLEXITY

O(K) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Min-heap stores at most K list node references simultaneously.

Formal Recurrence Relation

T(N, K) = N · O(log K) = O(N log K)

Derivation Progression

Heap Initialization

K list heads ⟹ O(K log K)

Initializes min-heap with heads of all K lists.

Extract-Min & Splicing

N total nodes × O(log K) heappop/heappush

Appends smallest node to merged list in O(log K).

Total Linear-Logarithmic Bound

O(N log K)

Every node in all lists is pushed and popped exactly once.

Variable Definitions

NNN

Total number of nodes across all linked lists combined

KKK

Number of sorted linked lists (min-heap capacity)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(K) Min-heap of size K

🟢 Output Space

O(1) Merged linked list head (in-place pointer splicing)

Boundary Best / Worst Cases

Best Case

O(Nlog⁡K)O(N \log K)O(NlogK)

Average Case

O(Nlog⁡K)O(N \log K)O(NlogK)

Worst Case

O(Nlog⁡K)O(N \log K)O(NlogK)

Binary Heap Priority Queue Tree

Binary Heap Priority Queue Tree
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Trigger: "merge k sorted linked lists": every node must come out, in order. Merging the lists one after another costs O(k⋅N)O(k \cdot N)O(k⋅N), NNN = total nodes. A K-Way Merge keeps one head per list in a min-heap, so each node costs O(log⁡k)O(\log k)O(logk).

CONSTRAINTS & BOUNDS

k≤104k \le 10^4k≤104, total nodes N≤104N \le 10^4N≤104. Time budget: O(Nlog⁡k)O(N \log k)O(Nlogk). Memory budget: O(k)O(k)O(k) heap elements at any moment.

FAANG PRODUCTION TRAPS & EDGE CASES

With up to 10410^4104 lists, many short or empty, the heap is filled once with every non-empty head: an empty list is None and has no .val, so it must be skipped. When the lists are real streams (files, network readers), each is read in order and only its current head is held, so kkk open inputs, not NNN values, are the memory cost.

Core Algorithmic State Invariants

  1. Relink the Nodes, Don't Copy Them

curr.next = node reuses the popped node itself, so the merged list is built from the input nodes with no new allocations. The dummy sentinel gives curr somewhere to start, so the first node needs no special case, and dummy.next is the merged head.

Theory Context•Priority Queue / Heap
HardLC 23

Merge k Sorted Lists (LeetCode 23)

Target Frequency:MetaAmazonGoogleApple

You're given lists, an array holding k linked lists, where each individual list is already sorted from smallest to largest.

Combine every node from all k lists into a single linked list that is itself sorted from smallest to largest, and return its head.

Worked Examples

Example 1
Input:lists = [[1,4,5],[1,3,4],[2,6]]
Output:[1,1,2,3,4,4,5,6]
Explanation: Reading the three input lists as 1->4->5, 1->3->4, and 2->6, folding every node from all three into ascending order produces 1->1->2->3->4->4->5->6.
Example 2
Input:lists = []
Output:[]
Explanation: There are no lists, so the result is empty.
Example 3
Input:lists = [[]]
Output:[]
Explanation: The one list is empty, so the result is empty.

⚖️Formal Constraints & Bounds

  • k == lists.length

  • 0 <= k <= 104

  • 0 <= lists[i].length <= 500

  • -104 <= lists[i][j] <= 104

  • lists[i] is sorted in ascending order.

  • The sum of lists[i].length will not exceed 104.

Deep-Dive & Conceptual Insights

Core Insight

The min-heap always contains at most K items, reducing the cost of finding the next minimum element from O(K) to O(log K).

Real-World Scenario & Production Applications

External merge sort in database query engines (PostgreSQL/DuckDB spilling to disk) and distributed log stream aggregation.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Head Node Priority Queue Seeding

Push the head node of each of the K sorted linked lists into a min-heap (node.val, list_idx, node) in O(K log K) time.

Mathematical Recurrence / Code Invariant
min_heap = []
for i, head in enumerate(lists):
    if head:
        heappush(min_heap, (head.val, i, head))

Step-by-Step Execution Trace Table

StepHeap Frontier (val, list, index)Popped ElementMerged List OutputNext Refilled Element
1(1,A,0), (1,B,0), (2,C,0)(1, A, 0)[1](4, A, 1)
2(1,B,0), (2,C,0), (4,A,1)(1, B, 0)[1, 1](3, B, 1)
3(2,C,0), (3,B,1), (4,A,1)(2, C, 0)[1, 1, 2](6, C, 1)
4(3,B,1), (4,A,1), (6,C,1)(3, B, 1)[1, 1, 2, 3](4, B, 2)
5(4,A,1), (4,B,2), (6,C,1)(4, A, 1)[1, 1, 2, 3, 4](5, A, 2)
6(4,B,2), (5,A,2), (6,C,1)(4, B, 2)[1, 1, 2, 3, 4, 4]List B exhausted →\to→ None
7(5,A,2), (6,C,1)(5, A, 2)[1, 1, 2, 3, 4, 4, 5]List A exhausted →\to→ None
8(6,C,1)(6, C, 1)[1, 1, 2, 3, 4, 4, 5, 6]All lists exhausted →\to→ Done
Code Shape
Archetype Code Shape
Python
1heap = [(node.val, i, node) for i, node in enumerate(lists) if node]
2dummy = ListNode(0)
3curr = dummy
4while heap:
5 val, i, node = heappop(heap)
6 curr.next = node
7 curr = curr.next
8 if node.next:
9 heappush(heap, (node.next.val, i, node.next))
10return dummy.next

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition
Code / Blueprint
Merging $K$ pre-sorted linked lists generalizes the 2-way merge from Merge Sort. Rather than comparing all $K$ list heads on every step in $O(K)$ time, we place the active head node of each list into a min-heap of size $K$. Extracting the root yields the globally smallest unmerged node in $O(\log K)$ time. Appending its successor `curr.next` back to the heap maintains the multi-way stream frontier until all lists are exhausted in $O(N \log K)$ total time.
 
🃏 The Analogy: Merging k Decks of Cards

Imagine k separate decks of cards, each already sorted face-up. To merge them into one sorted pile, you only ever need to look at the top card of each deck — the smallest visible card across all k decks is guaranteed to be the smallest card not yet placed anywhere. Take it, place it on your output pile, then flip over the next card in whichever deck you just took from. Repeat until every deck is empty.

🔑 The Key Idea in the Code

The heap never holds more than k nodes at once — it's not merging all N nodes at once, only ever comparing the current "frontier" (one candidate per list), which is what keeps this O(N log K) instead of O(N·K).

  • Python 3 TypeError on duplicate node values: Storing (node.val, node) in Python's heapq raises TypeError: '<' not supported between instances of 'ListNode' when two nodes have identical .val. Store (node.val, index, node) as a unique tie-breaker.

  • Empty input list or list with null heads: Guarding lists = [] and filtering out empty list heads (None) before seeding the min-heap.

  • Advancing node pointer without pushing node.next: After extracting minimum node, you must push node.next into the heap if node.next is not None.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Merge K independently sorted linked lists.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Decision rule: pop (val, i, node), link it after curr, and push node.next from the same list i. A list advances only when its own head is used, so the output stays sorted.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Node comparison failure in Python heap: store tuple (node.val, list_index, node) to prevent comparing ListNode objects.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use a K-Way Merge. The smallest node left overall is always the head of one of the lists, so I keep just one head per list in a min-heap, as value, list index and node. I pop the smallest, link it after my tail, and push the next node from that same list, so each list advances only when its own head is used and the output stays sorted. A dummy head means the first node needs no special case, and I skip empty lists. The trap is ties: I put the list index in each tuple, so equal values never make Python compare two nodes, which would crash. Every node is pushed and popped once, so time is O(N log K) for N nodes in total, and the heap needs O(K) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N log K)

Look at the execution steps: Min-heap stores current head of each of the K sorted linked lists. At each step, extracts min node in O(log K) and pushes next node in that list in O(log K). Total N nodes processed.

SPACE COMPLEXITY

O(K) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Min-heap stores at most K list node references simultaneously.

Formal Recurrence Relation

T(N, K) = N · O(log K) = O(N log K)

Derivation Progression

Heap Initialization

K list heads ⟹ O(K log K)

Initializes min-heap with heads of all K lists.

Extract-Min & Splicing

N total nodes × O(log K) heappop/heappush

Appends smallest node to merged list in O(log K).

Total Linear-Logarithmic Bound

O(N log K)

Every node in all lists is pushed and popped exactly once.

Variable Definitions

NNN

Total number of nodes across all linked lists combined

KKK

Number of sorted linked lists (min-heap capacity)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(K) Min-heap of size K

🟢 Output Space

O(1) Merged linked list head (in-place pointer splicing)

Boundary Best / Worst Cases

Best Case

O(Nlog⁡K)O(N \log K)O(NlogK)

Average Case

O(Nlog⁡K)O(N \log K)O(NlogK)

Worst Case

O(Nlog⁡K)O(N \log K)O(NlogK)

Binary Heap Priority Queue Tree

Binary Heap Priority Queue Tree
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Trigger: "merge k sorted linked lists": every node must come out, in order. Merging the lists one after another costs O(k⋅N)O(k \cdot N)O(k⋅N), NNN = total nodes. A K-Way Merge keeps one head per list in a min-heap, so each node costs O(log⁡k)O(\log k)O(logk).

CONSTRAINTS & BOUNDS

k≤104k \le 10^4k≤104, total nodes N≤104N \le 10^4N≤104. Time budget: O(Nlog⁡k)O(N \log k)O(Nlogk). Memory budget: O(k)O(k)O(k) heap elements at any moment.

FAANG PRODUCTION TRAPS & EDGE CASES

With up to 10410^4104 lists, many short or empty, the heap is filled once with every non-empty head: an empty list is None and has no .val, so it must be skipped. When the lists are real streams (files, network readers), each is read in order and only its current head is held, so kkk open inputs, not NNN values, are the memory cost.

Core Algorithmic State Invariants

  1. Relink the Nodes, Don't Copy Them

curr.next = node reuses the popped node itself, so the merged list is built from the input nodes with no new allocations. The dummy sentinel gives curr somewhere to start, so the first node needs no special case, and dummy.next is the merged head.

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