Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Rotate an Array

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Rotate an Array. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

North Carolina 511 periodically reorders route updates so the most recent entries appear first. Implement a function that rotates an integer array to the right by k positions in place and returns the same array.

A right rotation moves each element k positions toward the end. Elements that pass the last index wrap around to the beginning. Aim for linear time and constant extra space.

Formal Specification

  • Input: nums, a mutable list of integers, and k, a nonnegative integer.
  • Output: The rotated list, with nums modified in place.
  • If k is larger than the array length, treat it modulo the array length.

Constraints

  • 1 <= len(nums) <= 10^5
  • 0 <= k <= 10^9
  • -10^9 <= nums[i] <= 10^9
  • The rotation must be performed in place
  • Use O(1) additional space

Function Signature

def rotate(nums, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output