Insert node before (kth node) in Doubly Linked List

Pattern: Doubly and circular lists

medium

Walk to node K and link the new node between K's prev and K. If K is the head, the new node becomes the head.

The problem

Given the head of a doubly linked list, a value X and a position K (counting from 1, with 1 ≤ K ≤ n), insert a new node holding X just before the K-th node and return the head. For example, 1 ⇄ 3 ⇄ 5 with X = 7, K = 2 becomes 1 ⇄ 7 ⇄ 3 ⇄ 5.

The function name insertBeforeKthPosition matches the takeUforward practice page. Use the link above for the exact statement and limits. In this guide's code the node type is DNode.

Think first

  • Where does the walk stop?
  • Which four pointers connect the new node?
  • What happens when K = 1?

Hints

    Brute force, and why it fails

    Rebuilding is O(n) with new nodes. Linking in place is O(K) with one new node.

    The key insight

    "Before node K" in a doubly linked list needs only node K, because its prev gives the other neighbour.

    Dry run

    10 
    31kth
    52 

    The list is 1 ⇄ 3 ⇄ 5, X = 7 and K = 2. Walk to node 2, the 3.

    Step 1 of 3

    The plan

    kth = head; repeat K - 1 times: kth = kth.next
    node = new DNode(X); node.prev = kth.prev; node.next = kth
    if kth.prev is not null: kth.prev.next = node
    else: head = node
    kth.prev = node
    return head
    

    Complexity

    Time
    O(K)
    Space
    O(1)

    The walk stops at node K.

    Edge cases

    • K = 1: the new node is the head.
    • K = n: the new node goes before the tail.
    • One node with K = 1: two nodes.
    I've built my logic, show the code

    Java

    class Solution {
        public DNode insertBeforeKthPosition(DNode head, int X, int K) {
            DNode kth = head;
            for (int i = 1; i < K; i++) kth = kth.next;   // node K
            DNode node = new DNode(X);
            node.prev = kth.prev;
            node.next = kth;
            if (kth.prev != null) kth.prev.next = node;
            else head = node;                       // inserting before the head
            kth.prev = node;
            return head;
        }
    }

    C++

    class Solution {
    public:
        DNode* insertBeforeKthPosition(DNode* head, int X, int K) {
            DNode* kth = head;
            for (int i = 1; i < K; i++) kth = kth->next;   // node K
            DNode* node = new DNode(X);
            node->prev = kth->prev;
            node->next = kth;
            if (kth->prev != NULL) kth->prev->next = node;
            else head = node;                       // inserting before the head
            kth->prev = node;
            return head;
        }
    };

    Python

    from lib import DNode
    
    class Solution:
        def insertBeforeKthPosition(self, head: DNode, X: int, K: int) -> DNode:
            kth = head
            for _ in range(K - 1):                  # node K
                kth = kth.next
            node = DNode(X, kth.prev, kth)
            if kth.prev is not None:
                kth.prev.next = node
            else:
                head = node                         # inserting before the head
            kth.prev = node
            return head

    Common mistakes

    • Setting kth.prev = node before saving kth.prev, which loses the node before.
    • Forgetting to update the head when K = 1.
    • Walking K steps, which inserts one place too late.

    Similar problems