Start learning free

LESSON 121 OF 293 · ARRAYS - CHALLENGES

Swap First and Last in Rust: Swapping Vec Items With a Temp

Practice Read the full explanation

Given a Vec 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 5
    Ctrl + Enter to check

    RUST · ARRAYS - CHALLENGES

    Swap First And Last in Rust, explained

    Problem overview

    The function swap_first_and_last takes a vector of integers, nums, swaps its first and last numbers, and returns it. The numbers in between stay where they are. With one number, that number is both first and last, so nothing changes. The vector has at least one number, each between -1000 and 1000.

    For [1, 2, 3, 4, 5] the result is [5, 2, 3, 4, 1]: 1 and 5 trade places. For [4, 9] it is [9, 4], and for [7] it is [7].

    Approach

    Two values can't trade places in one move. If you copy the last number into the first place right away, the old first number is overwritten and lost. So one of them has to wait somewhere safe first: a temporary variable. The sequence is:

    1. save the first number in temp;
    2. copy the last number into the first place;
    3. put temp into the last place.

    The function's signature says mut nums. The function owns the vector, and mut lets it change the items. Because the vector is passed by value, the caller's vector is moved into the function, and the function hands it back at the end.

    Step by step

    1. Store the last index in last. It is the length minus 1, because indexes start at 0. For five numbers the last index is 4.
    2. Save the first number in temp. nums[0] is about to be overwritten.
    3. Copy the last number into the first place: nums[0] = nums[last].
    4. Put the saved number in the last place: nums[last] = temp. The old first number only survives in temp, since nums[0] now holds the last one.
    5. Return nums as the last expression, without a semicolon.

    The solution in Rust

    impl Solution {
        fn swap_first_and_last(mut nums: Vec<i32>) -> Vec<i32> {
            let last = nums.len() - 1;
            let temp = nums[0];
            nums[0] = nums[last];
            nums[last] = temp;
            nums
        }
    }
    

    Some details worth knowing:

    • mut in the parameter. Without it, assigning to nums[0] doesn't compile, because variables are immutable by default. Putting mut on the parameter makes this function's own binding mutable; it doesn't change what the caller sees.
    • One number. Then last is 0 and the steps copy nums[0] onto itself, so the vector stays the same.
    • Two numbers. For [4, 9], temp is 4, the first place becomes 9, and the last place becomes 4, giving [9, 4].
    • i32 is Copy. let temp = nums[0]; copies the number, so temp stays valid when nums[0] changes.
    • The standard library has a shortcut. nums.swap(0, last) does the same job in one call, and the result is the same. The lesson spells out the temp variable so that the idea is visible.
    • The empty vector. The lesson rules it out. Its length is 0, and nums.len() - 1 would subtract from a usize that holds 0.

    Edge cases and common mistakes

    • Skipping temp. Writing nums[0] = nums[last] and then nums[last] = nums[0] gives [5, 2, 3, 4, 5] for the first example: the first number was lost at the first assignment.
    • Using the length as the index. nums[nums.len()] is one past the end and panics. The last index is len() - 1.
    • Forgetting mut. The compiler refuses the assignments to the items.
    • Adding a semicolon after nums. The last line would become a statement and the function would return nothing, which doesn't match the declared Vec<i32>.
    • Swapping the wrong pair. Only the first and last change: the numbers in between don't move.

    Testing

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