0
0
GoProgramBeginner · 2 min read

Go Program to Rotate Slice with Example and Explanation

In Go, you can rotate a slice by using slicing and appending like rotated := append(slice[n:], slice[:n]...) to move the first n elements to the end.
📋

Examples

Input[1, 2, 3, 4, 5], n=2
Output[3 4 5 1 2]
Input[10, 20, 30], n=1
Output[20 30 10]
Input[7, 8, 9], n=0
Output[7 8 9]
🧠

How to Think About It

To rotate a slice, think of moving the first n elements to the end while keeping the order of the rest. You can split the slice into two parts: from n to end, and from start to n, then join them in reverse order.
📐

Algorithm

1
Get the slice and the number n to rotate by.
2
Split the slice into two parts: from index n to end, and from start to n.
3
Create a new slice by appending the second part after the first part.
4
Return or print the rotated slice.
💻

Code

go
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)
}
Output
[3 4 5 1 2]
🔍

Dry Run

Let's trace rotating [1, 2, 3, 4, 5] by 2 positions through the code

1

Calculate effective rotation

n = 2 % 5 = 2

2

Split slice

slice[n:] = [3, 4, 5], slice[:n] = [1, 2]

3

Append slices

append([3, 4, 5], [1, 2]...) = [3, 4, 5, 1, 2]

Stepnslice[n:]slice[:n]Result
12[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

Rotate by copying to new slice
go
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))
}
This method creates a new slice and copies elements one by one, which uses extra memory but is clear and safe.
Rotate in-place using reversal
go
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)
}
This method rotates the slice in place without extra memory by reversing parts of the slice three times.

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.

ApproachTimeSpaceBest For
Slicing and appendO(n)O(n)Simple and readable code
Copy to new sliceO(n)O(n)Clear logic, safe copying
In-place reversalO(n)O(1)Memory efficient, in-place rotation
💡
Use modulo n % len(slice) to handle rotations larger than the slice length.
⚠️
Forgetting to use modulo causes index errors or no rotation when n is bigger than the slice length.