Middle
How to quickly check if one collection is contained in another: using an array or a set?
sobes.tech AI
Answer from AI
Set (Множество) is faster for checking element inclusion.
Explanation:
- Array: Checking if an element is included in an array takes O(n) time on average, where n is the number of elements. To check if one collection is included in another, n iterations are needed, each of which is O(m), where m is the size of the second collection. Total: O(n*m).
- Set: Checking if an element is included in a set takes O(1) time on average. To check if one collection is included in another, n iterations are needed, each of which is O(1). Total: O(n).
Example with a set:
- Create a
Setfrom the first collection. - Iterate over the second collection, checking each element for inclusion in the created
Set.
let collection1: [Int] = [1, 2, 3, 4, 5]
let collection2: [Int] = [2, 4]
// Create a set from collection1
let set1 = Set(collection1)
// Check if collection2 is a subset of collection1
let isSubset = collection2.allSatisfy { set1.contains($0) }
print(isSubset) // Will output true