DSA problem
Rotate an Array by K Positions
Given an array of N integers and a number K, rotate the array to the right by K positions, in-place.
For example, rotating [1, 2, 3, 4, 5] by 2 gives [4, 5, 1, 2, 3]. The brute-force approach shifts all elements one position at a time, K times, for O(N * K). The optimal approach uses the reversal algorithm in O(N) time and O(1) space: reverse the entire array, then reverse the first K elements, then reverse the remaining N - K elements.
Reversing the whole array puts the last K elements at the front but in reverse order; the two partial reversals fix the order within each segment. Normalize with K = K % N to handle K > N.
Examples
Example 1
Input:
nums = [1, 2, 3, 4, 5, 6, 7], k = 3Output:
[5, 6, 7, 1, 2, 3, 4]Explanation: The last 3 elements [5, 6, 7] move to the front and the rest shift right.
Constraints
- 1 <= nums.length <= 10^5
- 0 <= k <= 10^9
- -10^9 <= nums[i] <= 10^9
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.