Ctrl K

Keep Some, Skip Some

Easy
You are given a singly linked list head and two integers keep and skip. Walk the list from the start and thin it out: the first keep nodes stay, the next skip nodes are removed, then another keep nodes stay, another skip are removed, and so on until the list runs out. If the last stretch is shorter than needed, just take whatever is left. Return the head of the resulting list. Try to do it without building a new list, by relinking the original one.
Example 1
head=list_node([4, 8, 15, 16, 23, 42, 7, 9]), keep=3, skip=2 → [4, 8, 15, 42, 7, 9]

Keep 4, 8, 15, drop 16 and 23, keep 42, 7, 9, and the list ends there.

Example 2
head=list_node([5, 6, 7, 8, 9, 10, 11]), keep=1, skip=1 → [5, 7, 9, 11]

Every second node goes away, leaving 5, 7, 9, 11.

Example 3
head=list_node([3, 1, 2]), keep=4, skip=10 → [3, 1, 2]

There are fewer nodes than keep, so nothing is removed.

Constraints
  • The list has between 1 and 10⁴ nodes
  • 1 ≤ Node.val ≤ 10⁶
  • 1 ≤ keep, skip ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsZip Two Sorted Chains EasyThin Out a Sorted Chain EasyCut Out Matching Nodes EasyFlip the Chain EasySymmetric Bead String Easy
loading Python…
Input
head=list_node([4, 8, 15, 16, 23, 42, 7, 9]), keep=3, skip=2
Expected
[4, 8, 15, 42, 7, 9]

Run checks the first 3 tests in your browser. Submit checks all 100 tests on the server, hidden ones included.