Left Rotate Array by One

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

The problem

Given an integer array nums, rotate the array to the **left **by one.

Note: There is no need to return anything, just modify the given array.

Input: nums = [1, 2, 3, 4, 5] Output: [2, 3, 4, 5, 1] Explanation: Initially, nums = [1, 2, 3, 4, 5] Rotating once to left -> nums = [2, 3, 4, 5, 1]

Input: nums = [-1, 0, 3, 6] Output: [0, 3, 6, -1] Explanation: Initially, nums = [-1, 0, 3, 6] Rotating once to left -> nums = [0, 3, 6, -1]

Input: nums = [7, 6, 5, 4]

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

cpp

class Solution {
public:
    void rotateArrayByOne(vector<int>& nums) {

    }
};

java

class Solution {
    public void rotateArrayByOne(int[] nums) {
        
    }
}

python

class Solution:
    def rotateArrayByOne(self, nums):

javascript

class Solution {
    rotateArrayByOne(nums) {

    }
}

csharp

public class Solution
{
    public void rotateArrayByOne(List<int> nums)
    {

    }
}

go

func rotateArrayByOne(nums []int) {
	//your code goes here
}
Stuck? Show a way to structure it+
  1. 01Store the first element.
  2. 02Shift every later element one position left.
  3. 03Write the stored element into the final slot.
  4. 04Handle arrays of length zero or one safely.

Reference answer

Then expect these follow-ups

  • How would you rotate left by k places?

    Tests: generalization

  • How would you do the same for a linked list?

    Tests: pointer handling

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