LeetCode 189: Rotate Array Solution
Master LeetCode problem 189 (Rotate Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
189. Rotate Array
Problem Explanation
Explanation
To rotate an array to the right by k steps, we can use the following approach:
- Reverse the entire array.
- Reverse the first
kelements. - Reverse the remaining elements.
This approach allows us to achieve the rotation in-place with O(1) extra space.
Time complexity: O(n), where n is the number of elements in the array. Space complexity: O(1).
Solution Code
class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 189 (Rotate Array)?
This page provides optimized solutions for LeetCode problem 189 (Rotate Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 189 (Rotate Array)?
The time complexity for LeetCode 189 (Rotate Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 189 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 189 in Java, C++, or Python.