#189

Rotate Array

Medium
ArrayMathTwo PointersArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses array reversal to achieve the rotation in-place. This is efficient and uses O(1) extra space.

⚙️

Algorithm

3 steps
  1. 1Step 1: Reverse the entire array.
  2. 2Step 2: Reverse the first k elements.
  3. 3Step 3: Reverse the remaining n-k elements.
solution.py9 lines
1# Full working Python code
2
3def rotate(nums, k):
4    n = len(nums)
5    k = k % n  # Handle cases where k >= n
6    nums.reverse()  # Step 1
7    nums[:k] = reversed(nums[:k])  # Step 2
8    nums[k:] = reversed(nums[k:])  # Step 3
9

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times (3 reversals). The space complexity is O(1) since we do not use any additional data structures.

  • 1Reversing an array can solve rotation problems efficiently.
  • 2Using modular arithmetic helps handle cases where k is larger than the array length.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.