# Fastest way to get elements in one list but not in other and vice versa

This topic is 1364 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi,

There might be a term for this (list intersection?) but I am not sure so lets open it up a little bit.

I have two lists of integers, A and B. I need a fast way to get two new lists based on the elements in them. One of the new lists should contain all elements found in A but not in B, and the other list should contain all elements found in B but not in A. Since I am not really sure what to call this, I am having a hard time finding good info on it online.

I am looking for a general algorithm or best practice on how to do this sort of thing. If it matters, I am using C# for this. The length of the lists are usually quite small (less than 50 elements) but the algorithm needs to be quick since I need to do it every 10 frames or so.

I can think of a brute force way to do it, but is there anything faster?

Cheers!

##### Share on other sites

Oppps, delete, fastcall22 is right, it doesnt work for single elements.

Edited by Ashaman73

##### Share on other sites
Ashaman, I don't think that works. Consider A=[1,2,3,110,115] and B=[100,200]. With your code, A-B = [1,2,3] and B-A = [200]; the expected differences should be A and B respectively.

If linq is an option, you can use the Except filter:
List<int> a = new List<int>();
List<int> b = new List<int>();

for ( int i = 3; i <= 6; ++i )
for ( int i = 5; i <= 8; ++i )

IList<int> a_without_b, b_without_a;
a_without_b = a.Except(b).ToList();
b_without_a = b.Except(a).ToList();

foreach ( IList<int> l in new IList<int>[]{a_without_b,b_without_a})
Console.WriteLine(string.Join(",", l.Select(x=>x.ToString()).ToArray()));

Sample with output Edited by fastcall22

##### Share on other sites

http://msdn.microsoft.com/en-us/library/bb397894.aspx

Essentially the C# version of the standard library algorithm fastcall22 listed.

LINQ is magic.

EDIT:  More specifically, it's the Except function you want.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx

Edited by SeraphLance

##### Share on other sites

Thank you so far!

Yeah Ashaman's solution probably does not work in this situation since the lists are overlapping and can contain holes etc. Unfortunately, I cannot rely on LINQ in this case either as I am using Unity for mobile and it limits what I can do with LINQ (eg. runtime JIT required in most cases).

##### Share on other sites

Well, you could just reimplement Except using the standard approach (it will likely be fast enough, for 50 items every 10 frames even the naive method would do it even on mobile I think), but theoretically it can be done in O(n log n) time by using the following approach:

1. sort lists a and b [O(n log n)]

2. for every element in a, check if it exists in list b via binary search, and same for b [n * O(log n) => O(n log n)]

And, if you don't mind using some extra memory, it can in fact be done in O(n) time, by replacing the sort and binary search with a lookup into a hash table:

1. put every element of a and b in hash tables Ha, Hb [n * amortized O(1) => O(n)]

2. for every element in a, check if it exists in Hb, and same for b [n * amortized O(1) => O(n)]

Astute readers will notice this is actually the naive algorithm, just implemented using a HashSet and its Contains method, because HashSets are awesome.

If the order of the resulting list needs to reflect the order of the two original lists, then you must iterate in the order of the original lists in step 2 (which will require making a copy of the list to sort it in the first case, otherwise you lose the order). But you didn't mention if this was the case, and if it isn't, then it just becomes a straightforward set intersection!

##### Share on other sites
Bacterius, we can eliminate binary searching altogether since accessing the elements in both lists are sequential:
IList<int> a, b;
a.Sort();
b.Sort();

List<int> a_without_b = new List<int>();
List<int> b_without_a = new List<int>();

int bdx = 0;
while ( adx < a.Count && bdx < b.Count ) {
int bb = b[bdx];
if ( aa < bb ) {
} else if ( bb < aa ) {
bdx++;
} else {
bdx++;
}
}
for ( ; bdx < b.Count; ++bdx )

It should be the fastest out of all proposed solutions, as it doesn't make unnecessary iterations through binary search, and it doesn't occur any of the associated costs with hashing collisions. Of course, this is assuming both lists are sorted before hand; it could be that the HashSet approach might be faster if it takes less time than the sorting of both lists in this approach. Edited by fastcall22

##### Share on other sites

There might be a term for this (list intersection?) but I am not sure so lets open it up a little bit.

I have two lists of integers, A and B. I need a fast way to get two new lists based on the elements in them. One of the new lists should contain all elements found in A but not in B, and the other list should contain all elements found in B but not in A. Since I am not really sure what to call this, I am having a hard time finding good info on it online.

The elements that are in A and not in B are called the difference of A and B, written A \ B ( see wikipedia Complement ).

To my knowledge there is no mathematical term for both sets; it is simply A \ B and B \ A.

On another note I will bite the bullet and ask you why you are concerned about performance given your description:

• Lists contain integers (cheap comparison)
• Less than 50 elements per list (small data set)
• Needs to be done every ~10th frame (low call amount)

Mobile devices aren't that slow nowadays. Converting the lists to sets and performing two difference operations shouldn't matter if you only do it every 10th frame.

##### Share on other sites

Valid question, duckflock. In this case I could probably do it the brute force way (which is actually not that different from the code fastcall22 posted, I need to test that, thanks man!), but this is not the first time I have come across this problem and sometimes the conditions haven't been so forgiving. That's why I was wondering if there is some defacto way to do this, even for complicated cases.

##### Share on other sites

Valid question, duckflock. In this case I could probably do it the brute force way (which is actually not that different from the code fastcall22 posted, I need to test that, thanks man!), but this is not the first time I have come across this problem and sometimes the conditions haven't been so forgiving. That's why I was wondering if there is some defacto way to do this, even for complicated cases.

Any set difference implementation that relies on sorted lists is probably going to look something like that.  Any set difference implementation that doesn't rely on sorted lists is probably going to be slower, standard library or otherwise.

Standard library functions tend to be very fast for their given constraints, but if you have stronger constraints (like a sorted list in this case), it's not hard to beat them.

##### Share on other sites

Valid question, duckflock. In this case I could probably do it the brute force way (which is actually not that different from the code fastcall22 posted, I need to test that, thanks man!), but this is not the first time I have come across this problem and sometimes the conditions haven't been so forgiving. That's why I was wondering if there is some defacto way to do this, even for complicated cases.

There's a pretty big difference in complexity between a brute force method and what fastcall22 posted. Maybe the code is somewhat similar, but that's all the more reason to not use the brute force method, because you're not saving yourself much programming time by going that way. You might as well implement it the proper way.

##### Share on other sites

edit: ok. apparently I misread the question.

[source]

std::vector<T> difference(const std::vector<T>& A, const std::vector<T>& B) {

std::vector<T> result(std::max(A.size(), B.size());

for (auto &e : A) {

if (std::find(B.begin(), B.end(), e) == B.end()) {

result.push_back(e);

}

}

return result;

}

difference(A, B); // A - B

difference(B, A); // B - A

[/source]

Possible optimizations:

• Sorted A and B can use binary search.
• Only perform this operation when A/B change.  If you can identify a part in your code where A and B change, you can minimize the recalculation.
Edited by alnite