Bird
Raised Fist0
Interview Prepin-place-linked-listhardAmazonFacebookGoogleMicrosoftBloomberg

Merge K Sorted Lists

Choose your preparation mode4 modes available
</>
IDE
def mergeKLists(lists: List[Optional[ListNode]]) -> Optional[ListNode]:public ListNode mergeKLists(ListNode[] lists)ListNode* mergeKLists(vector<ListNode*>& lists)function mergeKLists(lists)
def mergeKLists(lists: List[Optional[ListNode]]) -> Optional[ListNode]:
    # Write your solution here
    pass
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        // Write your solution here
        return null;
    }
}
#include <vector>
using namespace std;

ListNode* mergeKLists(vector<ListNode*>& lists) {
    // Write your solution here
    return nullptr;
}
function mergeKLists(lists) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: Missing nodes or incomplete merged listNot processing all lists or stopping early when merging✅ Ensure all lists are pushed into the min-heap and all nodes are processed until heap is empty
Wrong: Output list missing duplicates or merged incorrectlySkipping nodes with equal values or merging duplicates incorrectly✅ Do not skip nodes with equal values; always push next nodes into the heap regardless of duplicates
Wrong: Crashes or returns non-null for empty inputNo check for empty input array or all empty lists✅ Add guard clauses to return null if input array is empty or all lists are empty
Wrong: Time limit exceeded (TLE)Using brute force sorting or repeated pairwise merges with O(kN) or O(N log N) complexity✅ Use a min-heap or divide and conquer merge to achieve O(N log k) time complexity
Wrong: Incorrect order due to greedy mergesMerging lists one by one greedily without balancing or heap✅ Use divide and conquer or min-heap to merge all lists efficiently and correctly
✓
Test Cases
t1_01basic
Input{"lists":[[1,4,5],[1,3,4],[2,6]]}
Expected"1->1->2->3->4->4->5->6"

Merging the three sorted lists results in one sorted list: 1->1->2->3->4->4->5->6

t1_02basic
Input{"lists":[[2,5,7],[3,11],[1,6,8,9]]}
Expected"1->2->3->5->6->7->8->9->11"

Merging three sorted lists results in 1->2->3->5->6->7->8->9->11

t2_01edge
Input{"lists":[]}
Expected""

Empty list array input should return an empty list (null).

t2_02edge
Input{"lists":[[],[],[]]}
Expected""

All lists empty should return an empty list (null).

t2_03edge
Input{"lists":[[5],[1],[3]]}
Expected"1->3->5"

Lists with one element each should merge correctly into a sorted list.

t2_04edge
Input{"lists":[[-10],[0],[10]]}
Expected"-10->0->10"

Lists with negative and positive single elements merge correctly.

t3_01corner
Input{"lists":[[1,4,5],[1,3,4],[2,6],[1,1,1]]}
Expected"1->1->1->1->2->3->4->4->5->6"

Merging lists with duplicates should maintain all duplicates in sorted order.

t3_02corner
Input{"lists":[[1,3,5],[2,4,6],[7,8,9]]}
Expected"1->2->3->4->5->6->7->8->9"

Greedy approach that merges only first two lists repeatedly fails; correct approach merges all lists properly.

t3_03corner
Input{"lists":[[1,2,3],[1,2,3],[1,2,3]]}
Expected"1->1->1->2->2->2->3->3->3"

Confusing 0/1 vs unbounded merges: each node must be used exactly once, no duplicates added or missed.

t4_01performance
Input{"lists":[[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499]]}
⏱ Performance - must finish in 2000ms

Merging 1 list with 500 nodes tests handling large input; must complete in 2s with O(N log k) or better.

Practice

(1/5)
1. Identify the bug in the following code snippet intended to find the intersection node of two singly linked lists using the two-pointer approach:
medium
A. Line 6: Using '!=' instead of 'is not' to compare nodes
B. Line 8: Not checking if headA or headB is None before starting
C. Line 9: Incorrectly resetting pA and pB to headB and headA respectively
D. Line 10: Returning pA instead of pB

Solution

  1. Step 1: Understand node comparison

    Nodes must be compared by reference, not by value. Using '!=' compares values, not references, causing incorrect intersection detection.
  2. Step 2: Identify correct comparison operator

    'is not' compares object identity, ensuring correct detection of intersection node.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Using '!=' causes false positives or misses intersection [OK]
Hint: Use 'is' or 'is not' to compare nodes, not '==' or '!=' [OK]
Common Mistakes:
  • Comparing node values instead of references
  • Forgetting to handle empty lists
  • Infinite loops due to pointer reset errors
2. The following code attempts to merge two sorted linked lists in-place:
def mergeTwoLists(l1, l2):
    if not l1:
        return l2
    if not l2:
        return l1
    if l1.val > l2.val:
        l1, l2 = l2, l1
    head = l1
    while l1 and l2:
        prev = None
        while l1 and l1.val <= l2.val:
            prev = l1
            # BUG: Missing l1 pointer advancement here
        prev.next = l2
        l1, l2 = l2, l1
    return head
What is the bug in this code?
medium
A. Swapping l1 and l2 when l1.val > l2.val is incorrect
B. Not initializing prev before inner while loop causes NoneType error
C. Returning head instead of l1 or l2 at the end causes wrong output
D. Line missing advancement of l1 inside inner while loop causes infinite loop

Solution

  1. Step 1: Identify the inner while loop behavior

    The inner loop should advance l1 pointer to traverse nodes with values <= l2.val. Missing l1 = l1.next causes infinite loop.
  2. Step 2: Confirm impact of missing advancement

    Without advancing l1, prev remains the same, loop never ends, causing infinite loop or crash.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Missing l1 advancement inside inner loop causes infinite loop [OK]
Hint: Always advance pointers inside loops to avoid infinite loops [OK]
Common Mistakes:
  • Confusing swap of l1 and l2 as bug
  • Thinking return head is incorrect
  • Assuming prev initialization causes error
3. Consider the following buggy code snippet for removing duplicates from a sorted linked list. Which line contains the subtle bug that causes incorrect removal of duplicates at the head of the list?
def deleteDuplicates(head):
    if not head or not head.next:
        return head
    prev = None
    current = head
    while current and current.next:
        if current.val == current.next.val:
            val_to_remove = current.val
            while current and current.val == val_to_remove:
                current = current.next
            if prev:
                prev.next = current
        else:
            prev = current
            current = current.next
    return head
medium
A. Line 3: prev initialized to null instead of dummy node.
B. Line 7: while loop condition should check current.next.val instead of current.val.
C. Line 11: Missing update of prev when duplicates are removed at head.
D. Line 14: prev pointer updated incorrectly inside else block.

Solution

  1. Step 1: Identify problem with head duplicates

    Without a dummy node, if duplicates appear at the head, prev is None and cannot link to the new head after removal.
  2. Step 2: Analyze code behavior

    Line 3 initializes prev to None instead of a dummy node, so when duplicates at the head are removed, the head pointer is not updated correctly, causing incorrect output.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Dummy node needed to handle head duplicates [OK]
Hint: Always use dummy node to handle head duplicates [OK]
Common Mistakes:
  • Not using dummy head
  • Incorrect prev updates
  • Skipping null checks
4. Examine the following buggy code intended to remove duplicates from a sorted linked list. Which line contains the subtle bug that can cause an infinite loop or incorrect skipping of nodes?
medium
A. Line 5: current.next = current.next.next
B. Line 4: if current.val == current.next.val:
C. Line 7: current = current.next
D. Line 2: current = head

Solution

  1. Step 1: Understand pointer updates

    When duplicates are found, current.next is updated to skip duplicate nodes; current pointer stays to check next node.
  2. Step 2: Identify bug in pointer advancement

    If current pointer is moved unconditionally after removal, it may skip nodes or cause infinite loops. The else clause must move current only when no duplicate is removed.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Incorrect pointer advancement causes skipping or infinite loops [OK]
Hint: Only advance current when no duplicate removed [OK]
Common Mistakes:
  • Advancing current pointer after removing duplicates
5. Suppose the problem is modified so that the linked list is circular (last node points back to head). Which of the following changes is necessary to correctly remove the nth node from the end in one pass?
hard
A. Use the same two-pointer approach without changes; it works as is.
B. First break the circular link to convert it into a linear list, then apply the standard algorithm.
C. Use a hash set to detect the cycle and count nodes before removal.
D. Modify the recursion to detect when the node revisits the head to stop infinite recursion.

Solution

  1. Step 1: Understand circular list implications

    In a circular list, traversal never ends naturally, so counting nodes or recursion can loop infinitely.
  2. Step 2: Break the cycle

    Temporarily breaking the cycle converts it to a linear list, allowing standard removal algorithms to work correctly.
  3. Step 3: Restore circular link if needed

    After removal, reconnect the last node to the new head to restore circularity.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Breaking cycle prevents infinite loops and enables standard logic [OK]
Hint: Circular lists require cycle breaking before linear algorithms [OK]
Common Mistakes:
  • Assuming two-pointer works on circular lists
  • Using recursion without cycle detection
  • Using extra space unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard