Rotate a list
A carousel shows the same items starting from a different one each time it advances.
- Rotating left by one moves the first item to the end.
- A shift larger than the list wraps around; a negative shift rotates the other way.
- An empty list rotates to an empty list.
RotateLeft(values: list<int>, by: int) → list<int>
C# 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.
Where you start
public List<int> RotateLeft(List<int> values, int by) {
}
Worked examples
| Call | Result |
|---|---|
RotateLeft(new List<int> { 1, 2, 3, 4 }, 1) | new List<int> { 2, 3, 4, 1 } |
RotateLeft(new List<int> { 1, 2, 3, 4 }, 5) | new List<int> { 2, 3, 4, 1 } |
RotateLeft(new List<int> { 1, 2, 3, 4 }, -1) | new List<int> { 4, 1, 2, 3 } |
RotateLeft(new List<int> { 1, 2, 3 }, 0) | new List<int> { 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 C#
public List<int> RotateLeft(List<int> values, int by) {
int n = values.Count;
var result = new List<int>();
if (n == 0) return result;
int k = ((by % n) + n) % n;
for (int i = 0; i < n; i++) result.Add(values[(i + k) % n]);
return result;
}