oneby7

Arrays and Hashing Array basics

56. Rotate Array

Medium

You are given an array of integers nums and a whole number k. Rotate the array to the right by k steps and return it.

One step moves every element one position to the right, and the last element wraps around to the front. So after one step, [1, 2, 3, 4] becomes [4, 1, 2, 3].

Do it in place: change nums itself and use only O(1) extra memory.

Example 1

Input: nums = [3, 8, -1, 6, 2, 9], k = 2

Output: [2,9,3,8,-1,6]

Explanation: The last two elements, 2 and 9, wrap around to the front and keep their order. The other four move two places to the right.

Example 2

Input: nums = [5, -7, 0, 4], k = 10

Output: [0,4,5,-7]

Explanation: Four steps bring a four-element array back to where it started, so ten steps end in the same place as two steps.

Example 3

Input: nums = [1000000000, -1000000000, 7], k = 3

Output: [1000000000,-1000000000,7]

Explanation: Three steps move every element of a three-element array all the way round, back to its start.

Check your understanding

Work out the answer for this input before you write any code.

nums = [1, 2, 3, 4, 5], k = 2

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.