Insertion at the Kth position of Linked List

Pattern: Traversal and dummy nodes

easy

Stand on node K - 1 and link the new node between it and the old node K. A dummy node in front makes K = 1 work the same way.

The problem

Given the head of a singly linked list, a value X and a position K (counting from 1, with 1 ≤ K ≤ n + 1), insert a new node holding X so that it becomes the K-th node, and return the head. For example, 1 → 2 → 3 with X = 5 and K = 2 becomes 1 → 5 → 2 → 3. K = n + 1 adds it at the end.

The function name insertAtKthPosition matches the takeUforward practice page. Use the link above for the exact statement and limits.

Think first

  • After the insertion, which node comes just before the new one?
  • In what order must the two pointers be set?
  • How can K = 1 and K = n + 1 use the same code?

Hints

    Brute force, and why it fails

    Copy to an array, insert at index K - 1, rebuild: O(n) memory. Linking in place needs O(1).

    The key insight

    Every insertion is "after some node". The dummy turns "insert at the front" into "insert after the dummy", so one rule covers every position.

    Dry run

    dummy0prev
    11 
    22 
    33 

    The list is 1 → 2 → 3, X = 5 and K = 2. A dummy goes in front, and prev starts on it (node 0).

    Step 1 of 4

    The plan

    dummy.next = head, prev = dummy
    repeat K - 1 times: prev = prev.next
    node = new node(X)
    node.next = prev.next
    prev.next = node
    return dummy.next
    

    Complexity

    Time
    O(K)
    Space
    O(1)

    The walk stops at node K - 1.

    Edge cases

    • K = 1: the new node is the head.
    • K = n + 1: the new node is the tail.
    • Empty list with K = 1: just the new node.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode insertAtKthPosition(ListNode head, int X, int K) {
            ListNode dummy = new ListNode(0);       // so inserting at position 1 needs no special case
            dummy.next = head;
            ListNode prev = dummy;
            for (int i = 1; i < K; i++) prev = prev.next;   // node K - 1 (the dummy is node 0)
            ListNode node = new ListNode(X);
            node.next = prev.next;                  // link the new node in front of the old node K
            prev.next = node;
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        ListNode* insertAtKthPosition(ListNode* head, int X, int K) {
            ListNode dummy(0);                      // so inserting at position 1 needs no special case
            dummy.next = head;
            ListNode* prev = &dummy;
            for (int i = 1; i < K; i++) prev = prev->next;   // node K - 1 (the dummy is node 0)
            ListNode* node = new ListNode(X);
            node->next = prev->next;                // link the new node in front of the old node K
            prev->next = node;
            return dummy.next;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def insertAtKthPosition(self, head: ListNode, X: int, K: int) -> ListNode:
            dummy = ListNode(0, head)               # so inserting at position 1 needs no special case
            prev = dummy
            for _ in range(K - 1):                  # node K - 1 (the dummy is node 0)
                prev = prev.next
            prev.next = ListNode(X, prev.next)      # link the new node in front of the old node K
            return dummy.next

    Common mistakes

    • Setting prev.next = node first, which loses the rest of the list.
    • Taking K steps instead of K - 1.
    • Handling K = 1 separately and forgetting to return the new head.

    Similar problems