InferenceAI

Enter at least two characters to search.

Start free

Reverse in Groups of K

hardLinked Lists40 min50 XP

Reverse the nodes of the list k at a time. If the number of nodes left at the end is less than k, leave them as they are.

Linked lists are given and returned as Python lists of node values, from head to tail. Think in terms of nodes and pointers; the list format just makes the tests readable.

Requirements

  • With real nodes, use O(1)O(1) extra space by relinking pointers in place.

Examples

EXAMPLE WALKTHROUGHpairs

A guided view of the published example, not a trace of your code.

INPUT[[1,2,3,4,5],2]
TASKreverse_in_groups()
EXPECTED OUTPUT[2,1,4,3,5]

Start with the input values shown in this example.

Example 1 of 3

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

Output: [2,1,4,3,5]

Explanation: pairs

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

Output: [3,2,1,4,5]

Explanation: leftover

Input: values = [1], k = 1

Output: [1]

Explanation: single

Hint 1

Check that k nodes remain, reverse them, and connect the reversed block to the rest.

Topics

DSALinked ListsPython