Swift's map and filter functions time complexity

All higher-order functions in the Swift standard library, such as map, flatMap/compactMap, filter and reduce have O(n) time complexity in general, since all of them work on the full collection they're called on and they visit each element exactly once, so they have linear time complexity.

Taking this into consideration, your first implementation has O(J*S) time complexity, since for every element in J you iterate through all elements of S using filter.

Your second implementation on the other hand has roughly linear time complexity depending on which String has more Characters in it, S or J, its time complexity is O(J) or O(S), since you don't have any nested loops, you only iterate through J and S sequentially.

Whether Implementation 1 or 2 is more efficient depends on the size of J and S completely.


flatMap / compactMap take O(m + n), where n is the length of this sequence and m is the length of the result.

This is written in iOS SDK documentation.

Tags:

Ios

Swift