Solution Review: Problem Challenge 2

Rotate a LinkedList (medium) #

Given the head of a Singly LinkedList and a number ‘k’, rotate the LinkedList to the right by ‘k’ nodes.

Created with Fabric.js 1.6.0-rc.1 Original List: head head k=3 1 2 3 4 5 6 null 4 5 6 1 2 3 null Rotated LinkedList: Example 1:
Created with Fabric.js 1.6.0-rc.1 Original List: head head Rotated LinkedList: 1 2 3 4 5 null Example 2: k=8 3 4 5 1 2 null

Solution #

Another way of defining the rotation is to take the sub-list of ‘k’ ending nodes of the LinkedList and connect them to the beginning. Other than that we have to do three more things:

  1. Connect the last node of the LinkedList to the head, because the list will have a different tail after the rotation.
  2. The new head of the LinkedList will be the node at the beginning of the sublist.
  3. The node right before the start of sub-list will be the new tail of the rotated LinkedList.

Code #

Here is what our algorithm will look like:

Output

0.729s

Nodes of original LinkedList are: 1 2 3 4 5 6 Nodes of rotated LinkedList are: 4 5 6 1 2 3

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 2
Next    →
Introduction