I have a (potentially very large) array of users. I want to remove a specific user from this array, if the user is contained within it. Here is my code:
if users.contains(user) {
users = users.filter { $0.id != user.id }
count -= 1
change -= 1
}
Thinking about this in terms of time and space complexity, contains() is a O(n) operation, and filter() is also a O(n) operation.
I could do this:
for (index, user) in users.enumerated() {
if user == userToRemove {
users.remove(at: index)
count -= 1
change -= 1
}
}
But here remove(at:) is a O(n) operation, as is the for-loop. So in both cases, I'm having to loop through the whole array twice.
Another thing I could do is convert it to a Set beforehand, but that would the lose the ordering.
Is there any way to improve on the efficiency of this such that it only has to loop through at most once?
CodePudding user response:
Assuming that you want unique users, you could just use a Set, whose contains is O(1).
If you need the users to be ordered, you can use OrderedSet from the Swift Collections package.
