Solution Review: Problem Challenge 1

Reverse alternating K-element Sub-list (medium) #

Given the head of a LinkedList and a number ā€˜k’, reverse every alternating ā€˜k’ sized sub-list starting from the head.

If, in the end, you are left with a sub-list with less than ā€˜k’ elements, reverse it too.

Created with Fabric.js 1.6.0-rc.1 Original List: Example: head head 1 2 3 4 5 6 7 8 null Reversed Sub-list: k=2 2 1 3 4 6 5 7 8 null

Solution #

The problem follows the In-place Reversal of a LinkedList pattern and is quite similar to Reverse every K-element Sub-list. The only difference is that we have to skip ā€˜k’ alternating elements. We can follow a similar approach, and in each iteration after reversing ā€˜k’ elements, we will skip the next ā€˜k’ elements.

Code #

Most of the code is the same as Reverse every K-element Sub-list; only the highlighted lines have a majority of the changes:

Output

0.494s

Nodes of original LinkedList are: 1 2 3 4 5 6 7 8 Nodes of reversed LinkedList are: 2 1 3 4 6 5 7 8

Time complexity #

The time complexity of our algorithm will be O(N)O(N) where ā€˜N’ is the total number of nodes in the LinkedList.

Space complexity #

We only used constant space, therefore, the space complexity of our algorithm is O(1)O(1).

Mark as Completed
←    Back
Problem Challenge 1
Next    →
Problem Challenge 2