Problem 226876 · medium · Phase 02 Linear Data Structures

Rotate Left In Place

arrays · in-place · reversal

Given a list nums and a non-negative integer k, rotate the list to the left by k positions in place: the element at index k becomes the first element, and the first k elements move to the end in their original order. The function returns nothing; the list itself must be changed, and you may use only O(1) extra memory (no copy of the list, no slice concatenation).

Tests call it as (rotate_left(a := [1, 2, 3, 4, 5], 2), a)[1] and inspect the list afterwards.

Examples

Input:  nums = [1, 2, 3, 4, 5], k = 2
After:  [3, 4, 5, 1, 2]

Input:  nums = [1, 2, 3], k = 7
After:  [2, 3, 1]
Explanation: 7 left steps on 3 elements equals 1 left step.

Constraints

  • 0 <= len(nums) <= 10**5
  • 0 <= k <= 10**9
  • Modify nums in place, return None, O(1) extra space.
  • Target: O(n) time.

Goals

  • Rotate without allocating a second list
  • Compose three reversals into a rotation
  • Reduce k modulo the length before rotating
Starting Python…