Start learning free

LESSON 150 OF 338 · LOOPING OVER ARRAY INDICES

Reverse Array in Go: Looping Backwards Over a Slice

Practice Read the full explanation

Given an array of integers nums, return an array containing the integers in reverse order, without using built-in functions.

Example:

Input: nums = [2, 9, 1, 5, 8]
Output: [8, 5, 1, 9, 2]

Note:

Do not use builtin functions such as reverse(), it would defy the purpose of the challenge. Write the whole code yourself.

STEP 1 OF 4
    Ctrl + Enter to check

    GO · LOOPING OVER ARRAY INDICES

    Reverse Array in Go, explained

    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

    1. Create the answer. answer := []int{} is an empty, non-nil slice that append can grow.
    2. Write a counting-down loop. Go's for has three parts: start at len(nums) - 1, continue while i >= 0, and run i-- after each pass. The start is len(nums) - 1 because indices begin at 0, so the last valid index is one less than the length.
    3. Append each element. nums[i] goes onto answer, and the result of append is assigned back to answer.
    4. Return answer once 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-part for init; condition; post covers 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. len returns an int, so i is an int too and can go below zero. That is why i >= 0 works as the stopping test. In languages with unsigned sizes, this loop needs extra care.
    • append returns the slice. When the underlying array is full, append allocates a bigger one, so the returned slice may point somewhere new. Always write answer = 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) - 1 is -1, the condition -1 >= 0 is false immediately, and the function returns an empty slice. No error occurs.
    • One element. [7] gives [7].
    • Starting at len(nums). Index len(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 [].
    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free