TikTok OA Interview Problem Analysis: Rotate Array

15 Views
No Comments

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Example 1:

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

Explanation:

  • rotate 1 step to the right: [7,1,2,3,4,5,6]
  • rotate 2 steps to the right: [6,7,1,2,3,4,5]
  • rotate 3 steps to the right: [5,6,7,1,2,3,4]

This problem asks you to rotate an array to the right by k steps while preserving the relative order of elements. A standard solution is to first reduce k with modulo n, then either build the result by splitting and concatenating the array or perform the rotation in place with the reverse-three-times technique. For the sample [1,2,3,4,5,6,7] with k = 3, the result is [5,6,7,1,2,3,4].

END
 0