Start learning free

LESSON 116 OF 285 · ARRAYS - CHALLENGES

Undo the Last Add in Java: ArrayList add and remove

Practice Read the full explanation

You keep a shopping list, an ArrayList 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

    JAVA · ARRAYS - CHALLENGES

    Undo The Last Add in Java, explained

    Problem overview

    The method undoLastAdd receives a shopping list, items, and two words, first and second. It adds first to the end of the list, adds second to the end, then undoes the last add by removing the final item, and returns the list.

    With items = ["milk", "eggs"], first = "bread" and second = "jam", the list becomes ["milk", "eggs", "bread", "jam"], and removing the last item leaves ["milk", "eggs", "bread"]. The method returns exactly that. With an empty list, "apples" and "pears", the result is ["apples"].

    Approach: remove by position, not by value

    The undo must take away the item at the end, even when the same word also appears earlier. With items = ["water"], first = "juice" and second = "water", the list after the two adds is ["water", "juice", "water"]. A method that searched for "water" and removed the first match would delete the wrong item. The method removes by index instead: the last item sits at index items.size() - 1.

    Step by step

    1. Add first with add. On an ArrayList, add(x) always appends to the end, so on an empty list first becomes the only item.
    2. Add second the same way. It is now the last item.
    3. Remove the item at index items.size() - 1. Indexes start at 0, so a list of size 4 has its last item at index 3.
    4. Return items. The list was changed in place, so it already holds the final contents, which end with first.

    The solution in Java

    class Solution {
        public List<String> undoLastAdd(List<String> items, String first, String second) {
            items.add(first);
            items.add(second);
            items.remove(items.size() - 1);
            return items;
        }
    }
    

    The Java details worth knowing:

    • remove has two forms. remove(int index) deletes the item at that position, and remove(Object o) deletes the first item equal to o. Here the argument items.size() - 1 is an int, so the index form runs. On a List<Integer> the choice matters: with the list [10, 20, 3], remove(2) removes the item at index 2 and leaves [10, 20], while remove(Integer.valueOf(10)) removes the value 10.
    • The list is modified in place. The method returns the same list object that the caller passed in, now with the new contents.
    • The list must be growable. An ArrayList works. A fixed-size list such as the one from List.of("a") throws an UnsupportedOperationException on add.

    Related list methods

    The method declares its parameter as List<String>, the interface, so any list implementation can be passed in. ArrayList is the usual choice. remove(int) also returns the item it removed, which the lesson ignores. For the list [a, b, c], String removed = l.remove(l.size() - 1); gives "c" and leaves [a, b]. Java 21 adds removeLast() to lists, which does the same job without the index arithmetic, but the index form works in every Java version and is the one this lesson practises.

    Edge cases and common mistakes

    • Removing by value. items.remove(second) removes the first item equal to second. For ["water"] with "juice" and "water" it would give ["juice", "water"] instead of ["water", "juice"].
    • Off-by-one index. items.remove(items.size()) is one past the end and throws an IndexOutOfBoundsException.
    • Wrong order. Removing before the second add, or adding second first, leaves the wrong word at the end.
    • Empty start. An empty items needs no special case: after two adds the list has two items, so the last index is valid.

    Testing

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