DSA · Linked List · #151
Reverse Nodes in k-Group
Module 42 · difficulty 4/5·⏱ 30:00starts on first keystroke
Given the `head` of a singly linked list, reverse the nodes of the list `k` at a time and return the modified list's head. `k` is a positive integer and is at most the length of the list. If the number of nodes is not a multiple of `k`, the leftover nodes at the end should remain in their original order. You may not alter the values in the list's nodes — only the node links themselves may be changed. Implement `reverseKGroup(head, k)`, where `head` is the first node `{ val, next }` (or `null`) and `k` is an integer. Return the head of the resulting list.
Examples
head = [1,2,3,4,5], k = 2→[2,1,4,3,5]— First two nodes and next two nodes are each reversed; the final node stays put.head = [1,2,3,4,5], k = 3→[3,2,1,4,5]— The first group of 3 is reversed; the remaining 2 nodes are fewer than k so stay as-is.head = [1,2,3,4,5], k = 1→[1,2,3,4,5]— k = 1 leaves the list unchanged.
Constraints
- · The number of nodes in the list is n.
- · 1 <= k <= n <= 5000
- · 0 <= Node.val <= 1000
- · Try to solve it in O(1) extra memory.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.