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. Use O(1) extra space.
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.
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.
1 to 5000 nodes.1 <= k <= the number of nodes0 <= node.val <= 1000Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.
Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #241 Flip Every Batch of K. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.