Easy: Warm-Ups · Problem 7 of 82

Rotate a List

EasyLists and SortingPython

Write rotate_left(items, k) that returns a new list with the items moved k places to the left, the items that fall off the front reappearing at the back: rotate_left([1, 2, 3, 4, 5], 2) is [3, 4, 5, 1, 2].

k can be zero, larger than the length of the list, or negative (a negative k rotates to the right). The list may be empty.

Understand the problem

Work out slicing and wrap-around.

What is [1, 2, 3, 4, 5][2:] + [1, 2, 3, 4, 5][:2]? Type the list.

The slice from position 2 to the end is [3, 4, 5] and the slice up to position 2 is [1, 2]. Together: [3, 4, 5, 1, 2]. That is a rotation by 2.

Rotating a list of 5 items by 7 is the same as rotating it by how many? (7 % 5)

After 5 rotations the list is back where it started, so only the remainder matters. 7 % 5 = 2.

What is -1 % 5 in Python?

Python's % gives a non-negative result for a positive divisor. Rotating left by -1 is the same as rotating left by 4, which is the same as rotating right by 1.

Write the solution

Return a new list; do not change the one you are given.

def rotate_left(items, k):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What can you do with k first, so that every kind of k becomes a number from 0 to len - 1? And what must you check about the list before dividing by its length?

Hint 2: the shape of the answer

If the list is empty, return it (a copy). Otherwise k = k % len(items) and return items[k:] + items[:k].

Reflect

Solution

def rotate_left(items, k):
    if not items:
        return []
    k %= len(items)
    return items[k:] + items[:k]

Another way: collections.deque

from collections import deque

def rotate_left(items, k):
    d = deque(items)
    d.rotate(-k)
    return list(d)

What this tests: slicing, list concatenation, % with negative numbers, and the empty-list edge case (k % 0 is a ZeroDivisionError).

The idea: a rotation by k is a rotation by k % len. Reduce first, then one slice and one more.

Cost: O(n) time and space. deque.rotate is the tool when you rotate many times, because it works in place.

What an interviewer might ask next: Do it in place with O(1) extra space. (Reverse the whole list, then reverse the two parts: three reversals.)