Drill

ProblemsJava › warmup

Rotate a list

mediumwarmupArraysJava

A carousel shows the same items starting from a different one each time it advances.

rotateLeft(values: list<int>, by: int) → list<int>

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

List<Integer> rotateLeft(List<Integer> values, int by) {
    
}

Worked examples

CallResult
rotateLeft(Main.<Integer>ls(1, 2, 3, 4), 1)Main.<Integer>ls(2, 3, 4, 1)
rotateLeft(Main.<Integer>ls(1, 2, 3, 4), 5)Main.<Integer>ls(2, 3, 4, 1)
rotateLeft(Main.<Integer>ls(1, 2, 3, 4), -1)Main.<Integer>ls(4, 1, 2, 3)
rotateLeft(Main.<Integer>ls(1, 2, 3), 0)Main.<Integer>ls(1, 2, 3)

Hint

Reduce the shift with a modulo first, and remember that the modulo of a negative number is negative in most of these languages.

Reference solution in Java
List<Integer> rotateLeft(List<Integer> values, int by) {
    int n = values.size();
    List<Integer> result = new ArrayList<>();
    if (n == 0) return result;
    int k = ((by % n) + n) % n;
    for (int i = 0; i < n; i++) result.add(values.get((i + k) % n));
    return result;
}

The same problem in another language

More warmup problems in Java