You are given the head of a singly linked list and a whole number k. Cut the list into groups of k nodes, starting from the head, and reverse the order of the nodes inside each full group. Return the head of the new list.
If the last group has fewer than k nodes, leave it exactly as it is. Change the links between nodes, not the values stored in them.
Example 1
Input: head = [4, 8, 1, 6, 3], k = 2 Output: [8, 4, 6, 1, 3] Why: groups 4,8 and 1,6 flip; 3 is alone and stays
2 more examples and the constraints
Example 2
Input: head = [4, 8, 1, 6, 3], k = 3 Output: [1, 8, 4, 6, 3] Why: 4,8,1 flips; only two nodes are left, so 6,3 stay
Example 3
Input: head = [9], k = 1 Output: [9] Why: a group of one reversed is itself
Constraints
- 1 ≤ k ≤ number of nodes ≤ 5,000
- 0 ≤ value of each node ≤ 1,000
- Follow-up: use only O(1) extra memory
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Stack per groupO(n)
- Reverse in placeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 5,000 nodes | Verdict |
|---|---|---|---|
| Stack per group | O(n), O(k) space | Passes; uses extra memory | |
| Reverse in place | O(n), O(1) space | Best; meets the follow-up |
n = nodes in the list, k = group size.
Edge cases to test
- k = 1. Every group is one node, so the list comes back unchanged.
- k equals the length. The whole list is one group and is fully reversed.
- Short last group. [10, 20, 30, 40, 50] with k = 3 keeps 40, 50 in their order.
- Length is a multiple of k. No leftover; the last group's tail must end with null.
Common mistakes
- Reversing the short last group too. It must stay as it is.
- Losing the link from the previous group, so the list ends after the first group.
- Swapping node values instead of relinking the nodes.
How to talk through it
- 1Clarify. What happens to a short last group? May I change values, or only links? Is k always at most the length?
- 2Give the simple version. Push each group onto a stack and pop it back; say it costs O(k) memory.
- 3Name the pointers. group_prev, kth and group_next fix the boundaries before any arrow moves.
- 4Code the in-place flip. Count k ahead, flip with prev starting at group_next, then stitch and advance.
- 5Test out loud. Run k = 1, k equal to the length, and a short leftover group.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?