Start learning free

LESSON 234 OF 285 · SETS

Unique Count in Go: Using a Map as a Set

Practice Read the full explanation

Given an array of integers nums, return how many different values it has.

A value that appears several times counts only once.

 

Example 1:

Input: nums = [4, 7, 4, 1, 7]
Output: 3
Explanation: The different values are 4, 7 and 1. The second 4 and the second 7 are repeats, so they don't count again.

Example 2:

Input: nums = [5, 5, 5]
Output: 1
Explanation: Every number is 5, so there is only one different value.

Example 3:

Input: nums = [-2, 0, 3, 8]
Output: 4
Explanation: No value repeats, so every number counts.

 

Constraints:

  • nums has at least one number.
  • Every number is between -109 and 109.
STEP 1 OF 4
    Ctrl + Enter to check

    GO · SETS

    Unique Count in Go, explained

    Problem overview

    The function uniqueCount takes a slice of integers, nums, and returns how many different values it contains. A value that appears several times counts once. For [4, 7, 4, 1, 7] the different values are 4, 7 and 1, so the answer is 3.

    Approach: a set

    A set is a collection that holds each value at most once. Adding a value that is already inside changes nothing, and checking whether a value is inside is fast. If you put every number of nums into a set, the set's size is the number of different values.

    Go has no built-in set type. The usual stand-in is a map whose keys are the values and whose values are bool. A map can't hold the same key twice, which is exactly the property a set needs. Each present value is stored as true; the booleans themselves carry no extra information.

    Step by step

    1. Create the set. unique := map[int]bool{} is empty: nothing has been added.
    2. Loop over nums with for _, num := range nums. The numbers go in one at a time; Go can't build the map from a slice in a single step.
    3. Add each number. unique[num] = true adds the key if it is new, and rewrites true over true if it is already there.
    4. Return the size. len(unique) is the number of keys, so it is the number of different values.

    Tracing the example

    For [4, 7, 4, 1, 7], the size of unique after each number is 1, 2, 2, 3 and 3. The second 4 and the second 7 don't add a key, so the size doesn't change. At the end the map is map[1:true 4:true 7:true] and len(unique) is 3.

    The solution in Go

    func uniqueCount(nums []int) int {
        unique := map[int]bool{}
        for _, num := range nums {
            unique[num] = true
        }
        return len(unique)
    }
    

    Go details worth knowing

    • len works on maps. It returns the number of keys.
    • Other set spellings. Some Go programmers use map[int]struct{} for sets, because struct{} takes no space; the values are then written as struct{}{}. The bool version reads more simply, and a membership test is just if unique[x], since a missing key reads as false.
    • Time and space. One pass with constant-time average map operations is O(n), and the set holds at most one key per distinct value, so the extra space is O(n).

    Why a set and not a slice

    You could keep a slice of the values seen so far and, for each number, scan the slice to check whether it is already there. That works, but it costs a scan per number: O(n²) overall. Looking a key up in a map doesn't scan, so the set keeps the whole job to one pass. For a membership test, unique[x] is true for a value that was added and false otherwise, and reading it doesn't add anything.

    Edge cases and common mistakes

    • All equal. [5, 5, 5] gives 1.
    • No repeats. [-2, 0, 3, 8] gives 4. Negative numbers and zero are ordinary keys.
    • Returning len(nums). That counts the repeats too.
    • Returning inside the loop reports the size after the first number only, which is 1.
    • Counting true values by hand. It is not needed: every key in the map is stored as true, so len gives the answer directly.

    Testing

    • [4, 7, 4, 1, 7] returns 3.
    • [5, 5, 5] returns 1.
    • [-2, 0, 3, 8] returns 4.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free