
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)
Editorial
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. |
Solution Hints
- Use modulo arithmetic to handle large values of k
- Slice and concatenate: return nums[-k:] + nums[:-k]