FrontendInterviews.dev

Loading problem…

33. Rotate Array - Circular Shift

Medium•
Acceptance: 77.78%
•
🔓3/3 Pro unlocks today

You're building a carousel or image slider component that needs to rotate items. Given an array, you need to rotate it to the right by k steps.

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Requirements

1. Basic Functionality

  • Rotate array to the right by k positions
  • Modify array in-place (O(1) extra space)
  • Handle k larger than array length
  • Handle edge cases (empty array, k=0, k=array.length)

Example Usage

// Example 1
let nums = [1,2,3,4,5,6,7];
rotate(nums, 3);
// nums becomes [5,6,7,1,2,3,4]
// Rotated right by 3: [1,2,3,4,5,6,7] → [5,6,7,1,2,3,4]

// Example 2
let nums = [-1,-100,3,99];
rotate(nums, 2);
// nums becomes [3,99,-1,-100]

Real-World Context

This problem models real frontend scenarios:

  • Carousel rotation: Rotate items in image carousel
  • Circular buffer: Implement circular data structures
  • Array manipulation: Common in data transformation
  • UI animations: Rotate elements in circular fashion

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • 0 <= k <= 10^5
  • Must modify array in-place with O(1) extra space