Skip to the code
+50 XP

#241 Flip Every Batch of K

hard

An image gallery loads photos in batches of k and, for a "newest first" effect, shows each full batch in reverse order. The photos are a linked list.

Write flipBatches(head, k) that reverses the nodes of each group of k consecutive nodes, from the start of the list, and returns the head. If the last group has fewer than k nodes, leave it as it is. Relink the nodes; don't change their values. The gallery can hold 100,000 photos, so use O(1) extra space: no array of nodes, and no recursion, which keeps one call waiting for every batch.

Example 1

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

1, 2 and 3, 4 are flipped; 5 is a short batch and stays.

Example 2

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

1, 2, 3 is flipped; 4, 5 is a short batch.

Constraints

  • The list has 1 to 10^5 nodes.
  • 1 <= k <= the number of nodes
  • 0 <= node.val <= 1000

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).