Go Program to Rotate Slice with Example and Explanation
rotated := append(slice[n:], slice[:n]...) to move the first n elements to the end.Examples
How to Think About It
Algorithm
Code
package main import ( "fmt" ) func rotateSlice(slice []int, n int) []int { length := len(slice) if length == 0 { return slice } n = n % length return append(slice[n:], slice[:n]...) } func main() { s := []int{1, 2, 3, 4, 5} rotated := rotateSlice(s, 2) fmt.Println(rotated) }
Dry Run
Let's trace rotating [1, 2, 3, 4, 5] by 2 positions through the code
Calculate effective rotation
n = 2 % 5 = 2
Split slice
slice[n:] = [3, 4, 5], slice[:n] = [1, 2]
Append slices
append([3, 4, 5], [1, 2]...) = [3, 4, 5, 1, 2]
| Step | n | slice[n:] | slice[:n] | Result |
|---|---|---|---|---|
| 1 | 2 | [3 4 5] | [1 2] | [3 4 5 1 2] |
Why This Works
Step 1: Modulo for rotation
Using n = n % len(slice) ensures rotation works even if n is larger than the slice length.
Step 2: Slicing the slice
We split the slice into two parts: from n to end, and from start to n.
Step 3: Appending slices
Appending the first part after the second moves the first n elements to the end, completing the rotation.
Alternative Approaches
package main import "fmt" func rotateCopy(slice []int, n int) []int { length := len(slice) if length == 0 { return slice } n = n % length rotated := make([]int, length) for i := 0; i < length; i++ { rotated[i] = slice[(i+n)%length] } return rotated } func main() { s := []int{1, 2, 3, 4, 5} fmt.Println(rotateCopy(s, 2)) }
package main import "fmt" func reverse(slice []int, start, end int) { for start < end { slice[start], slice[end] = slice[end], slice[start] start++ end-- } } func rotateInPlace(slice []int, n int) { length := len(slice) if length == 0 { return } n = n % length reverse(slice, 0, n-1) reverse(slice, n, length-1) reverse(slice, 0, length-1) } func main() { s := []int{1, 2, 3, 4, 5} rotateInPlace(s, 2) fmt.Println(s) }
Complexity: O(n) time, O(n) space
Time Complexity
The main approach uses slicing and appending which takes O(n) time because it processes each element once.
Space Complexity
The main method creates a new slice with append, so it uses O(n) extra space. The in-place reversal method uses O(1) space.
Which Approach is Fastest?
The in-place reversal method is fastest in space, but slightly more complex. The append method is simpler but uses extra memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Slicing and append | O(n) | O(n) | Simple and readable code |
| Copy to new slice | O(n) | O(n) | Clear logic, safe copying |
| In-place reversal | O(n) | O(1) | Memory efficient, in-place rotation |
n % len(slice) to handle rotations larger than the slice length.