Rotate Array - Complete Solution Guide
Rotate Array is LeetCode problem 189, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] Constraints:
Detailed Explanation
The problem requires rotating an array `nums` to the right by `k` steps. This means moving the last `k` elements to the beginning of the array and shifting the remaining elements to the right. The rotation should be done in-place, meaning we should modify the original array directly without using extra space proportional to the input size. The value of `k` can be larger than the array's length, so we need to handle that as well.
Solution Approach
The solution utilizes the reversal algorithm. First, it reduces 'k' using the modulo operator to ensure it's within the array's bounds. Then, it reverses the entire array. After that, it reverses the first 'k' elements and then reverses the remaining 'n-k' elements. This combination of reversals effectively rotates the array to the right by 'k' positions.
Step-by-Step Algorithm
- Step 1: Calculate k % n to handle cases where k > n. This ensures k is within the valid range of array indices.
- Step 2: Reverse the entire array nums from index 0 to n-1.
- Step 3: Reverse the first k elements of the array nums from index 0 to k-1.
- Step 4: Reverse the remaining n-k elements of the array nums from index k to n-1.
Key Insights
- Insight 1: Using the modulo operator (%) is crucial to handle cases where 'k' is greater than the length of the array 'nums'. This ensures that the rotation happens within the bounds of the array.
- Insight 2: The problem can be efficiently solved in-place by reversing array segments. Reversing the entire array, then reversing the first k elements, and finally reversing the remaining elements will effectively rotate the array.
- Insight 3: Reversing is an O(n) operation, so performing a constant number of reverses results in an overall linear time complexity.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Math, Two Pointers.
Companies
Asked at: Accenture, American Express, Capgemini, Capital One, DXC Technology, EPAM Systems, Flipkart, Goldman Sachs, IBM, Infosys, Netflix, Oracle, Samsung, Scale AI, ServiceNow, Visa, Walmart Labs, Wipro, Zoho, eBay, razorpay, tcs.