DevPath

← All problems

Rotate Array Right

Medium arrays

Description

Return the array rotated right by k steps.

Constraints

0 <= n <= 100000; 0 <= k

Examples

Input: nums = [1,2,3,4,5,6,7], k = 3

Output: [5,6,7,1,2,3,4]

Hints (1)
  • Reduce k modulo n; the last k elements move to the front.

Solutions

Split at n-k and swap the halves. · Time O(n) · Space O(n)

func rotateRight(nums []int, k int) []int {
    n := len(nums)
    if n == 0 {
        return []int{}
    }
    k %= n
    out := make([]int, 0, n)
    out = append(out, nums[n-k:]...)
    out = append(out, nums[:n-k]...)
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account