Introduction
Rotate List means shifting linked list nodes towards the right by k positions.
The task is to:
- move last nodes to front
- maintain linked structure
- rotate efficiently
Example:
Input:
1 -> 2 -> 3 -> 4 -> 5
k = 2
Output:4 -> 5 -> 1 -> 2 -> 3
Explanation:
Last 2 nodes:4 -> 5
Move to front.
Updated list:
4 -> 5 -> 1 -> 2 -> 3
This problem is one of the most important applications of:
Circular Linked List TechniqueConstraints
0 <= Number of Nodes <= 10^5
0 <= k <= 10^9
Approach 1 : Brute Force (Rotate One by One)
Explanations:
Explanation:
The idea is:
- move last node to front
- repeat process k times
Steps:
- Find last node.
- Move it to front.
- Repeat k times.
This approach works but:
- becomes slow for large k
So optimized rotation is preferred.
Dry Run
Input:1 -> 2 -> 3 -> 4 -> 5
k = 2
First rotation:
5 -> 1 -> 2 -> 3 -> 4
Second rotation:
4 -> 5 -> 1 -> 2 -> 3
Practice :
Complexity Analysis :
Time Complexity:- O(n × k)Explanation :
List traversal is repeated k times.
Space Complexity:- O(1)
Explanation :
No extra space is used.
Approach 2 : Optimal Solution(Using Circular Linked List)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- connect tail to head
- create circular list
- break list at correct position
This avoids repeated rotations.
Dry Run
Input:1 -> 2 -> 3 -> 4 -> 5
k = 2
Length:
5
New head:
4
Break circle:
after node 3
Output:
4 -> 5 -> 1 -> 2 -> 3
Practice :