LeetCode 147: Insertion Sort List Solution

Master LeetCode problem 147 (Insertion Sort List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

147. Insertion Sort List

Problem Explanation

Explanation:

  • Algorithmic Idea:

    1. We start with an empty sorted list and iterate through the input list.
    2. For each element in the input list, we remove it and insert it in the correct position in the sorted list.
    3. To insert an element into the sorted list, we compare it with each element from the beginning of the sorted list and find the correct position to insert it.
  • Step-by-Step Iterations:

    • For input list [4,2,1,3]:
      1. Start with an empty sorted list.
      2. Insert 4 into the sorted list: [4]
      3. Insert 2 into the sorted list: [2,4]
      4. Insert 1 into the sorted list: [1,2,4]
      5. Insert 3 into the sorted list: [1,2,3,4]
  • Time Complexity: O(n^2) where n is the number of nodes in the linked list.

  • Space Complexity: O(1)

:

Solution Code

class Solution {
    public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode dummy = new ListNode(-1);
        ListNode curr = head;
        
        while (curr != null) {
            ListNode prev = dummy;
            ListNode nextNode = curr.next;
            
            while (prev.next != null && prev.next.val < curr.val) {
                prev = prev.next;
            }
            
            curr.next = prev.next;
            prev.next = curr;
            curr = nextNode;
        }
        
        return dummy.next;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 147 (Insertion Sort List)?

This page provides optimized solutions for LeetCode problem 147 (Insertion Sort List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 147 (Insertion Sort List)?

The time complexity for LeetCode 147 (Insertion Sort List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 147 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 147 in Java, C++, or Python.

Back to LeetCode Solutions