Left Rotate Array by K Places
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+
- 01Normalize k with `k %= n`.
- 02Reverse the first k elements.
- 03Reverse the remaining n-k elements.
- 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 602 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Sr. Director - Software Engineering (Java, GenAI, Payment Risk, Cloud, NoSQL - 18+ years' exp)
IN - Bengaluru, India
Staff Software Engineer
US - Austin, TX
Analyst, Technical Service Experience
PH - Pasay, Philippines - Manila
Next question