Problem overview
The function reverse receives a slice of integers, nums, and returns a new slice with the same numbers in the opposite order. The lesson asks you to write the loop yourself instead of calling a ready-made reverse helper.
For nums = [2, 9, 1, 5, 8], the answer is [8, 5, 1, 9, 2]: the last element comes first, then the one before it, and so on down to the first.
Approach: walk the indices from the end
Reading a slice from the front gives the original order. Reading it from the back gives the reverse. So the plan is to visit the indices from len(nums) - 1 down to 0 and append each element to a new slice. After the last visit, the new slice holds the numbers in reverse order.
The input is left untouched, since the function builds a separate answer.
On the example, i starts at 4 and appends 8. Then i is 3 and it appends 5, then 1 at index 2, then 9 at index 1, and finally 2 at index 0. After that i becomes -1, the condition i >= 0 fails and the loop ends with [8, 5, 1, 9, 2] in answer.
Step by step
- Create the answer.
answer := []int{}is an empty, non-nil slice thatappendcan grow. - Write a counting-down loop. Go's
forhas three parts: start atlen(nums) - 1, continue whilei >= 0, and runi--after each pass. The start islen(nums) - 1because indices begin at 0, so the last valid index is one less than the length. - Append each element.
nums[i]goes ontoanswer, and the result ofappendis assigned back toanswer. - Return
answeronce the loop ends.
The solution in Go
func reverse(nums []int) []int {
answer := []int{}
for i := len(nums) - 1; i >= 0; i-- {
answer = append(answer, nums[i])
}
return answer
}
The Go details worth knowing:
- Go has one loop keyword. There is no
while; the three-partfor init; condition; postcovers counting up, counting down and everything in between. The parentheses other languages use around the three parts are not written in Go. - The loop variable is a plain
int.lenreturns anint, soiis aninttoo and can go below zero. That is whyi >= 0works as the stopping test. In languages with unsigned sizes, this loop needs extra care. appendreturns the slice. When the underlying array is full,appendallocates a bigger one, so the returned slice may point somewhere new. Always writeanswer = append(answer, ...).- The input is not modified. After
reverse([]int{1, 2, 3})returns[3 2 1], the original slice is still[1 2 3].
Complexity
Time: O(n). The loop runs once per element, and each append costs amortized constant time.
Space: O(n). The answer holds n integers. Reversing in place with two indices that swap elements from both ends would need only O(1) extra space, but this lesson builds a new slice.
Edge cases and common mistakes
- Empty slice.
len(nums) - 1is -1, the condition-1 >= 0is false immediately, and the function returns an empty slice. No error occurs. - One element.
[7]gives[7]. - Starting at
len(nums). Indexlen(nums)is one past the end, and reading it stops the program with an "index out of range" panic. - Stopping at
i > 0. The first element would be skipped, so[2, 9, 1]would give[1, 9]. - Counting the wrong way. With
i++in a loop that starts at the end, the index runs past the slice and panics. - Ignoring the result of
append. Go refuses to compile a call whose result is unused.
Testing
[2, 9, 1, 5, 8]gives[8, 5, 1, 9, 2].[1, 2]gives[2, 1].[7]gives[7].[]gives[].