Go Program to Reverse Slice with Example and Explanation
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 { slice[i], slice[j] = slice[j], slice[i] }.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func reverseSlice(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func main() { slice := []int{1, 2, 3, 4, 5} reverseSlice(slice) fmt.Println(slice) }
Dry Run
Let's trace reversing the slice [1, 2, 3, 4, 5] through the code
Initial indexes and slice
i=0, j=4, slice=[1 2 3 4 5]
Swap elements at i and j
Swap slice[0] and slice[4]: slice becomes [5 2 3 4 1]
Move indexes
i=1, j=3
Swap elements at i and j
Swap slice[1] and slice[3]: slice becomes [5 4 3 2 1]
Move indexes
i=2, j=2 (stop because i is not less than j)
| i | j | Slice state |
|---|---|---|
| 0 | 4 | [1 2 3 4 5] |
| 1 | 3 | [5 2 3 4 1] |
| 2 | 2 | [5 4 3 2 1] |
Why This Works
Step 1: Two pointers approach
We use two pointers, i at the start and j at the end, to swap elements moving inward.
Step 2: Swapping elements
Swapping s[i] and s[j] reverses their positions without needing extra space.
Step 3: Stopping condition
When i meets or passes j, the slice is fully reversed.
Alternative Approaches
package main import "fmt" func reverseNewSlice(s []int) []int { n := len(s) result := make([]int, n) for i := 0; i < n; i++ { result[i] = s[n-1-i] } return result } func main() { slice := []int{1, 2, 3, 4, 5} reversed := reverseNewSlice(slice) fmt.Println(reversed) }
package main import "fmt" func reverseRecursive(s []int, start, end int) { if start >= end { return } s[start], s[end] = s[end], s[start] reverseRecursive(s, start+1, end-1) } func main() { slice := []int{1, 2, 3, 4, 5} reverseRecursive(slice, 0, len(slice)-1) fmt.Println(slice) }
Complexity: O(n) time, O(1) space
Time Complexity
The loop runs once for half the slice length, so it is O(n) where n is the slice length.
Space Complexity
The reversal is done in-place with no extra slice, so space complexity is O(1).
Which Approach is Fastest?
In-place swapping is fastest and uses least memory; creating a new slice uses extra space and recursion adds call overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| In-place swap | O(n) | O(1) | Memory efficient and fast |
| New reversed slice | O(n) | O(n) | When original slice must not be changed |
| Recursion | O(n) | O(n) | Conceptual clarity but less efficient for large slices |