Tutorialspoint
Problem
Solution
Submissions

Rotate Array by K Steps

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to rotate an array to the right by k steps. Each element should move k positions to the right, with elements at the end wrapping around to the beginning.

Example 1
  • Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3
  • Output: [5, 6, 7, 1, 2, 3, 4]
  • Explanation:
    • Original array is [1, 2, 3, 4, 5, 6, 7] and k = 3.
    • After 1 rotation: [7, 1, 2, 3, 4, 5, 6].
    • After 2 rotations: [6, 7, 1, 2, 3, 4, 5].
    • After 3 rotations: [5, 6, 7, 1, 2, 3, 4].
Example 2
  • Input: nums = [-1, -100, 3, 99], k = 2
  • Output: [3, 99, -1, -100]
  • Explanation:
    • Original array is [-1, -100, 3, 99] and k = 2.
    • After 1 rotation: [99, -1, -100, 3].
    • After 2 rotations: [3, 99, -1, -100].
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • -2^31 ≤ nums[i] ≤ 2^31 - 1
  • 0 ≤ k ≤ 10^5
  • Time Complexity: O(n)
  • Space Complexity: O(1) for in-place solution
ArraysDeloitteLTIMindtree
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the reverse technique to rotate the array efficiently
  • First, reverse the entire array
  • Then reverse the first k elements
  • Finally, reverse the remaining elements from k to end
  • Handle the case where k is greater than array length using modulo operation
  • This approach works in-place without using extra space

Steps to solve by this approach:

 Step 1: Calculate k modulo array length to handle cases where k is greater than array size.
 Step 2: Reverse the entire array from index 0 to n-1.
 Step 3: Reverse the first k elements from index 0 to k-1.
 Step 4: Reverse the remaining elements from index k to n-1.
 Step 5: The array is now rotated by k positions to the right.
 Step 6: Use a helper reverse function that swaps elements using two pointers approach.
 Step 7: This approach modifies the array in-place without using extra space.

Submitted Code :