Start learning free

LESSON 117 OF 285 · ARRAYS - CHALLENGES

Swap First and Last in Go: Changing a Slice in Place

Practice Read the full explanation

Given a slice of integers nums, swap its first and last numbers and return it.

Change nums itself, then return it. The numbers in between stay where they are. When nums has only one number, that number is both the first and the last, so it stays as it is.

 

Example 1:

Input: nums = [1, 2, 3, 4, 5]
Output: [5, 2, 3, 4, 1]
Explanation: 1 and 5 trade places. 2, 3 and 4 don't move.

Example 2:

Input: nums = [4, 9]
Output: [9, 4]
Explanation: With two numbers, the first and the last are next to each other, and they trade places.

Example 3:

Input: nums = [7]
Output: [7]
Explanation: One number is both the first and the last, so nothing changes.

 

Constraints:

  • nums has at least one number.
  • Every number is an integer between -1000 and 1000.
STEP 1 OF 4
    Ctrl + Enter to check

    GO · ARRAYS - CHALLENGES

    Swap First And Last in Go, explained

    Problem overview

    The function swapFirstAndLast receives a slice of integers, nums, with at least one number. It swaps the first and last numbers and returns the slice. The numbers in between stay where they are, and a slice with one number stays as it is, because that number is both the first and the last.

    [1, 2, 3, 4, 5] becomes [5, 2, 3, 4, 1]. [4, 9] becomes [9, 4], and [7] stays [7].

    Approach

    Swapping two values is a small puzzle. If you copy the last number into the first place, the old first number is gone. The classic fix is a temporary variable, which holds one value while the other moves, like a third cup when you swap the drinks in two cups:

    1. save the first number;
    2. copy the last number over the first place;
    3. put the saved number in the last place.

    The last index of a slice is len(nums)-1, because indexes start at 0. The function changes the slice it was given, and then returns that same slice.

    Step by step

    1. Save the first number in a variable named temp, declared with :=: temp := nums[0].
    2. Copy the last number into the first place: nums[0] = nums[len(nums)-1].
    3. Put the saved number in the last place: nums[len(nums)-1] = temp. At this point the old first number only exists in temp, so this step has to come after the save.
    4. Return nums.

    The solution in Go

    func swapFirstAndLast(nums []int) []int {
        temp := nums[0]
        nums[0] = nums[len(nums)-1]
        nums[len(nums)-1] = temp
        return nums
    }
    

    Running it on the three examples gives these results:

    [1 2 3 4 5] -> [5 2 3 4 1]
    [4 9]       -> [9 4]
    [7]         -> [7]
    

    Details worth knowing:

    • The caller's slice changes too. A slice refers to an underlying array, and the function writes into that array. After the call, a variable a := []int{1, 2, 3, 4, 5} that was passed in holds [5 2 3 4 1], the same as the returned value. The function doesn't make a copy.
    • := declares and assigns. temp := nums[0] creates temp with the type of nums[0], which is int. Go also reports a variable that is declared and never used as a compile error, which is not a problem here since temp is used in step 3.
    • Go can swap without a variable. The tuple assignment nums[0], nums[len(nums)-1] = nums[len(nums)-1], nums[0] evaluates the right side first, then assigns, so it swaps the two items in one line. The lesson spells out the three steps so that the idea is visible.

    Edge cases and common mistakes

    • A single number. The first and last indexes are both 0. The code saves nums[0], copies it onto itself, and writes it back: nothing changes, and no special case is needed.
    • Two numbers. The first and last are neighbours, and the same three steps swap them: [4, 9] becomes [9, 4].
    • Skipping the temporary variable. Writing nums[0] = nums[len(nums)-1] followed by nums[len(nums)-1] = nums[0] gives [5, 2, 3, 4, 5] for the first example: the old first number is lost after the first assignment.
    • Using len(nums) as the last index. It is one past the end, and indexing there stops the program with an "index out of range" panic.
    • An empty slice. The constraints promise at least one number. For an empty slice, nums[0] would stop the program with an "index out of range" panic.

    Testing

    • [1, 2, 3, 4, 5] gives [5, 2, 3, 4, 1].
    • [4, 9] gives [9, 4].
    • [7] gives [7].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free