oneby7

Linked Lists Singly linked list basics

270. Delete the K-th Node

Medium

You are given head, the first node of a singly linked list, and an integer k. Delete the k-th node of the list, counting from the head, and return the head of the list that is left.

Positions start at 1: the head is node 1, the node after it is node 2, and so on. So k = 1 deletes the head, and k equal to the number of nodes deletes the last node.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The output shows the list you return the same way. When no nodes are left, return null, which shows as [].

Example 1

head
12-530819
output
12-5819

Input: head = [12, -5, 30, 8, 19], k = 3

Output: [12,-5,8,19]

Explanation: Node 3 holds 30. After the deletion, the node holding -5 links straight to the node holding 8.

Example 2

4941
head
941
output

Input: head = [4, 9, 4, 1], k = 1

Output: [9,4,1]

Explanation: Node 1 is the head. Once it is deleted, the list starts at the node holding 9, and that node is the head to return.

Example 3

-7

Input: head = [-7], k = 1

Output: []

Explanation: The only node is deleted. No nodes are left, so the answer is null.

Check your understanding

Work out the answer for this input before you write any code.

head = [7, 3, 7, 2, 6], k = 4

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • 1 ≤ k ≤ number of nodes

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.