Array Left Shift by Reversal - Problem
Given an array of integers and a number k, left-shift the array elements by k positions using the triple-reversal technique with O(1) extra space.
The triple-reversal technique works by:
- Reverse the entire array
- Reverse the first
n-kelements - Reverse the last
kelements
Where n is the length of the array and k is normalized to k % n to handle cases where k > n.
Example: Array [1,2,3,4,5] left-shifted by 2 positions becomes [3,4,5,1,2]
Input & Output
Example 1 — Basic Left Shift
$
Input:
nums = [1,2,3,4,5], k = 2
›
Output:
[3,4,5,1,2]
💡 Note:
Left shift by 2: elements 1,2 move to end, elements 3,4,5 move to front. Triple reversal: [1,2,3,4,5] → [5,4,3,2,1] → [3,4,5,2,1] → [3,4,5,1,2]
Example 2 — Full Rotation
$
Input:
nums = [1,2,3], k = 3
›
Output:
[1,2,3]
💡 Note:
k=3 equals array length, so k%3=0. No shift needed, array remains [1,2,3]
Example 3 — Large k Value
$
Input:
nums = [1,2], k = 5
›
Output:
[2,1]
💡 Note:
k=5 > array length 2, so k%2=1. Left shift by 1: [1,2] → [2,1] → [1,2] → [2,1]
Constraints
- 1 ≤ nums.length ≤ 105
- -231 ≤ nums[i] ≤ 231 - 1
- 0 ≤ k ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code