FunctionRacerProblemsRace

Keep Every Kth Node

EasyLinked listsPython, JavaScript, TypeScript, Java, C++

Count the nodes starting from 1 at the head. Keep only the nodes whose position is a multiple of k (positions k, 2k, 3k, ...), drop all the others, and return the new head. The list is passed in as head.

Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.

Example 1

head [10,20,30,40,50]
k 2
returns [20,40]

Positions 2 and 4 hold 20 and 40.

Example 2

head [5,6,7]
k 1
returns [5,6,7]

Every position is a multiple of 1.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Linked lists problems