Left Rotate Array by K Places

Asked atOracleVisa
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an integer array nums and a non-negative integer k, rotate the array to the left by k steps.

Input: nums = [1, 2, 3, 4, 5, 6], k = 2 Output: nums = [3, 4, 5, 6, 1, 2] Explanation: rotate 1 step to the left: [2, 3, 4, 5, 6, 1] rotate 2 steps to the left: [3, 4, 5, 6, 1, 2]

Input: nums = [3, 4, 1, 5, 3, -5], k = 8 Output: nums = [1, 5, 3, -5, 3, 4] Explanation: rotate 1 step to the left: [4, 1, 5, 3, -5, 3] rotate 2 steps to the left: [1, 5, 3, -5, 3, 4] rotate 3 steps to the left: [5, 3, -5, 3, 4, 1] rotate 4 steps to the left: [3, -5, 3, 4, 1, 5] rotate 5 steps to the left: [-5, 3, 4, 1, 5, 3] rotate 6 steps to the left: [3, 4, 1, 5, 3, -5] rotate 7 steps to the left: [4, 1, 5, 3, -5, 3] rotate 8 steps to the left: [1, 5, 3, -5, 3, 4]

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

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • 0 <= k <= 105

cpp

class Solution {
public:
    void rotateArray(vector<int>& nums, int k) {

    }
};

java

class Solution {
    public void rotateArray(int[] nums, int k) {
        
    }
}

python

class Solution:
    def rotateArray(self, nums, k: int) -> None:

javascript

class Solution {
    rotateArray(nums, k) {

    }
}

csharp

public class Solution {
    public void rotateArray(List<int> nums, int k) {

    }
}

go

func rotateArray(nums []int, k int) {
    //your code goes here
}
Stuck? Show a way to structure it+
  1. 01Normalize k with `k %= n`.
  2. 02Reverse the first k elements.
  3. 03Reverse the remaining n-k elements.
  4. 04Reverse the entire array.

Reference answer

Then expect these follow-ups

  • How would you rotate right by k?

    Tests: transformation reasoning

  • How would you rotate a linked list?

    Tests: pointer manipulation

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question