Algorithm-Day15-Rotate-Array-lc-189
🧩 Problem Description
Given an integer array nums
, rotate the array to the right by k
steps, where k
is non-negative.
Example:
1 | Input: nums = [1,2,3,4,5,6,7], k = 3 |
💡 Naive Approach (Extra Array)
Copy elements into a new array
Place each element at
(i + k) % n
indexCopy back to
nums
✅ Works
❌ Uses O(n) extra space
💡 Optimal Approach: Reverse Method
🧠 Key Idea
- Reverse the whole array
- Reverse the first
k
elements - Reverse the remaining
n - k
elements
✅ Why It Works
Reversing segments restores them into rotated order.
🔢 Java Code
🔢 Java Code
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
In-place rotation using reversals
✍️ Summary
- This problem demonstrates an important array manipulation pattern.
- The reverse trick is efficient and widely applicable in other rotation-related problems.
- Avoid extra space when possible by reusing in-place algorithms.
Understand both the logic and implementation of reverse-in-place operations — this comes up in multiple array and string questions!