Start learning free

LESSON 237 OF 292 · SETS

Common Count in Swift: Sets and contains

Practice Read the full explanation

Given two arrays of integers, a and b, return how many different values appear in both of them.

A value counts only once, however many times it appears in a or in b.

 

Example 1:

Input: a = [1, 2, 3, 4], b = [3, 4, 5]
Output: 2
Explanation: 3 and 4 are in both. 1 and 2 are only in a, and 5 is only in b.

Example 2:

Input: a = [7, 7, 8], b = [7, 9, 7]
Output: 1
Explanation: 7 is the only value in both. It appears twice in each, but it counts once.

Example 3:

Input: a = [1, 2], b = [3, 4]
Output: 0
Explanation: No value is in both.

 

Constraints:

  • a and b each have at least one number.
  • Every number is between -109 and 109.
STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · SETS

    Common Count in Swift, explained

    Problem overview

    The method commonCount receives two arrays of integers, a and b, and returns how many different values appear in both. A value counts once, however many times it shows up in either array.

    With a = [1, 2, 3, 4] and b = [3, 4, 5] the answer is 2: the values 3 and 4 are in both. With a = [7, 7, 8] and b = [7, 9, 7] the answer is 1, because 7 is the only shared value and it counts once even though it appears twice on each side. With a = [1, 2] and b = [3, 4] nothing is shared, so the answer is 0.

    Approach

    Two ideas are needed: fast membership checks and counting each value once. A Set gives both. Asking an array whether it contains a value means scanning it, but asking a set is fast on average, because a set is a hash table. And a set never stores the same value twice, so inserting a value that is already there changes nothing.

    The plan: put the values of a into a set, then walk through b. Each value of b that is in that set belongs to both arrays, so it goes into a second set, common. The size of common is the answer. If 7 appears many times in b, it is inserted many times but stored once.

    Step by step

    1. Build a set from a. Set(a) turns the array into a set, dropping duplicates. The constant is called setA, and let is enough because it never changes.
    2. Create an empty result set. Set<Int>() needs its element type written out, since there is nothing to infer it from. It is a var because values are added to it.
    3. Loop over b. Each value is called num.
    4. Test and insert. If setA.contains(num) is true, the value is in both arrays, so common.insert(num).
    5. Return common.count. The count of a set is the number of distinct values in it.

    The solution in Swift

    class Solution {
        func commonCount(_ a: [Int], _ b: [Int]) -> Int {
            let setA = Set(a)
            var common = Set<Int>()
            for num in b {
                if setA.contains(num) {
                    common.insert(num)
                }
            }
            return common.count
        }
    }
    

    Swift details worth knowing:

    • Set(a) works because Int is Hashable. The element type is inferred from the array, so the result is a Set<Int>.
    • insert is safe to repeat. Inserting a value that is already in the set leaves the set unchanged, so no check is needed before it.
    • _ in the signature means callers pass the arguments without labels: commonCount([1, 2], [2, 3]).
    • The result of insert is a tuple saying whether the value was new. Swift marks it as discardable, so ignoring it produces no warning.

    Complexity

    Time is O(n + m) on average, where n and m are the lengths of a and b: building setA visits every value of a once, and the loop makes one set lookup per value of b. Space is O(n + m) in the worst case, for the two sets.

    Edge cases and common mistakes

    • Counting matches instead of distinct values. A counter that goes up for every value of b found in a returns 2 for a = [7, 7, 8], b = [7, 9, 7]. The expected answer is 1, which is why common is a set.
    • Duplicates in a only. They disappear when Set(a) is built, so they cause no trouble.
    • Repeated values in b only. a = [5, 5, 5] and b = [5] give 1.
    • No overlap. The loop never inserts anything, and common.count is 0.

    Testing

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