Bird
Raised Fist0
DSA Javaprogramming~20 mins

Sort a Linked List Using Merge Sort in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
šŸŽ–ļø
Merge Sort Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
ā“ Predict Output
intermediate
2:00remaining
Output of Merge Sort on a Linked List
What is the printed state of the linked list after applying merge sort on this list?

Initial list: 4 -> 2 -> 1 -> 3 -> null
DSA Java
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val; this.next = null; }
}

public class Solution {
    public static ListNode mergeSort(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode mid = getMiddle(head);
        ListNode nextToMid = mid.next;
        mid.next = null;
        ListNode left = mergeSort(head);
        ListNode right = mergeSort(nextToMid);
        return merge(left, right);
    }

    private static ListNode getMiddle(ListNode head) {
        if (head == null) return head;
        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    private static ListNode merge(ListNode a, ListNode b) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while (a != null && b != null) {
            if (a.val <= b.val) {
                tail.next = a;
                a = a.next;
            } else {
                tail.next = b;
                b = b.next;
            }
            tail = tail.next;
        }
        tail.next = (a != null) ? a : b;
        return dummy.next;
    }

    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val);
            if (head.next != null) System.out.print(" -> ");
            head = head.next;
        }
        System.out.println(" -> null");
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(4);
        head.next = new ListNode(2);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(3);
        ListNode sorted = mergeSort(head);
        printList(sorted);
    }
}
A1 -> 2 -> 3 -> 4 -> null
B4 -> 3 -> 2 -> 1 -> null
C1 -> 3 -> 2 -> 4 -> null
D2 -> 1 -> 3 -> 4 -> null
Attempts:
2 left
šŸ’” Hint
Merge sort splits the list and merges sorted halves.
🧠 Conceptual
intermediate
1:30remaining
Why use Merge Sort for Linked Lists?
Why is merge sort preferred over quicksort for sorting a linked list?
AQuicksort is faster on linked lists because of pointer swaps.
BMerge sort uses less memory than quicksort on linked lists.
CQuicksort cannot be implemented on linked lists.
DMerge sort does not require random access and works well with linked lists.
Attempts:
2 left
šŸ’” Hint
Think about how linked lists store elements and how merge sort works.
šŸ”§ Debug
advanced
2:00remaining
Identify the Bug in Merge Function
What error will occur when running this merge function on two sorted linked lists?
DSA Java
private static ListNode merge(ListNode a, ListNode b) {
    ListNode dummy = new ListNode(0);
    ListNode tail = dummy;
    while (a != null && b != null) {
        if (a.val < b.val) {
            tail.next = a;
            a = a.next;
        } else {
            tail.next = b;
            b = b.next;
        }
        tail = tail.next;
    }
    tail.next = a;
    tail.next = b;
    return dummy.next;
}
ANullPointerException because tail is not initialized.
BThe last assignment overwrites tail.next causing loss of nodes; some nodes are skipped.
CInfinite loop because tail.next is never updated.
DNo error; the function merges correctly.
Attempts:
2 left
šŸ’” Hint
Check how tail.next is assigned after the loop.
ā“ Predict Output
advanced
2:00remaining
Output After Sorting a Longer Linked List
What is the printed linked list after sorting this list using merge sort?

Initial list: 10 -> 5 -> 3 -> 8 -> 2 -> 7 -> null
DSA Java
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val; this.next = null; }
}

public class Solution {
    public static ListNode mergeSort(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode mid = getMiddle(head);
        ListNode nextToMid = mid.next;
        mid.next = null;
        ListNode left = mergeSort(head);
        ListNode right = mergeSort(nextToMid);
        return merge(left, right);
    }

    private static ListNode getMiddle(ListNode head) {
        if (head == null) return head;
        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    private static ListNode merge(ListNode a, ListNode b) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while (a != null && b != null) {
            if (a.val <= b.val) {
                tail.next = a;
                a = a.next;
            } else {
                tail.next = b;
                b = b.next;
            }
            tail = tail.next;
        }
        tail.next = (a != null) ? a : b;
        return dummy.next;
    }

    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val);
            if (head.next != null) System.out.print(" -> ");
            head = head.next;
        }
        System.out.println(" -> null");
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(10);
        head.next = new ListNode(5);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(8);
        head.next.next.next.next = new ListNode(2);
        head.next.next.next.next.next = new ListNode(7);
        ListNode sorted = mergeSort(head);
        printList(sorted);
    }
}
A3 -> 2 -> 5 -> 7 -> 8 -> 10 -> null
B10 -> 8 -> 7 -> 5 -> 3 -> 2 -> null
C2 -> 3 -> 5 -> 7 -> 8 -> 10 -> null
D2 -> 3 -> 5 -> 8 -> 7 -> 10 -> null
Attempts:
2 left
šŸ’” Hint
Merge sort sorts the list in ascending order.
🧠 Conceptual
expert
1:30remaining
Time Complexity of Merge Sort on Linked List
What is the time complexity of merge sort when applied to a linked list with n nodes?
AO(n log n) because the list is split and merged recursively.
BO(n^2) because each merge requires scanning the entire list.
CO(log n) because the list is divided into halves.
DO(n) because linked lists allow fast merges.
Attempts:
2 left
šŸ’” Hint
Consider how many times the list is split and merged.

Practice

(1/5)
1. What is the main advantage of using merge sort to sort a linked list compared to quicksort?
easy
A. Merge sort is easier to implement with arrays than linked lists.
B. Quicksort is faster on linked lists because it uses less memory.
C. Merge sort does not require random access and works well with linked lists.
D. Quicksort always sorts linked lists in O(n) time.

Solution

  1. Step 1: Understand linked list access

    Linked lists do not support fast random access, so algorithms needing it perform poorly.
  2. Step 2: Compare merge sort and quicksort

    Merge sort splits and merges lists using pointers, avoiding random access, making it efficient for linked lists.
  3. Final Answer:

    Merge sort does not require random access and works well with linked lists. -> Option C
  4. Quick Check:

    Merge sort suits linked lists better than quicksort [OK]
Hint: Merge sort fits linked lists due to pointer-based splitting [OK]
Common Mistakes:
  • Thinking quicksort is always faster on linked lists
  • Assuming arrays and linked lists behave the same
  • Ignoring random access needs
2. Which of the following is the correct base case condition in the merge sort function for a linked list?
easy
A. if (head == null) return head.next;
B. if (head == null || head.next == null) return head;
C. if (head.next == null) return null;
D. if (head == null && head.next == null) return null;

Solution

  1. Step 1: Identify base case for recursion

    When the list is empty or has one node, it is already sorted.
  2. Step 2: Check condition correctness

    Condition 'head == null || head.next == null' correctly checks for empty or single-node list.
  3. Final Answer:

    if (head == null || head.next == null) return head; -> Option B
  4. Quick Check:

    Base case returns head if list size ≤ 1 [OK]
Hint: Base case: empty or single node list returns itself [OK]
Common Mistakes:
  • Using && instead of || in base case
  • Returning null incorrectly for single node
  • Not handling empty list properly
3. Given the linked list: 4 -> 2 -> 1 -> 3 -> null, what is the sorted linked list after applying merge sort?
medium
A. 1 -> 2 -> 3 -> 4 -> null
B. 4 -> 3 -> 2 -> 1 -> null
C. 1 -> 3 -> 2 -> 4 -> null
D. 2 -> 1 -> 3 -> 4 -> null

Solution

  1. Step 1: Split the list into halves

    Split into (4 -> 2) and (1 -> 3).
  2. Step 2: Recursively sort halves and merge

    Sort (4 -> 2) to (2 -> 4), sort (1 -> 3) to (1 -> 3), then merge to (1 -> 2 -> 3 -> 4).
  3. Final Answer:

    1 -> 2 -> 3 -> 4 -> null -> Option A
  4. Quick Check:

    Sorted list ascending order [OK]
Hint: Merge sorted halves to get fully sorted list [OK]
Common Mistakes:
  • Not splitting list correctly
  • Merging without sorting halves
  • Mixing node order during merge
4. Identify the error in this merge function snippet for linked lists:
Node merge(Node a, Node b) {
  if (a == null) return b;
  if (b == null) return a;
  if (a.data < b.data) {
    a.next = merge(a.next, b);
    return b;
  } else {
    b.next = merge(a, b.next);
    return a;
  }
}
medium
A. The function does not merge nodes recursively.
B. The base cases do not handle null nodes.
C. The comparison operator should be <= instead of <.
D. The function returns the wrong node after recursion.

Solution

  1. Step 1: Analyze return statements

    When a.data < b.data, function should return 'a' but returns 'b' incorrectly.
  2. Step 2: Correct return node after recursion

    Return the node chosen as smaller to maintain sorted order; here it should be 'a' or 'b' accordingly.
  3. Final Answer:

    The function returns the wrong node after recursion. -> Option D
  4. Quick Check:

    Return chosen smaller node to merge correctly [OK]
Hint: Return the smaller node after recursive merge [OK]
Common Mistakes:
  • Returning wrong node after recursive call
  • Ignoring base cases
  • Incorrect comparison operator
5. You have a linked list with nodes: 5 -> 3 -> 8 -> 2 -> 7 -> null. After applying merge sort, what is the correct sorted linked list? Also, explain why merge sort is preferred over bubble sort for this linked list.
hard
A. 2 -> 3 -> 5 -> 7 -> 8 -> null; Merge sort is faster and uses less memory on linked lists.
B. 8 -> 7 -> 5 -> 3 -> 2 -> null; Bubble sort is faster for small lists.
C. 2 -> 3 -> 5 -> 7 -> 8 -> null; Bubble sort is preferred because it is simpler.
D. 5 -> 3 -> 8 -> 2 -> 7 -> null; Merge sort does not work on linked lists.

Solution

  1. Step 1: Sort the list using merge sort

    Sorted order is 2 -> 3 -> 5 -> 7 -> 8 -> null after splitting and merging.
  2. Step 2: Explain merge sort advantage

    Merge sort is O(n log n) and uses pointers efficiently; bubble sort is O(n²) and inefficient for linked lists.
  3. Final Answer:

    2 -> 3 -> 5 -> 7 -> 8 -> null; Merge sort is faster and uses less memory on linked lists. -> Option A
  4. Quick Check:

    Sorted list + merge sort efficiency [OK]
Hint: Merge sort is efficient and stable for linked lists [OK]
Common Mistakes:
  • Confusing bubble sort as faster
  • Incorrect sorted order
  • Thinking merge sort can't handle linked lists
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