Problem 252412 · easy · Phase 02 Linear Data Structures

Rotate Right by K Steps

arrays · slicing · modular arithmetic

Given a list nums and a non-negative integer k, return a new list equal to nums rotated to the right by k steps: every element moves k positions to the right and elements that fall off the end re-enter at the front.

k may be larger than the length of the list.

Examples

Input:  nums = [1, 2, 3, 4, 5], k = 2
Output: [4, 5, 1, 2, 3]
Explanation: two right steps: [1,2,3,4,5] -> [5,1,2,3,4] -> [4,5,1,2,3].

Input:  nums = [1, 2, 3], k = 4
Output: [3, 1, 2]
Explanation: rotating 4 times is the same as rotating once.

Constraints

  • 0 <= len(nums) <= 10**5
  • 0 <= k <= 10**9
  • Return a new list; do not modify nums.
  • Target: O(n) time.

Goals

  • Reduce a rotation count with the modulo operator
  • Build a rotated copy from two slices
  • Handle the empty list and k = 0 without special-case bugs
Starting Python…