CodeArchon

hardLinked ListFacebookMicrosoftAmazon

K-Fold Chain Reversal

A conveyor-belt sorter reverses parcels in fixed-size windows of k; any trailing partial window is left alone.

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list. Nodes that don't form a full group of k remain as-is.

Choose approach

1
head
2
3
4
5
nil
1/4
Narrationstep 1 of 4

Reverse in groups of 2.

1def reverseKGroup(head, k):
2 dummy = ListNode(0, head)
3 groupPrev = dummy
4 while True:
5 kth = groupPrev
6 for _ in range(k):
7 kth = kth.next
8 if not kth: break
9 if not kth: break
10 groupNext = kth.next
11 prev, curr = groupNext, groupPrev.next
12 while curr != groupNext:
13 curr.next, prev, curr = prev, curr, curr.next
14 tmp = groupPrev.next
15 groupPrev.next = kth
16 groupPrev = tmp
17 return dummy.next
Variables
k=2
head=1

How to think about it

  1. Dummy sentinel removes the special-case for the first group.
  2. After each full group, the new tail becomes the next groupPrev.
  3. Partial trailing group is left untouched by exiting on the kth-probe check.

Edge cases to catch in interview

  • k = 1 → list unchanged.
  • k = n → full reverse.
  • Partial last group of length < k is left as-is.

Examples

Example 1[2,1,4,3,5]
{"values":[1,2,3,4,5],"k":2}
Example 2[3,2,1,4,5]
{"values":[1,2,3,4,5],"k":3}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed