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 in a Linked List INPUT Original Linked List: 4 5 DELETE 1 9 NULL Input Values: head = [4, 5, 1, 9] node = 5 Constraint: No access to head pointer! Only given node to delete. node points to value 5 node.next points to value 1 ALGORITHM STEPS 1 Get Next Node Access node.next (value 1) 5 1 2 Copy Value node.val = node.next.val 1 copied! 1 3 Skip Next Node node.next = node.next.next 1 1 9 4 Done! Original next node orphaned node.val = node.next.val; node.next = node.next.next; // O(1) time, O(1) space FINAL RESULT Modified Linked List: 4 1 9 NULL Output: [4, 1, 9] OK - Node Deleted! Value 5 removed from list Complexity: Time: O(1) Space: O(1) Key Insight: Since we cannot access previous nodes, we use a clever trick: instead of actually deleting the node, we copy the next node's value into current node, then skip over the next node. This effectively "deletes" our node by making it become its successor. Works because node is guaranteed not to be last! TutorialsPoint - Delete Node in a Linked List | Copy Next Node's Value (Clever Trick)
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