What is the big O when I subtract two sets?

3.2k Views Asked by At

If I have two non-empty sets of equal lengths, B and A, what is the big O time to subtract B from A (B-A; length(B) == length(A))? I think it is either O(n) or O(1), but not sure which one.

Also, would this question be more appropriate for Stack Overflow?

1

There are 1 best solutions below

3
On

Assuming that by subtraction you mean the set difference operator, if n=A.length, then this would take O(n^2) time. This is because for every element in A, you must compare it to every element in B to determine if the elements are the same and that element can be removed from B. In the worst case, the intersection of A and B is empty, so you will need to compare n elements from A against n elements from B, leading to a runtime of O(n^2).