Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Programming Challenge: Rotate Array

5. Array Rotation

Problem Statement: Given an array, rotate it to the right by k steps where k is non-negative.

Function Signature:

public void rotate(int[] nums, int k);

Examples:

  • Input: nums = [1,2,3,4,5,6,7], k = 3
    Output: [5,6,7,1,2,3,4]
  • Input: nums = [-1,-100,3,99], k = 2
    Output: [3,99,-1,-100]

Solution Code

public class ArrayRotator {
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }
    
    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}

Complexity Analysis

Approach Time Complexity Space Complexity
Reverse Method O(n) O(1)