Drill

ProblemsGo › warmup

Rotate a list

mediumwarmupArraysGo

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

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

Go 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

func rotateLeft(values []int, by int) []int {
	
}

Worked examples

CallResult
rotateLeft([]int{1, 2, 3, 4}, 1)[]int{2, 3, 4, 1}
rotateLeft([]int{1, 2, 3, 4}, 5)[]int{2, 3, 4, 1}
rotateLeft([]int{1, 2, 3, 4}, -1)[]int{4, 1, 2, 3}
rotateLeft([]int{1, 2, 3}, 0)[]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 Go
func rotateLeft(values []int, by int) []int {
	n := len(values)
	result := []int{}
	if n == 0 {
		return result
	}
	k := ((by % n) + n) % n
	for i := 0; i < n; i++ {
		result = append(result, values[(i+k)%n])
	}
	return result
}

The same problem in another language

More warmup problems in Go