Start learning free

LESSON 119 OF 291 · ARRAYS - CHALLENGES

Undo the Last Add in Scala: ArrayBuffer += and remove

Practice Read the full explanation

You keep a shopping list, an ArrayBuffer 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 4
    Ctrl + Enter to check

    SCALA · ARRAYS - CHALLENGES

    Undo The Last Add in Scala, explained

    Problem overview

    The method undoLastAdd receives a shopping list, items, which is an ArrayBuffer[String], 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, and returns the list.

    With items = ["milk", "eggs"], first = "bread" and second = "jam", the list grows to milk, eggs, bread, jam. The undo removes jam, so the result is milk, eggs, bread.

    Approach

    An ArrayBuffer is Scala's growable, mutable sequence. Unlike a List or Vector, it changes in place, so the method can modify the buffer it was given and return it. Three operations are enough: append, append, and remove by position.

    The undo must remove the item at the end, by position, not "the item equal to second". Removing by value would take away the first matching word, which is the wrong one when the same word is already in the list.

    Step by step

    1. Append first with +=. On an empty list it becomes the only item.
    2. Append second the same way. It is now the last item.
    3. Remove the item at index items.size - 1, the last valid index, with remove.
    4. Return items.

    The solution in Scala

    class Solution {
        def undoLastAdd(items: ArrayBuffer[String], first: String, second: String): ArrayBuffer[String] = {
            items += first
            items += second
            items.remove(items.size - 1)
            return items
        }
    }
    

    Some details worth knowing:

    • += on an ArrayBuffer is a method call that appends in place. The buffer is a val-like parameter, but its contents can change.
    • remove(i) with an Int removes the element at index i and returns it. Here the returned word is simply ignored.
    • Indexes start at 0, so the last index is size - 1. After the two adds the buffer always has at least two items, so that index is always valid.
    • In a file of your own, add import scala.collection.mutable.ArrayBuffer to use the type by its short name.

    Edge cases and common mistakes

    • Repeated words. With items = ["water"], first = "juice" and second = "water", the buffer becomes water, juice, water, and removing the last index leaves water, juice. The original water stays.
    • Empty list. With items = [], first = "apples" and second = "pears", the result is apples.
    • Off-by-one. items.remove(items.size) throws an exception, because the index size is one past the end.

    What the method really does

    Add, add, undo: the net effect is that only first ends up on the list, and second is added and removed again. The exercise is there to practise the three operations that make an undo feature work in any list-based program: append to the end, remove from the end, and find the end with size - 1. A real undo would remove whatever was added last, not a fixed word, and the index size - 1 is what makes that possible.

    Why the buffer is changed in place

    Because ArrayBuffer is mutable, the method doesn't build a new list. It edits the one it received, and the returned value is that same buffer. Anyone still holding the original reference sees the changes too. Tracing items = ["water"] with first = "juice" and second = "water" shows the buffer after each line:

    after items += first    ArrayBuffer(water, juice)
    after items += second   ArrayBuffer(water, juice, water)
    after the remove        ArrayBuffer(water, juice)
    

    Removing by value is a different operation

    The operator -= removes an element by value, and it removes the first match. On ArrayBuffer(water, juice, water), -= "water" leaves ArrayBuffer(juice, water): the old item went, not the one just added. That is why this lesson removes by index.

    Testing

    These calls give:

    undoLastAdd(ArrayBuffer("milk", "eggs"), "bread", "jam")  -> ArrayBuffer(milk, eggs, bread)
    undoLastAdd(ArrayBuffer(), "apples", "pears")             -> ArrayBuffer(apples)
    undoLastAdd(ArrayBuffer("water"), "juice", "water")       -> ArrayBuffer(water, juice)
    
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free