1572. Drop Every Kth Link

Easy1.5 points estimatedLinked List

A ticket queue is stored as a singly linked list, and every k-th ticket in the queue is voided. Given head and an integer k, unlink every node whose 1-based position in the original list is a multiple of k, and return the head of the remaining list. Positions are counted in the original list, not in the shrinking one, so with k = 3 the nodes at positions 3, 6, 9 and so on are removed. When k = 1 every node is removed and the answer is an empty list (null). Do it in a single pass with a running position counter and without allocating new nodes. The list has 0 to 1000 nodes and 1 <= k <= 1000. Aim for O(n) time and O(1) extra space.

Example 1

Input:
head = [1,2,3,4,5,6], k = 2
Output:
[1,3,5]
Explanation:

Positions 2, 4 and 6 are removed, leaving 1,3,5.

Example 2

Input:
head = [1,2,3], k = 1
Output:
[]
Explanation:

With k = 1 every node is removed.

Example 3

Input:
head = [5,6,7], k = 5
Output:
[5,6,7]
Explanation:

No position is a multiple of 5, so the list is unchanged.

Constraints

0 ≤ length ≤ 1000

1 ≤ k ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…