Delete Node in a Linked List - Problem

Given a singly-linked list and a reference to a specific node to be deleted, write a function to delete that node from the linked list.

Important constraints:

  • You are only given the node to be deleted - you do NOT have access to the head of the list
  • All values in the linked list are unique
  • The given node is guaranteed NOT to be the last node in the list
  • The given node is guaranteed to be a valid node in the list

The goal is to make it so that:

  • The value of the given node no longer exists in the linked list
  • The number of nodes decreases by one
  • All other values remain in the same relative order

Input & Output

Example 1 — Delete Middle Node
$ Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
💡 Note: The node with value 5 should be deleted. We copy the next node's value (1) to the current node, making it [4,1,1,9], then skip the next node to get [4,1,9].
Example 2 — Delete First Node
$ Input: head = [4,5,1,9], node = 4
Output: [5,1,9]
💡 Note: Delete the first node by copying next node's value (5) to current node, then skipping the next node. Result: [5,1,9].
Example 3 — Two Node List
$ Input: head = [1,2], node = 1
Output: [2]
💡 Note: In a two-node list, deleting the first node leaves only the second node. We copy value 2 to the first node and remove the second.

Constraints

  • The number of nodes in the given linked list is in the range [2, 1000]
  • -1000 ≤ Node.val ≤ 1000
  • The value of each node in the linked list is unique
  • The node to be deleted is in the linked list and is not a tail node

Visualization

Tap to expand
Delete Node: Input → Process → OutputInput: Delete node 54519Target to deleteOutput: After deletion419Key Trick: Copy next value (1) to current node, then skip next node
Understanding the Visualization
1
Input
Linked list [4,5,1,9] and node with value 5 to delete
2
Process
Copy next node's value and skip next node
3
Output
List becomes [4,1,9] with value 5 removed
Key Takeaway
🎯 Key Insight: When you can't delete yourself, become the next person and delete them instead
Asked in
Adobe 15 Apple 12 Microsoft 18 Facebook 25
98.2K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen