Back to course home
0% completed
Vote For New Content
Solution: Problem Challenge 2: Rotate a LinkedList
Problem Statement
Given the head of a Singly LinkedList and a number ‘k’, rotate the LinkedList to the right by ‘k’ nodes.
Constraints:
- The number of nodes in the list is in the range
[0, 500]
. -100 <= Node.val <= 100
- 0 <= k <= 2 * 10^9
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:
- Connect the last node of the LinkedList to the head, because the list will have a different tail after the rotation.
- The new head of the LinkedList will be the node at the beginning of the sublist.
- 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:
Python3
Python3
. . . .
Time Complexity
The time complexity of our algorithm will be 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).
.....
.....
.....
Like the course? Get enrolled and start learning!
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible