Tutorialspoint
Problem
Solution
Submissions

Rotate a linked list to the right by k places

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to implement the RotateRight function, which rotates a linked list to the right by k places. The function should take the head of a linked list and an integer k, and return the head of the rotated list.

Example 1
  • Input: head = [1,2,3,4,5], k = 2
  • Output: [4,5,1,2,3]
  • Explanation:
    • Original list: 1 -> 2 -> 3 -> 4 -> 5
    • After rotation by 2 places: 4 -> 5 -> 1 -> 2 -> 3
Example 2
  • Input: head = [0,1,2], k = 4
  • Output: [2,0,1]
  • Explanation:
    • Original list: 0 -> 1 -> 2
    • After rotation by 4 places (which is equivalent to rotating by 1 place as 4 % 3 = 1): 2 -> 0 -> 1
Constraints
  • The number of nodes in the list is in the range [0, 500]
  • -100 ≤ Node.val ≤ 100
  • 0 ≤ k ≤ 2 * 10^9
  • Time Complexity: O(n) where n is the number of nodes in the list
  • Space Complexity: O(1)
Linked ListTech MahindraApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Handle edge cases: empty list, single node, or k = 0
  • Calculate the actual rotation needed (k % length of list)
  • Connect the list into a ring
  • Break the ring at the appropriate place
  • Find the new head and tail nodes

Steps to solve by this approach:

 Step 1: Handle edge cases (empty list, single node, or k = 0)
 Step 2: Calculate the length of the linked list by traversing it
 Step 3: Calculate the effective rotation (k % length) to avoid unnecessary rotations
 Step 4: If effective rotation is 0, return the original list
 Step 5: Connect the last node to the head to form a cycle
 Step 6: Find the new tail node which is (length - k - 1) nodes from the head
 Step 7: Set the node after the new tail as the new head and break the cycle

Submitted Code :