← All lessonsUnit 1 · Swift for problems
Lesson 1.5

A set

A set says whether a value is there in one step, however many values it holds, and it keeps no order and no repeats.

Reach for it when
You only need to know whether something is there.
The move
insert, contains, Set(array). No order and no repeats.
Cost
insert and contains are one step, on average.

The idea

Harper

My friend's code passed its test on Monday and failed it on Tuesday. Nobody touched it in between.

Arthur

Then somebody touched it.

Harper

Nobody. We'll come back to it. You're at a party. A thousand guests are standing in one long line. Is Ada here?

Arthur

I walk along the line and read every name badge until I find hers.

Harper

And if she stayed at home?

Arthur

Then I find that out at the far end, a thousand badges later.

Harper

That's an array. Now the cloakroom. A wall of hooks, and every name has one hook that is its own. Ada's coat can only ever hang on Ada's hook. Is Ada here?

Arthur

I go to her hook and look. Coat or no coat. One look.

Harper

And with a million guests?

Arthur

A longer wall, and the same one look. I never see anybody else's coat.

Harper

That's a set. How do you know which hook is hers?

Arthur

Her name tells me. That is the whole trick: the value itself says where to look.

Harper

Ada turns up a second time, with a second coat.

Arthur

Her hook is taken, so the second coat goes nowhere. However often she turns up, she is on the wall once.

Harper

Who got here first?

Arthur

The wall can't say. The hooks are where the builder put them, not in the order the evening went.

Harper

Read me the coats anyway, from left to right.

Arthur

I can. It will be an order. It won't be the order they arrived in, and tomorrow night's wall could give you a different one.

Harper

So what does the one look cost me?

Arthur

Order and repeats. If you need either, you wanted the line.

Harper

My friend wanted the one look and the order.

Arthur

On a Tuesday, I assume.

That is the whole tool: a set answers one question, is this value there?, in one step however many values it holds. It pays for that with the two things the wall cannot do: it keeps no order, and it holds each value once.

The shape

This is what you know by heart:

Swift
/// Whether `wanted` is one of `numbers`.
func isThere(_ wanted: Int, in numbers: [Int]) -> Bool {
    var seen = Set<Int>()                // an empty set: a wall of free hooks
    for number in numbers {
        seen.insert(number)              // hang each number on its own hook
    }
    return seen.contains(wanted)         // one look at one hook
}

It has three parts, and each is there for a reason.

A set can hold whole numbers, characters or strings: any type where Swift can work out the hook from the value. Swift calls such a type Hashable. The five vowels in the lesson "A string as an array of characters" were a set of characters.

An array has contains too, and it gives the same answers. What differs is how it finds them. The array is the line. It starts at the front and compares wanted with one number after another, until it finds it or runs out of numbers. The set is the wall. It works out which hook to look at, and looks.

The lesson's code counted the comparisons. It put the numbers 1 to 1,000 into an array and into a set, and asked each of them the same hundred questions, about numbers spread evenly from the front of the line to the back. Then it did the same with the numbers 1 to 100,000. These are the averages for one question.

numbers heldthe array compared wanted withthe set compared wanted with
1,000505 numbersbetween 1 and 2 numbers
100,00050,500 numbersbetween 1 and 2 numbers

On average the array's walk ended halfway along the line. So a hundred times as many numbers cost the array a hundred times as many comparisons. They cost the set nothing more. That is the reason to use a set at all.

The set's figure is not exactly 1 because, now and then, two values are given the same hook, and the set has to look at the next hook along as well. So its cost is one step on average. What matters is that it does not grow with the set.

Watch it run

The numbers are 7, 3, 7, 9 and 3, and wanted is 9. Here is seen before and after each insert. A set has no order of its own, so the table writes its values smallest first, to give you something steady to read.

numberseen beforehook free?seen after
7[]yes[7]
3[7]yes[3, 7]
7[3, 7]no[3, 7]
9[3, 7]yes[3, 7, 9]
3[3, 7, 9]no[3, 7, 9]

Then comes the one look: seen.contains(9) is true. Had wanted been 4, it would be false.

Look at the third row. The second 7 goes to a hook that is already taken, so seen after is the same as seen before. Five numbers went in, and the set holds 3. Step 2 counts on that row, and step 3 asks insert about it.

Step by step

Step 1

Insert values and ask whether one is there

This step is the shape itself, written from an empty function. What is new is everything: an empty set, insert and contains.

For one question the set is no quicker than the array's own contains, because filling the set was already a walk along the whole line. A set earns its place when the questions keep coming. Fill it once, then ask it as often as you like:

Swift
/// For each question, whether that number is one of `numbers`.
func areThere(_ questions: [Int], in numbers: [Int]) -> [Bool] {
    var seen = Set<Int>()
    for number in numbers {              // walk the line once, to fill the wall
        seen.insert(number)
    }
    var answers: [Bool] = []
    for question in questions {          // then one look for each question
        answers.append(seen.contains(question))
    }
    return answers
}

For the questions 9, 4 and 7, asked of 7, 3, 7, 9, 3, this gives [true, false, true]. The line was walked once, to fill the wall. After that each answer cost one look.

This step has two problems. The first is the shape. The second is this function, and one of its checks has 100,000 numbers, 100,000 questions and a clock. With a set it passes at once. Asking the array each time means 100,000 walks, and that is far too slow to pass.

Step 2

How many different values an array holds

Swift
/// How many different values `numbers` holds.
func countOfDifferent(_ numbers: [Int]) -> Int {
    let different = Set(numbers)         // the whole array, hung up in one go
    return different.count               // each value is there once
}

What is new: Set(numbers) makes a set from a whole array in one go. It is the loop of step 1, written for you.

Each value is on the wall once, however many times it came, so count is the number of different values. For 7, 3, 7, 9, 3 it is 3. For 4, 4, 4 it is 1, and for an empty array it is 0.

The array went into the set, and two things did not go with it: the repeats and the order. count needs neither. But when a problem wants the values themselves back, somebody has to choose an order for them, because the set has none to offer:

Swift
/// The different values of `numbers`, each once, smallest first.
func differentValues(_ numbers: [Int]) -> [Int] {
    let different = Set(numbers)
    return different.sorted()            // a set has no order, so give it one
}

sorted() hands back the set's values as an array, smallest first: [3, 7, 9] here. The next lesson, "Sorting by a key", is about sorted(). In this lesson it has one job, which is to make the answer the same every time. This step's second problem asks for this function. Its third gives you the function with a wrong last line, to mend. In the rest of this lesson, a problem that wants a set's values back says smallest first, and its last line is sorted().

Step 3

What insert hands back: it says whether the value was new

The trace had a column called hook free?. insert can fill in that column itself. It hands back a pair of things, and the one that problems use is called inserted: true when the hook was free and the value went in, false when the value was there already and nothing changed.

Swift
/// For each number, whether it was new to the set when it went in.
func wasNew(_ numbers: [Int]) -> [Bool] {
    var seen = Set<Int>()
    var answers: [Bool] = []
    for number in numbers {
        let isNew = seen.insert(number).inserted     // true when the hook was free
        answers.append(isNew)
    }
    return answers
}

For 7, 3, 7, 9, 3 this gives [true, true, false, true, false], which is the trace's column again.

What is new: insert answers "was it new?" as it inserts. You could ask first and insert second instead:

Swift
func wasNewInTwoLooks(_ numbers: [Int]) -> [Bool] {
    var seen = Set<Int>()
    var answers: [Bool] = []
    for number in numbers {
        if seen.contains(number) {       // one look
            answers.append(false)
        } else {
            seen.insert(number)          // a second look, at the same hook
            answers.append(true)
        }
    }
    return answers
}

It gives the same answers, [true, true, false, true, false]. But it goes to the same hook twice, once to look and once to hang, and the look has to come before the hanging. insert was going to that hook anyway, so let it say what it found.

This step's second problem gives you a version that asks at the wrong moment, for you to mend.

Step 4

The values in one set and not in another (subtracting)

Two walls now. On first hang 1, 2, 3 and 4. On second hang 2, 4 and 6.

Swift
/// The values that are in `first` and not in `second`, smallest first.
func onlyInFirst(_ first: Set<Int>, _ second: Set<Int>) -> [Int] {
    let remaining = first.subtracting(second)        // a new set: `first` is not changed
    return remaining.sorted()
}

What is new: first.subtracting(second) is a new set that holds every value of first that is not in second. For these two it holds [1, 3]. Neither first nor second is changed.

The function takes two sets, and you can still call it with square brackets: onlyInFirst([1, 2, 3, 4], [2, 4, 6]). Swift sees that sets are wanted and makes them.

Which set you start from matters. second.subtracting(first) asks the other question, what is in second and not in first, and its answer is [6]. This step's second problem is a function that asks the wrong one of the two.

Step 5

The values in both (intersection)

Swift
/// The values that are in both sets, smallest first.
func inBoth(_ first: Set<Int>, _ second: Set<Int>) -> [Int] {
    let shared = first.intersection(second)          // a new set, again
    return shared.sorted()
}

What is new: first.intersection(second) is a new set that holds the values that hang on both walls. For the same two sets it holds [2, 4].

This one is the same whichever set you start from: second.intersection(first) also holds [2, 4]. When the two sets share nothing, the answer is an empty set, and sorted() makes an empty array of it: for 1, 2 and 3, 4 the function gives [].

Step 6

Are two sets equal?

Swift
/// Whether the two arrays hold the same values, in any order and any number of times.
func sameValues(_ first: [Int], _ second: [Int]) -> Bool {
    return Set(first) == Set(second)     // equal when each holds what the other holds
}

What is new: == between two sets. It is true when each set holds exactly the values the other holds. Nothing else could matter: there is no order to differ in, and no value is there twice.

So 7, 3, 7, 9, 3 and 9, 7, 3 hold the same values: the function says true. As arrays those two are not equal, and == between them says false, because an array also compares order and repeats. For 7, 3 against 3, 7, 9 the function says false: one wall has a hook taken that is free on the other.

What goes wrong

Counting on an order.

Swift
func differentValuesInNoOrder(_ numbers: [Int]) -> [Int] {
    let different = Set(numbers)
    return Array(different)              // wrong: whatever order the wall has them in
}

Array(different) takes the values in whatever order the wall has them, and so do for value in different and different.first. That is not the order they went in, and it is not the same on every run. The lesson's code made 200 sets, each from 7, 3, 7, 9, 3, and turned every one into an array this way. The arrays came out in 6 different orders, which is every order three values can stand in. With sorted() in place of Array(...), the number of different orders was 1. When values leave a set and anyone will look at their order, sort them.

Asking the line. numbers.contains(wanted) is right, and it is a walk. Inside a loop it is a walk on every pass. In the table above the array compared wanted with 50,500 numbers for each question, and the set with between 1 and 2. When the question will be asked more than once, fill a set first.

Square brackets alone make an array.

Swift
let asSet: Set<Int> = [2, 3, 5, 7]       // a set, because the type says so
let asArray = [2, 3, 5, 7]               // an array: brackets alone make an array

The first is a Set<Int> and the second is an Array<Int>. Both answer contains, and the second one walks. A set has to have its type said, or Set(...) put round it.

Asking after inserting.

Swift
func wasNewAskedTooLate(_ numbers: [Int]) -> [Bool] {
    var seen = Set<Int>()
    var answers: [Bool] = []
    for number in numbers {
        seen.insert(number)
        answers.append(!seen.contains(number))       // wrong: it went in one line ago
    }
    return answers
}

For 7, 3, 7, 9, 3 this gives [false, false, false, false, false]. Every number is already on its hook when the question is asked, so nothing ever looks new. With inserted this cannot happen, because the asking and the hanging are one call.

Subtracting the wrong way round. first.subtracting(second) and second.subtracting(first) are different sets: [1, 3] and [6] in step 4. Say the sentence before you type it: in this one and not in that one. The set you start from is "this one".

Asking a set how many times. A set knows that 7 is there. It does not know that 7 came twice: three 4s make a set that holds 1 value. When how often matters, you want a dictionary that counts, from the lesson "A dictionary with a default".

Say it back

1

What question does a set answer, and what does the answer cost?

Show the answerHide the answer

"Is this value there?" One look at one hook, on average, however many values the set holds. An array has to walk its line.

2

What does a set give up for that?

Show the answerHide the answer

Order and repeats. It holds each value once, and it cannot say which came first.

3

How do you find how many different values an array holds?

Show the answerHide the answer

Set(numbers).count. Set(numbers) hangs each value up once, and count is how many hooks are taken.

4

What does insert hand back, and what does that save you?

Show the answerHide the answer

seen.insert(value).inserted is true when the value was new, and false when it was already there. It saves a separate contains, which would go to the same hook a second time.

5

first holds 1, 2, 3, 4 and second holds 2, 4, 6. What do first.subtracting(second) and first.intersection(second) hold?

Show the answerHide the answer

[1, 3] and [2, 4]. The first answer changes if you swap the two sets. The second does not.

6

When are two sets equal?

Show the answerHide the answer

When each holds exactly the values the other holds. Order and repeats cannot matter, because a set has neither.

7

Why did the code pass on Monday and fail on Tuesday, with nobody touching it?

Show the answerHide the answer

Its last line was return Array(different), and the test wanted the values in one order. A set has no order, so the array came out one way on Monday's run and another way on Tuesday's. different.sorted() comes out the same way on every day of the week.

Practise

These are this lesson's problems in the Orithms app, in the order they come.

ProblemLevel
1Is it there?Easy
2One set, many questionsEasy
3How many different values?Easy
4The different values, smallest firstEasy
5Passed on Monday, failed on TuesdayEasy
6Was it new?Easy
7Nothing is ever newEasy
8In the first set and not in the secondEasy
9Who stayed away?Easy
10In both setsEasy
11Do they hold the same values?Easy

These problems are done in the Orithms Mac app.

Every piece of code and every number in a lesson comes from a file that was compiled and run.