AlgoInsight

DSA problem

Delete Node in a Linked List

MediumLinked ListPattern: Linked Listtop600AmazonMicrosoftAppleAdobeBloomberg

There is a singly linked list and you are given a reference to a node inside it, but NOT the head of the list. The task is to delete the given node from the list. It is guaranteed that the node to be deleted is not the tail node.

This problem is a clever twist on linked-list deletion. Normally to delete a node you need access to its predecessor, so you can reroute prev.next to skip the doomed node. Here you have no head and no way to reach the predecessor, so that classic strategy is impossible.

The key realization is that you do not actually have to remove the physical node you were given; you only have to make the list behave as if its value were gone. Since you have access to the node's successor, you can copy the successor's value into the current node, and then splice out the successor instead.

The optimal approach is therefore a constant-time trick: set node.val to node.next.val, then set node.next to node.next.next. This effectively shifts every subsequent value one step earlier and drops one node, producing a list identical to one with the target value removed. It runs in O(1) time and O(1) space.

Examples

Example 1
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the node with value 5. After copying the next value and skipping a node, the list becomes [4,1,9].
Example 2
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the node with value 1. After the copy-and-skip operation, the list becomes [4,5,9].
Example 3
Input: head = [1,2,3,4], node = 3
Output: [1,2,4]
Explanation: The node holding 3 takes on the value 4 from its successor, then the successor is unlinked, leaving [1,2,4].

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-list

Browse all DSA problems