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

Hiring now

Visa has 638 open roles right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Software Engineer Intern

    GB - London, United Kingdom

  • Sr. Software Engineer (3+ yrs, DevOps, Cloud, Coding, Infra)

    IN - Bengaluru, India

  • Sr Software Engineer (3-5 yrs of exp - Full stack development, Java, React, Gen AI)

    IN - Bengaluru, India

Or practice this question first

Next question