Start learning free

LESSON 114 OF 667 · ARRAYS - CHALLENGES

Swap First and Last in C++: Swapping Vector Items with a Temp

Practice Read the full explanation

Given a vector 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

    C++ · ARRAYS - CHALLENGES

    Swap First And Last in C++, explained

    Problem overview

    The function swapFirstAndLast receives a vector of integers, nums, swaps its first and last numbers, and returns it. The numbers in between stay where they are. For [1, 2, 3, 4, 5] the answer is [5, 2, 3, 4, 1]. For [4, 9] the two numbers trade places and the answer is [9, 4]. A vector with one number, [7], stays as it is, because that number is both the first and the last.

    The vector has at least one number, and each number is between -1000 and 1000.

    Approach

    Swapping two values can't be done with two plain assignments. If you write the last value into the first place, the old first value is gone. The standard answer is a third variable, often called temp, that holds one value while the other moves. The picture is two cups of different drinks: to swap them you need a third, empty cup.

    The first number is at index 0. The last one is at index nums.size() - 1, since indexes start at 0.

    Step by step

    1. Save the first number. int temp = nums[0]; keeps its value safe.
    2. Copy the last number into the first place. nums[0] = nums[nums.size() - 1]; overwrites the first position, which is fine now that its old value is in temp.
    3. Put the saved number in the last place. nums[nums.size() - 1] = temp; finishes the swap. Position 0 already holds the old last number, so the old first number survives only in temp.
    4. Return nums.

    The solution in C++

    class Solution {
    public:
        vector<int> swapFirstAndLast(vector<int> &nums) {
            int temp = nums[0];
            nums[0] = nums[nums.size() - 1];
            nums[nums.size() - 1] = temp;
            return nums;
        }
    };
    

    Details to know about this C++ code:

    • The reference parameter. vector<int> &nums means the function works on the caller's own vector, not on a copy. The swap therefore changes the caller's vector. For [1, 2, 3, 4, 5], the caller's vector holds [5, 2, 3, 4, 1] after the call.
    • Returning a vector. The return type is vector<int>, not a reference, so the function returns a copy of the swapped vector. The values are the same either way.
    • One element. When the vector has one number, nums.size() - 1 is 0. The three lines copy the value onto itself, and nothing changes.
    • The standard library has this built in. swap(nums.front(), nums.back()) swaps the same two items. It does the same work as the temp lines, and it is the usual choice in real code. The lesson writes the steps out so you can see how a swap works.
    • Unsigned size. nums.size() - 1 wraps around to a huge number on an empty vector, and indexing with it would be undefined behaviour. The constraints promise at least one number.

    Edge cases and common mistakes

    • Skipping the temporary variable. Writing nums[0] = nums[nums.size() - 1]; and then nums[nums.size() - 1] = nums[0]; leaves the last number in both places, because the first number was overwritten.
    • Using nums.size() as the last index. The last valid index is one less than the size.
    • Two numbers. The first and last positions are neighbours, and [4, 9] becomes [9, 4]. The same steps handle it.
    • Touching the middle. Only two positions change. The numbers between them stay in place.

    Testing

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