HardLinked ListRecursion

1 approach, code in every language

Problem description

Given the head of a singly linked list and an integer k, reverse the nodes of the list k at a time and return the modified head. Process the list in fixed-size blocks: reverse the first k nodes, then the next k, and so on.

If the number of nodes left at the end is smaller than k, leave that final group in its original order. You may only rearrange the node connections; node values must stay in place.

Example 1

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

Output: [2,1,4,3,5]

The first pair and the second pair are each reversed, and the leftover node 5 stays put.

Example 2

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

Output: [3,2,1,4,5]

The first three nodes are reversed while the remaining two, being fewer than k, keep their order.

Constraints

  • The number of nodes is n, and 1 <= k <= n <= 5000.
  • 0 <= Node.val <= 1000

After the pattern

Now solve one you haven't seen.

Shunting Wagon Blocks is our own problem on the technique behind Reverse Nodes in k-Group: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free