Skip to content
DeepForgeby svx
All problems
EasyData Structuresds-041

Rotate Array by Reversal

Problem

Rotate an array to the right by k steps using only reversal operations.

k may be larger than the array length, so reduce it modulo n first. The standard trick is to reverse the whole array, then reverse the first k elements, then reverse the remaining n-k elements.

Return a new rotated list.

Hint

Reversing the whole array then the two pieces turns a rotation into three reversals.

Test cases

case 1
in: [[1,2,3,4,5,6,7],3]
expected: [5,6,7,1,2,3,4]
case 2
in: [[1,2],0]
expected: [1,2]
case 3
in: [[],5]
expected: []
case 4
in: [[-1,-100,3,99],2]
expected: [3,99,-1,-100]
case 5
in: [[1,2,3],5]
expected: [2,3,1]
Starter codePython
def rotate_by_reversal(nums, k):
    # Your code here
    pass

5 test cases · run your code against them in the editor