Start learning free

LESSON 114 OF 285 · ARRAYS - CHALLENGES

Swap First and Last in Java: ArrayList with a Temp Variable

Practice Read the full explanation

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

    JAVA · ARRAYS - CHALLENGES

    Swap First And Last in Java, explained

    Problem overview

    The method swapFirstAndLast receives a list of integers, nums, swaps its first and last numbers, and returns it. The change is made on nums itself, and the numbers in between stay where they are. A list of one number is returned as it is, since its first and last numbers are the same item. Every list has at least one number.

    For [1, 2, 3, 4, 5] the result is [5, 2, 3, 4, 1]. For [4, 9] it is [9, 4]. For [7] it is [7].

    Approach: park one value in a temporary variable

    A swap can't be done in one move. If you first copy the last number into position 0, the original first number is overwritten and lost. So one value has to wait somewhere, like a third cup when you swap the drinks in two cups. That place is a temporary variable, temp.

    The order of the three moves is:

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

    For lists, two methods do all the work. get(i) reads the item at index i. set(i, value) replaces the item at index i and doesn't change the size. Indexes start at 0, so the first item is at 0 and the last is at size() - 1.

    Step by step

    1. Save the first number. int temp = nums.get(0); holds the value for a moment.
    2. Overwrite the first place with the last number. nums.set(0, nums.get(nums.size() - 1)); reads the last item and stores it at index 0.
    3. Write the saved number into the last place. nums.set(nums.size() - 1, temp); puts the old first number at the end. Index 0 already holds the last number, so the old first number survives only in temp.
    4. Return the list. The list itself was changed, so returning nums returns it swapped.

    The solution in Java

    class Solution {
        public List<Integer> swapFirstAndLast(List<Integer> nums) {
            int temp = nums.get(0);
            nums.set(0, nums.get(nums.size() - 1));
            nums.set(nums.size() - 1, temp);
            return nums;
        }
    }
    

    For the three examples, with nums built as an ArrayList, the calls print:

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

    Some Java details matter here:

    • The element type. List<Integer> is a list of Integer objects. nums.get(0) returns an Integer, which Java unboxes automatically into the int temp, and set boxes the values back.
    • The list is modified in place. Lists are objects, and the method receives a reference to the caller's list. After the call, the caller's list is swapped too. The returned value is the same object.
    • Only set replaces items. add would insert a new item and grow the list.
    • Not every list can be changed. A list from List.of(1, 2, 3) is unmodifiable, and calling set on it throws an UnsupportedOperationException. A list from new ArrayList<>(List.of(1, 2, 3)) can be changed.

    Edge cases and common mistakes

    • Skipping the temporary variable. Setting index 0 to the last number and then index size() - 1 to nums.get(0) writes the last number back to itself, so [1, 2, 3] would become [3, 2, 3].
    • One number. With [7] the first and last indexes are both 0. Save 7, write 7 to index 0, then write 7 to index 0 again: the list is unchanged, with no special case.
    • Two numbers. [4, 9] works with the same three moves and becomes [9, 4].
    • Using size() as an index. The last valid index is size() - 1. Index size() throws an IndexOutOfBoundsException.
    • Forgetting the return. The list is already swapped, but the method must still hand it back.
    • Square brackets. nums[0] is for arrays. A list needs get(0).

    Testing

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