Skip to problem
←

Delete a Node Without the Head

Easy 0 attempts

Given only a reference to a non-tail node of a singly linked list, remove its position from the list’s value sequence. You cannot access the head or the preceding node.

The resulting list must have one fewer node and preserve the order of all remaining values. Node values may be overwritten; you are not required to detach the exact object passed to the function.

For 4 → 5 → 1 → 9, selecting the node at index 1 must leave 4 → 1 → 9.

Function contract

The fixture supplies a value array and zero-based nodeIndex. Your function receives only that non-tail node, with val and next properties—not the head or index.

Output: Modify the list in place so its value sequence omits the selected position. The runner checks the original list; return values are ignored.

Example 1

Input
head = [4,5,1,9]
nodeIndex = 1
Output
[4,1,9]

Example 2

Input
head = [1,2]
nodeIndex = 0
Output
[2]
Constraints
  • 2 <= number of nodes <= 1000
  • -1000 <= Node.val <= 1000
  • The given node is not the tail
Topics

Approach: Copy and Skip

Since we cannot access the previous node, we copy the value of the next node into the current node, then point the current node's next pointer to skip the next node. The original node object remains, holding its successor’s value; the successor object is detached. This removes the requested position from the value sequence.

javascript
function deleteNode(node) {
  node.val = node.next.val;
  node.next = node.next.next;
}

Time Complexity: O(1)

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript