Start learning free

LESSON 124 OF 671 · ARRAYS - CHALLENGES

Add an Item If Missing in Go

Practice Read the full explanation

You get a shopping list items, a slice of strings, and a word item. Add item at the end only when it isn't in the list yet. Return the list.

When item is already there, the list stays as it is. The list may start empty.

 

Example 1:

Input: items = ["milk", "eggs"], item = "bread"
Output: ["milk", "eggs", "bread"]
Explanation: The word "bread" is not in the list yet.
It goes at the end.

Example 2:

Input: items = ["milk", "eggs"], item = "milk"
Output: ["milk", "eggs"]
Explanation: The word "milk" is already there.
Nothing is added.

Example 3:

Input: items = [], item = "apples"
Output: ["apples"]
Explanation: The list is empty, so "apples" is new.
It becomes the only item.

 

Constraints:

  • items has 0 to 9 words: it may be empty.
  • item and every word in items are made of lowercase English letters.
STEP 1 OF 3
    Ctrl + Enter to check

    GO · ARRAYS - CHALLENGES

    Add If Missing in Go, explained

    Problem overview

    The function addIfMissing receives a shopping list items, a slice of strings, and a word item. It adds item at the end only when the list doesn't hold it yet, and returns the list. When the word is already there, the list comes back as it was. The list may be empty.

    For ["milk", "eggs"] and "bread" the result is [milk eggs bread]. For "milk" it stays [milk eggs]. For an empty list and "apples" it becomes [apples].

    Approach

    The task is a check followed by an action. The check is a membership test, which slices.Contains answers with a bool. The action is append. Put ! in front of the test, so the action runs only when the word is missing, and the list never gets the same word twice.

    The membership test reads the whole list, from the first word to the last, and stops at the first match. For a shopping list of a few words that is instant. Doing the test before the append is what keeps the list free of duplicates, and the order of the words is untouched: new words always go at the end.

    Step by step

    1. Write an if whose condition is !slices.Contains(items, item), true when the word is missing.
    2. Inside it, append item to items and assign the result back, since append returns the new slice.
    3. After the if, return items.

    The solution in Go

    func addIfMissing(items []string, item string) []string {
        if !slices.Contains(items, item) {
            items = append(items, item)
        }
        return items
    }
    

    There is no else: when the word is present, nothing needs to happen, and the function simply returns the slice it received.

    The assignment items = append(items, item) changes only the function's own variable. That is why the new slice is returned and the caller uses the return value. A helper that appended to its parameter and returned nothing would leave the caller's slice unchanged.

    An empty list is not special. slices.Contains on an empty slice is false, so the word is appended. A slice that is nil, with no memory behind it yet, behaves the same way: addIfMissing(nil, "tea") returns [tea].

    Testing

    itemsitemresult
    [milk eggs]bread[milk eggs bread]
    [milk eggs]milk[milk eggs]
    []apples[apples]

    All three rows come from running the function.

    Edge cases and common mistakes

    Three situations are worth checking by hand: a new word, a word already present, and an empty list. The table above covers all three. A word that appears in the middle of the list counts as present just like one at the start or end, because slices.Contains looks at every position.

    • Dropping the !. The word would be added only when it is already there, so new words never get in.
    • Appending without the check. ["milk"] becomes [milk milk].
    • Comparing with the wrong case. The words are all lowercase letters, so "Milk" would count as a different word. The constraints keep this from happening here.
    • Leaving out the assignment from append. Writing just append(items, item) is a compile error: append(items, item) (value of type []string) is not used.
    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free