↓Skip to main content
  1. LeetCode/

LeetCode 189: Rotate Array

·2 mins· ·
LeetCode Medium Array Math Two-Pointers
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-11

  • Submissions: Wrong Answer ×3 → Accepted → Wrong Answer → Accepted

Approach
#

Rotating right by k moves the last k elements to the front. k may exceed the length, so take k %= n first. Without extra space, reverse three times (Two Pointers Template 1):

  1. Reverse everything: the last k come first, reversed.
  2. Reverse the first k back.
  3. Reverse the last n - k back.

My Attempts
#

The early slicing versions did not reduce k: when k exceeded the length the slices were wrong, so [7, 8] with k = 7 stayed [7, 8] instead of [8, 7]; one computed n % k, dividing by zero when k = 0.

Solution
#

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        def rev(l, r):
            while l < r:
                nums[l], nums[r] = nums[r], nums[l]
                l, r = l + 1, r - 1
        n = len(nums)
        k %= n
        rev(0, n - 1)
        rev(0, k - 1)
        rev(k, n - 1)

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Reduce k modulo the length first.
  • With slices, nums[-k:] is the whole array when k = 0.

Interview Explanation
#

I reduce k modulo the length, then reverse the whole array, the first k, and the rest, which rotates it right. Time O(n), extra space O(1).

Related

LeetCode 204: Count Primes
·2 mins
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 note: the sieve of Eratosthenes, crossing out multiples of each prime p starting at p², with the outer loop only up to √n
LeetCode 48: Rotate Image
·2 mins
LeetCode Medium Array Math Matrix
LeetCode 48 note: rotating 90 degrees clockwise is a transpose followed by reversing each row, both in place
LeetCode 287: Find the Duplicate Number
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search Bit-Manipulation
LeetCode 287 note: treat i -> nums[i] as a linked list; the duplicate is the cycle entry, found with Floyd’s algorithm in O(1) space without modifying the array
LeetCode 973: K Closest Points to Origin
·1 min
LeetCode Medium Array Math Divide-and-Conquer Geometry
LeetCode 973 note: as in Top-K, keep a size-k max-heap (negated distances) holding the k closest points
LeetCode 167: Two Sum II - Input Array Is Sorted
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search
LeetCode 167 note: sorted, so move two pointers inward, shifting right when the sum is too large and left when too small; indices are 1-based
LeetCode 75: Sort Colors
·2 mins
LeetCode Medium Array Two-Pointers Sorting Quicksort
LeetCode 75 note: the Dutch flag, with 0s left of low and 2s right of high; after swapping a 2 to high, do not advance, since the swapped-in value is unchecked