Rotate Array by K

MediumArrays & Hashingreversal

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums and a non-negative integer k, rotate the array to the **right** by k positions. A right rotation by one step moves the last element of the array to the front, shifting every other element one slot to the right. Rotating by k steps repeats this operation k times. Return the rotated array. Note that k may be larger than the length of nums, in which case the rotation simply wraps around (rotating an array of length n by n steps yields the original array). For example, rotating [1, 2, 3, 4, 5] by 2 steps produces [4, 5, 1, 2, 3]: the trailing 2 elements [4, 5] move to the front while the rest follow. A common follow-up is to perform the rotation **in place** using O(1) extra space via the three-reversal trick, but returning a correct new array is sufficient here.

Examples

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
The last 3 elements [5,6,7] move to the front; the remaining [1,2,3,4] follow.
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
The last 2 elements [3,99] wrap to the front.
Input: nums = [1,2,3], k = 4
Output: [3,1,2]
k = 4 on length 3 is equivalent to rotating by 4 % 3 = 1 step.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.