Reverse a List in Blocks
A singly linked list is given as an array values, head first. Cut it into consecutive blocks of exactly k nodes starting from the head and reverse the order of nodes inside each block. If the last block has fewer than k nodes, leave it as it is.
Return the resulting list as an array. On real nodes the challenge is to do this with constant extra memory by relinking pointers block by block; think about how the tail of one reversed block connects to the head of the next.
Example 1
Input: values = [1,2,3,4,5], k = 2 Output: [2,1,4,3,5] Explanation: Blocks [1,2] and [3,4] are reversed; 5 is a short block and stays.
Example 2
Input: values = [1,2,3,4,5], k = 3 Output: [3,2,1,4,5] Explanation: Only one full block of 3 fits.
Constraints
- 0 <= values.length <= 3 * 10^4
- 1 <= k <= 3 * 10^4
- -1000 <= values[i] <= 1000
Hint 1
Before reversing a block, check that k nodes remain.
Hint 2
Reverse the block in place, then link the previous block's tail to the new block head; the old block head becomes the new tail.
Discussion 0
Join free to post in the discussion.
Good practice for: Backend Developer, Full Stack Developer, Embedded Systems Engineer, Game Developer, Automation Test Engineer
Run checks your code on 3 sample tests. Submit runs all 9 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.