Skip to interview prep
Apexed
Problem list117 / 125

117. Reverse Nodes in Groups of K

HardLinked lists

Reverse the nodes of a linked list k at a time and return the new head. If the number of nodes left at the end is smaller than k, leave those nodes in their original order.

Change the links between nodes rather than only swapping values.

A linked list is passed as ListNode objects with val and next. The tests write lists as arrays.

Example 1

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

Example 2

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

Constraints

  • 0 ≤ nodes ≤ 5000
  • 1 ≤ k ≤ 5000

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 5 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Reverse Nodes in Groups of K — coding interview practice — Apexed