Start learning free

LESSON 117 OF 292 · ARRAYS - CHALLENGES

Swap First and Last in Swift: Arrays Are Values

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

    SWIFT · ARRAYS - CHALLENGES

    Swap First And Last in Swift, explained

    Problem overview

    The function swapFirstAndLast receives an array of integers, nums, swaps its first and last numbers and returns the result. The numbers in between stay where they are. When the array has only one number, that number is both first and last, so nothing changes.

    For [1, 2, 3, 4, 5] the answer is [5, 2, 3, 4, 1]: 1 and 5 trade places while 2, 3 and 4 stay. For [4, 9] it is [9, 4]. For [7] it is [7].

    Approach: a temporary variable, and a copy you can change

    Two values can't trade places in a single move. If you copy the last number into the first place first, the old first number is gone. So one value has to wait somewhere: that is the job of a temporary variable, like a third cup when you swap the drinks in two cups.

    Swift adds one more detail. The parameter nums is a constant inside the function, and an array is a value type, so the caller's array is never changed by the function. Assigning to an item of the parameter is a compile error:

    error: cannot assign through subscript: 'nums' is a 'let' constant
    

    The fix is to make a copy that you may change.

    Step by step

    1. Make a changeable copy. Declare var nums = nums. The new variable has the same name and the same numbers and hides the parameter, so from here on nums means the copy.
    2. Save the first number in a constant: let temp = nums[0]. It waits there while the first place is overwritten.
    3. Move the last number to the front with nums[0] = nums[nums.count - 1]. Indexes start at 0, so the last one is the count minus 1.
    4. Put the saved number last with nums[nums.count - 1] = temp.
    5. Return nums, the swapped copy.

    The solution in Swift

    class Solution {
        func swapFirstAndLast(_ nums: [Int]) -> [Int] {
            var nums = nums
            let temp = nums[0]
            nums[0] = nums[nums.count - 1]
            nums[nums.count - 1] = temp
            return nums
        }
    }
    

    Details worth knowing:

    • Value semantics. Assigning an array to another variable gives an independent copy. After var b = a and b[0] = 99, with a = [1, 2, 3], a is still [1, 2, 3] and b is [99, 2, 3]. That is why the function returns the result instead of changing the caller's array: calling it on [1, 2, 3, 4, 5] returns [5, 2, 3, 4, 1] and leaves the original at [1, 2, 3, 4, 5]. The copy is cheap, because Swift copies the storage only when one of the two arrays is changed.
    • let versus var. temp is set once, so it is a let. The copy changes, so it is a var.
    • One item. For [7], nums.count - 1 is 0, so the first and last places are the same. The code stores 7, writes 7 over it, writes 7 again, and returns [7].
    • An empty array crashes. nums[0] doesn't exist for an empty array, and the program stops at run time. The lesson always gives at least one number.
    • A built-in alternative. swapAt swaps two positions of a var array: nums.swapAt(0, nums.count - 1) turns [1, 2, 3, 4, 5] into [5, 2, 3, 4, 1]. The lesson does the swap by hand to show how a temporary variable works.

    Edge cases and common mistakes

    • Skipping the temporary variable. Writing nums[0] = nums[nums.count - 1] and then nums[nums.count - 1] = nums[0] sets both places to the old last number, because the first one was already overwritten.
    • Editing the parameter. Without var nums = nums, the code doesn't compile.
    • Off by one. nums[nums.count] is one past the end and crashes. The last index is nums.count - 1.
    • Two numbers. [4, 9] gives [9, 4]: first and last are neighbours, and the same steps work.
    • Forgetting to return. The changes are made on a copy, so the function must return it.

    Testing

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