LeetCode 189. Rotate Array

Post by ailswan Oct.17, 2023

189. Rotate Array

Problem Statement

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

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

Example:

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 Approach

Achieve the rotation by manipulating array slicing and concatenation.

Algorithm

  1. Modulo Operation: First, make k modulo the length of nums to handle cases where k is larger than the length of the array.
  2. Array Slicing: Slice the last k elements from nums array.
  3. Concatenation: Join the last k elements to the start of the remaining part of the array to achieve the rotation.

Implement

    class Solution:
  def rotate(self, nums: List[int], k: int) -> None:
      """
      Do not return anything, modify nums in-place instead.
      """
      k %= len(nums)
      nums[:] = nums[-k:] + nums[:-k]