Start learning free

LESSON 123 OF 293 · ARRAYS - CHALLENGES

Undo the Last Add in Rust: Vec push and pop

Practice Read the full explanation

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

    RUST · ARRAYS - CHALLENGES

    Undo The Last Add in Rust, explained

    Problem overview

    The function undo_last_add receives a shopping list items, a Vec<String>, and two words, first and second. It adds first to the end, adds second to the end, removes the last item as an "undo", and returns the list.

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

    Approach

    A Vec grows and shrinks at the end cheaply, and Rust gives you a method for each direction: push appends an element and pop removes the last one. The task is just those two methods in order, so there is no searching and no index arithmetic.

    The undo removes the last position, not "the word second". That matters when the same word is already in the list. With items = ["water"], first = "juice" and second = "water", the list becomes ["water", "juice", "water"], and pop removes the final "water". The result is ["water", "juice"], with the original "water" untouched.

    Step by step

    1. Push first. It goes after every item already in the vector. On an empty list it becomes the only item.
    2. Push second. It is now the last element.
    3. Pop. This removes the last element, which is second, wherever else the same text appears.
    4. Return items as the last expression, without a semicolon.

    The solution in Rust

    impl Solution {
        fn undo_last_add(mut items: Vec<String>, first: String, second: String) -> Vec<String> {
            items.push(first);
            items.push(second);
            items.pop();
            items
        }
    }
    

    A few Rust details are at work here:

    • mut items in the signature. Parameters are immutable by default. Writing mut before the name lets the function change its own vector. The caller's variable is not affected, because the vector was moved into the function.
    • Moving the words. push(first) moves the String into the vector. first can't be used afterwards, and the code doesn't need to.
    • pop returns an Option. It gives Some(value) for the removed element and None on an empty vector. Here the value is thrown away, so the statement items.pop(); just ends with a semicolon. The vector is never empty at that point, since two words were just pushed.
    • The final expression. items has no semicolon, so it is the value the function returns.

    What pop does on an empty vector

    This function never pops from an empty vector, but it helps to know what would happen. Popping an empty Vec<String> doesn't panic: it returns None. After one push("x".to_string()), two pops in a row give Some("x") and then None. That is why pop returns an Option rather than a bare value, and why code that uses the removed element has to handle both cases.

    Edge cases and common mistakes

    • An empty list. With items = [], first = "apples" and second = "pears" the function returns ["apples"].
    • Removing by value. Looking for second in the vector and removing the first match would delete the wrong "water" in the example above. pop always takes the end.
    • Forgetting the return. A function whose last line ends in ; returns (), and the compiler reports a type mismatch with Vec<String>.
    • Swapping the pushes. If second is pushed first, the undo removes first and the result ends with the wrong word.

    Testing

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