Start learning free

LESSON 119 OF 292 · ARRAYS - CHALLENGES

Undo The Last Add in Swift: append and removeLast

Practice Read the full explanation

You keep a shopping list, an array of strings items. Add the word first to the end of the list, then add the word second to the end, then undo the last add by removing the last item. Return the list.

The undo always removes the item at the end of the list, even when the same word also appears earlier in the list.

 

Example 1:

Input: items = ["milk", "eggs"], first = "bread", second = "jam"
Output: ["milk", "eggs", "bread"]
Explanation: After the two adds the list is ["milk", "eggs", "bread", "jam"]. The undo removes "jam", the last item.

Example 2:

Input: items = [], first = "apples", second = "pears"
Output: ["apples"]
Explanation: The list starts empty. "apples" and "pears" are added, then "pears" is removed.

Example 3:

Input: items = ["water"], first = "juice", second = "water"
Output: ["water", "juice"]
Explanation: The list becomes ["water", "juice", "water"]. The undo removes the last item, the "water" just added, not the first one.

 

Constraints:

  • items has between 0 and 10 words: it may be empty.
  • first, second and every word in items are single words of lowercase English letters.
  • The same word may appear more than once.
STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · ARRAYS - CHALLENGES

    Undo The Last Add in Swift, explained

    Problem overview

    The function undoLastAdd receives a shopping list, an array of strings called items, and two words, first and second. It adds first to the end, adds second to the end, then undoes the last add by removing the last item. It returns the resulting list.

    With items = ["milk", "eggs"], first = "bread" and second = "jam", the list becomes ["milk", "eggs", "bread", "jam"] after the two adds. The undo removes "jam", so the result is ["milk", "eggs", "bread"].

    Approach

    The undo removes whatever is at the end of the array. It doesn't search for a word, so it never matters whether second also appears earlier in the list. With items = ["water"], first = "juice" and second = "water", the list goes ["water", "juice", "water"] and the undo takes off the last "water", leaving ["water", "juice"].

    Since second is added and then removed, the final list is always items followed by first. The lesson still asks you to do the three operations in order, which is the point of the exercise: practising append and removeLast().

    Other array methods work from the same idea. append and removeLast() both act on the end of the array, which is cheap, while insert(_:at:) and remove(at:) let you pick a position. Acting on the end is exactly how an undo button on a list behaves: the most recent change is the first one reversed.

    Printing the array after each operation shows what is happening. For the first example, the list is ["milk", "eggs"] to begin with, then ["milk", "eggs", "bread"], then ["milk", "eggs", "bread", "jam"], and finally ["milk", "eggs", "bread"] again.

    Step by step

    1. Make a mutable copy. A function's parameters are constants in Swift, so items.append(first) on the parameter is a compile error. Declaring a new var items from the parameter gives you an array you can change.
    2. Append first. append always adds at the end, and on an empty array the new word becomes the only item.
    3. Append second. Now second is the last element.
    4. Call removeLast(). It removes the final element, which is second.
    5. Return the array. It ends with first.

    The solution in Swift

    class Solution {
        func undoLastAdd(_ items: [String], _ first: String, _ second: String) -> [String] {
            var items = items
            items.append(first)
            items.append(second)
            items.removeLast()
            return items
        }
    }
    

    A few Swift details matter here:

    • Parameters are constants. Without the copy, the compiler rejects the code with cannot use mutating member on immutable value: 'items' is a 'let' constant.
    • Shadowing. var items = items declares a new local variable with the same name as the parameter. The right-hand side still refers to the parameter, and from the next line on, items means the copy.
    • Arrays are value types. Assigning an array copies it, so changing the local items never changes the array the caller passed in. After calling undoLastAdd(orig, "b", "c") on let orig = ["a"], printing orig still gives ["a"].
    • removeLast() returns the removed element. The call above ignores that value, which Swift allows for this method.

    Edge cases and common mistakes

    • An empty list. items = [], first = "apples", second = "pears" gives ["apples"]. The array has two elements by the time removeLast() runs, so it never operates on an empty array.
    • Removing by value. Looking for second and removing its first match would take out the wrong "water" in the example above. removeLast() works by position.
    • Skipping the copy. Trying to mutate the parameter fails to compile.
    • Calling removeLast() on an empty array stops the program with a run-time error. It can't happen in this lesson, but it is why you add before you remove.

    Testing

    • ["milk", "eggs"], "bread", "jam" gives ["milk", "eggs", "bread"].
    • [], "apples", "pears" gives ["apples"].
    • ["water"], "juice", "water" gives ["water", "juice"].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free