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:

  1. Reverse the entire array
  2. Reverse the first n-k elements
  3. Reverse the last k elements

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
INPUTALGORITHMRESULTArray: [1,2,3,4,5]k = 2 (shift left by 2)1234501234Original array with indicesTriple Reversal Steps:1Reverse entire array[1,2,3,4,5] → [5,4,3,2,1]2Reverse first n-k = 3 elements[5,4,3,2,1] → [3,4,5,2,1]3Reverse last k = 2 elements[3,4,5,2,1] → [3,4,5,1,2]Space: O(1) | Time: O(n)In-place modificationLeft-shifted by 2 positions34512Green: Elements moved to frontOrange: Elements moved to backOutput: [3,4,5,1,2]Successfully shifted left!Key Insight:Three coordinated array reversals achieve left shift without extra space - it transformsthe problem into simple in-place swaps rather than complex element movements.TutorialsPoint - Array Left Shift by Reversal | Triple Reversal Technique
Asked in
Amazon 32 Microsoft 28 Google 25 Meta 18
89.2K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen