Top Interview 150
Rotating an array is a fundamental problem that tests your ability to optimize space and time usage. Let's tackle LeetCode 189: Rotate Array, understand its nuances, and implement an efficient solution.
π Problem Description
Given an integer array nums
, rotate the array to the right by k
steps.
- Key Constraints:
- Perform the rotation in-place, meaning no extra array for storage.
- 1 β€ nums.length β€ 10*5
π‘ Examples
Example 1
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Example 2
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
π§ Key Insights
- Circular Rotation: Rotating by
k
steps is equivalent to slicing and concatenating, but achieving this in-place is tricky. - Modular Arithmetic: Since rotating by
k
steps is the same as rotating byk % nums.length
, unnecessary full rotations can be avoided.
π JavaScript Solution
This solution uses a reverse strategy for optimal in-place rotation.
Reverse Strategy
- Reverse the entire array.
- Reverse the first k elements.
- Reverse the remaining elements.
var rotate = function(nums, k) {
k = k % nums.length;
if (k === 0) return;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
};
function reverse(arr, start, end) {
while (start < end) {
[arr[start], arr[end]] = [arr[end], arr[start]];
start++;
end--;
}
}
π How It Works
Reverse the array:
Turns[1,2,3,4,5,6,7]
into[7,6,5,4,3,2,1]
.Reverse the first
k
elements:
Turns[7,6,5]
into[5,6,7]
.Reverse the rest:
Turns[4,3,2,1]
into[1,2,3,4]
.
Final Output:[5,6,7,1,2,3,4]
.
π Complexity Analysis
- > Time Complexity:
O(n)
, as each reverse operation takes O(n), and there are three operations. - > Space Complexity:
O(1)
, as no extra memory is used.
π Dry Run
Input: nums = [1,2,3,4,5,6,7]
, k = 3
Output: [5,6,7,1,2,3,4]
β¨ Pro Tips for Interviews
- Understand modular arithmetic: Reducing
k
tok % nums.length
is crucial for efficiency. - Edge cases: Consider arrays with one element or when
k = 0
. - Explain the reverse strategy: Itβs optimal and clean for in-place array rotation.
π Learn More
For a detailed walkthrough and explanation, check out my Dev.to post:
π Majority Element - JavaScript Solution
Let me know your thoughts! How would you approach this problem? π
Top comments (0)