Tutorialspoint
Problem
Solution
Submissions

Rotate Elements in a List to the Right by K Positions

Certification: Basic Level Accuracy: 56.25% Submissions: 64 Points: 10

Write a Python program that rotates the elements of a list to the right by K positions.

Example 1
  • Input: nums = [1, 2, 3, 4, 5], k = 2
  • Output: [4, 5, 1, 2, 3]
  • Explanation:
    • Step 1: Original list: [1, 2, 3, 4, 5].
    • Step 2: Rotate right by 1 position: [5, 1, 2, 3, 4].
    • Step 3: Rotate right by 1 more position: [4, 5, 1, 2, 3].
    • Step 4: Total rotations: 2, so the final result is [4, 5, 1, 2, 3].
Example 2
  • Input: nums = [7, 8, 9], k = 4
  • Output: [9, 7, 8]
  • Explanation:
    • Step 1: Original list: [7, 8, 9].
    • Step 2: Since k = 4 and the length of the list is 3, we need to rotate by k % len(nums) = 4 % 3 = 1 positions.
    • Step 3: Rotate right by 1 position: [9, 7, 8].
    • Step 4: Final result: [9, 7, 8].
Constraints
  • 0 ≤ len(list) ≤ 10^5
  • 0 ≤ k ≤ 10^9
  • Time Complexity: O(n)
  • Space Complexity: O(n)
NumberListDeloitteAdobe
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

  • Use modulo arithmetic to handle large values of k
  • Slice and concatenate: return nums[-k:] + nums[:-k]

Steps to solve by this approach:

 Step 1: Handle edge cases - empty list returns empty list.

 Step 2: Normalize the rotation value k by taking modulo with the list length.
 Step 3: Check if rotation is needed (k = 0 means no rotation).
 Step 4: Split the list into two parts: elements to be rotated and elements to stay.
 Step 5: Concatenate the parts in the new order: rotated elements first, then remaining elements.
 Step 6: Return the rotated list.

Submitted Code :