Rotate a List to the Left

Medium ⏱ 12 min 45% acceptance ★★★★★ 4.6
Write rotate_left(items, k) that rotates items to the left by k positions and returns the new list. Elements that fall off the front reappear at the end. Handle k larger than len(items) by using the modulo of the length. Assume items is non-empty.

Examples

Example 1
Input
items = [1, 2, 3, 4, 5], k = 2
Output
[3, 4, 5, 1, 2]
Explanation

The first two elements move to the end.

Example 2
Input
items = [1, 2, 3], k = 4
Output
[2, 3, 1]
Explanation

4 % 3 == 1, so this is a rotation by 1.

Constraints

  • 1 <= len(items) <= 10^5
  • 0 <= k <= 10^9

Topics

ListsSlicing

Companies

GoogleNetflix

Hints

Hint 1

k %= len(items) avoids unnecessary full rotations.

Hint 2

items[k:] + items[:k] performs the rotation via slicing.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.