Start learning free

LESSON 116 OF 667 · ARRAYS - CHALLENGES

Undo the Last Add in C++: push_back and pop_back

Practice Read the full explanation

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

    C++ · ARRAYS - CHALLENGES

    Undo The Last Add in C++, explained

    Problem overview

    The function undoLastAdd receives a vector<string> called items, which is a shopping list, and two words, first and second. It adds first to the end of the list, then adds second to the end, then undoes the last add by removing the last item. It returns the 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 function returns ["milk", "eggs", "bread"].

    Approach

    A vector has a front and a back, and the two operations that work at the back are exactly what the task describes. push_back(x) appends x after the last element. pop_back() removes the last element and returns nothing. The undo is therefore not a search for a word: it removes whatever sits at the end at that moment.

    That is the point of the third example. With items = ["water"], first = "juice" and second = "water", the list becomes ["water", "juice", "water"]. The word "water" appears twice, but pop_back never looks at values. It removes the final one, the word just added, and the result is ["water", "juice"].

    Here is the third example one operation at a time:

    start:                     ["water"]                    size 1
    push_back("juice"):        ["water", "juice"]           size 2
    push_back("water"):        ["water", "juice", "water"]  size 3
    pop_back():                ["water", "juice"]           size 2
    

    Each push grows the vector by one element and the pop shrinks it by one, so the final list is the starting list plus first. That also explains why the function can never fail on a vector of any length: the two pushes guarantee that the pop has something to remove.

    Step by step

    1. Add first. push_back puts it after the existing items. On an empty list it becomes the only item.
    2. Add second. It lands after first, so it is now the last item.
    3. Undo. pop_back removes the last item, which is second.
    4. Return items. The list now ends with first.

    The solution in C++

    class Solution {
    public:
        vector<string> undoLastAdd(vector<string> &items, string first, string second) {
            items.push_back(first);
            items.push_back(second);
            items.pop_back();
            return items;
        }
    };
    

    Two details are worth knowing:

    • items is a reference. The parameter is declared vector<string> &items, so the function changes the caller's vector, not a copy. After a call with ["milk", "eggs"], the caller's own list also reads ["milk", "eggs", "bread"]. The words first and second are passed by value and are copied.
    • The return value is a copy. return items; returns a vector<string> by value, so the caller receives a copy of the final list. The tests only check what is returned.

    Edge cases and common mistakes

    • Empty list. With items = [], first = "apples" and second = "pears", the list is ["apples", "pears"] after the adds and ["apples"] after the undo. pop_back is safe here because the list has two items by then.
    • Removing by value. Searching for second and erasing it would remove the first matching word, which is the wrong one when the word appears earlier in the list.
    • Calling pop_back on an empty vector. That is undefined behaviour. It can't happen in this lesson, because two words were just added, but it matters whenever you undo on a list you haven't just filled.
    • Forgetting the return. A function with a non-void return type that reaches its closing brace without return is undefined behaviour in C++, so always end with return items;.

    Testing

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