Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

147. Insertion Sort List

Linked ListSorting

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)

:

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.