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 <= 1000See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI