<AI/>
enru
Все статьи

Rotate array

LeetCode 189: Rotate an array to the right by k steps in place using three reversals.

Сложность
Средняя
Опубликовано
Темы
#array#two pointers
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given an integer array nums. Rotate the array to the right by k steps, where k is non-negative.

Constraints

  • The array contains from 1 to 105 elements
  • Values are in the range from -231 to 231 - 1
  • k is in the range from 0 to 105

Examples

Input

nums = [1, 2, 3, 4, 5, 6, 7]
k = 3

Answer: [5, 6, 7, 1, 2, 3, 4]

  1. Rotate 1 step to the right: [7,1,2,3,4,5,6].
  2. Rotate 1 step to the right: [6,7,1,2,3,4,5].
  3. Rotate 1 step to the right: [5,6,7,1,2,3,4].

Solution

To solve the problem optimally, let's simplify the statement a bit. Rotating the array by 1 means shifting all its elements one position to the right. Therefore, if k equals the array length or is a multiple of it, after all the shifts every element makes a full "lap" and returns to its original position. This means we can drop the repeated "laps" and keep only the last one.

To do that, we take the remainder of dividing k by the array length and get the number count. That's exactly how many positions all elements need to be shifted to the right.

We can simplify the algorithm even further. If you look closely, you'll notice that only three operations are needed to get the result:

  • reverse the whole array
  • reverse the first k elements
  • reverse the remaining elements

Example

nums = [1,2,3,4,5,6,7], k = 3

Reverse the whole array.

[7,6,5,4,3,2,1]

Reverse the first 3 elements.

[5,6,7,4,3,2,1]

Reverse the remaining elements.

[5,6,7,1,2,3,4]
typescript
export const reverse = (nums: number[], left: number, right: number): void => {
  while (left < right) {
    const tmp = nums[left];
    nums[left] = nums[right];
    nums[right] = tmp;
    left++;
    right--;
  }
};
 
export const rotate = (nums: number[], k: number): void => {
  const length = nums.length;
  if (length < 2) {
    return;
  }
 
  const count = k % length;
 
  reverse(nums, 0, length - 1);
  reverse(nums, 0, count - 1);
  reverse(nums, count, length - 1);
};

Complexity Analysis

n is the number of elements in the array.

Time Complexity

The time complexity consists of several parts:

  • O(n/2): reversing the whole array
  • O(k/2): reversing the first subarray, where k < n
  • O(m/2): reversing the second subarray, where m < n

Since m + k = n, the total complexity is O(n).

Space Complexity

The space complexity is O(1), since all changes are made in place.