FunctionRacerProblemsRace

Last One Standing

MediumLinked listsPython, JavaScript, TypeScript, Java, C++

Imagine the nodes sit in a circle in list order. Starting the count at the head (the head is 1), remove every k-th node and keep counting from the node after it, wrapping around. Return the value of the last node left. For [1,2,3,4,5] and k = 2 the nodes leave in the order 2, 4, 1, 5, so the answer is 3. 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 [1,2,3,4,5]
k 2
returns 3

Removed: 2, 4, 1, 5. Left: 3.

Example 2

head [10,20,30]
k 1
returns 30

Removing every node in turn leaves the last one.

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