Skip to content

Latest commit

 

History

History
48 lines (32 loc) · 711 Bytes

File metadata and controls

48 lines (32 loc) · 711 Bytes

Rotate Array

Problem Link

https://leetcode.com/problems/rotate-array/


Pattern

  • Array manipulation
  • Reverse

Approach

Rotate by reversing parts: reverse whole array, then reverse first k and last n-k segments (or use juggling algorithm).


Time Complexity

O(n)

Space Complexity

O(1)


Java Solution

class Solution {
    private void reverse(int[] a, int l, int r) {
        while (l < r) {
            int t = a[l]; a[l++] = a[r]; a[r--] = t;
        }
    }
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }
}