CodingNodes / Linked List / Reverse Nodes In K Group System design Space play · ←→ step · R restart

Problem

You get the head of a linked list and a number k.

Cut the list into consecutive groups of exactly k nodes, starting from the head, and reverse the nodes inside each group. If the nodes at the end do not make a full group of k, leave them as they are. Re-link the existing nodes (do not just swap values) and return the head of the result.

Constraints

  • 0 ≤ number of nodes ≤ 5000
  • 1 ≤ k ≤ 5000 (k can be larger than the list)
  • 0 ≤ Node.val ≤ 1000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: kth walks over every node once to check each group, and reversing a group touches each of its nodes once. Together that is a small constant number of passes.

Space: Only a dummy node and a handful of pointers are used. The nodes are re-linked in place.

Keep a pointer, before, to the node just ahead of the next group. Walk a second pointer k nodes ahead to find the group's last node. If it runs off the list, stop. Otherwise reverse the group with the usual prev/cur loop, but start prev at the node after the group so the last arrow lands on it. Then point before at the group's new first node, and continue from the group's old first node.