Skip to the solution
HardDSAAsked in 20246 min read

Rotate array N times

885 views

The problem

Problem, as an interviewer would state it: "Rotate an array to the right by k positions. Discuss edge cases (negative k, k larger than the length), runtime, and how to do it in place."

Examples:

Code
rotate([1, 2, 3, 4, 5, 6, 7], 3); // [5, 6, 7, 1, 2, 3, 4]
rotate([1, 2, 3, 4, 5], -2);      // [3, 4, 5, 1, 2]  (a negative k rotates left)

Clarifying questions expected:

  • Rotate right or left, and how should a negative k or a k larger than the length behave?
  • May I return a new array, or must the rotation happen in place with O(1) extra space?
  • What about an empty array?

Code / implementation expected: Yes — real, direct proof against an independent reference, and a measurement of why "rotate one step, k times" is the wrong approach.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: slice and in-place three-reversal rotations agree with an index-mapping reference for negative and oversized k, and one-step rotation grows with k

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 144 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Implement a Virtualized List That Renders Only Visible Rows

Continue