Start learning free

LESSON 114 OF 285 · ARRAYS - CHALLENGES

Swap First and Last in JavaScript: Swapping Array Items

Practice Read the full explanation

Given an array 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

    JAVASCRIPT · ARRAYS - CHALLENGES

    Swap First And Last in JavaScript, explained

    Problem overview

    The method swapFirstAndLast receives an array of integers, nums. It swaps the first and last numbers in place and returns the array. The numbers in between don't move.

    [1, 2, 3, 4, 5] becomes [5, 2, 3, 4, 1]. [4, 9] becomes [9, 4]. With a single number, such as [7], the first and the last are the same item, so the array stays as it is.

    Approach

    Two values can't trade places in a single assignment. If you write nums[0] = nums[nums.length - 1] first, the old first number is overwritten and lost. So one value has to wait in a temporary variable, like a third cup when you swap the drinks in two cups.

    The plan is: save the first number, copy the last number into the first place, then put the saved number into the last place. The last index is nums.length - 1, because indexes start at 0.

    Step by step

    1. Save the first number in a variable temp, declared with let.
    2. Copy the last number into index 0.
    3. Write temp into the last index. Now nums[0] holds the old last number, so the old first number survives only in temp.
    4. Return nums. The array itself was changed, so it comes back swapped.

    Tracing the swap

    Take nums = [1, 2, 3]. After the first step, temp is 1 and the array is still [1, 2, 3]. After the second step, index 0 holds 3, so the array is [3, 2, 3]: the old first number exists only in temp. After the third step, the last index holds 1, and the array is [3, 2, 1].

    The solution in JavaScript

    class Solution {
        swapFirstAndLast(nums) {
            let temp = nums[0];
            nums[0] = nums[nums.length - 1];
            nums[nums.length - 1] = temp;
            return nums;
        }
    }
    

    On the examples it returns:

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

    Arrays are objects, so the function changes the caller's array rather than a copy. If you call it with a variable a = [1, 2, 3], then afterwards a is [3, 2, 1], and the returned value is the very same array (a === result is true). This is what the lesson asks for: change nums itself, then return it.

    Changing an array inside a function

    A parameter that holds an array refers to the same array the caller has, so assigning to nums[0] changes it for everyone. Reassigning the parameter itself, nums = something, would not. Declaring an array with const doesn't stop you from changing its items either: after const k = [1, 2, 3]; k[0] = 9;, k is [9, 2, 3]. Only rebinding the name is blocked.

    Edge cases and common mistakes

    • Skipping the temporary variable. Copying the last item to the first place and then the first to the last place leaves both ends equal to the old last number, because the first was already overwritten.
    • One number. The first and last index are both 0. The code saves the number, writes it to the same place and writes it back, so nothing changes.
    • Two numbers. The items are neighbours, and the same three steps swap them.
    • Wrong last index. nums[nums.length] is past the end. Use nums.length - 1.

    Testing

    • [-5, 0, 5, 10] gives [10, 0, 5, -5].
    • [1000, -1000] gives [-1000, 1000].
    • [3, 3, 3] gives [3, 3, 3].

    The version without temp fails on the first example: it turns [1, 2, 3, 4, 5] into [5, 2, 3, 4, 5].

    JavaScript can also swap with destructuring, [a, b] = [b, a]. This lesson practises the temporary variable, which works in every language.

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free