• Create Account

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

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

11 replies to this topic

### #1GuyWithBeard  Members   -  Reputation: 1541

Like
0Likes
Like

Posted 24 April 2014 - 11:16 PM

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!

### #2Ashaman73  Crossbones+   -  Reputation: 13447

Like
0Likes
Like

Posted 25 April 2014 - 12:08 AM

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

Edited by Ashaman73, 25 April 2014 - 12:47 AM.

Ashaman

### #3fastcall22  Crossbones+   -  Reputation: 9058

Like
2Likes
Like

Posted 25 April 2014 - 12:19 AM

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, 25 April 2014 - 12:36 AM.

gzip: H4sIAAAAAAAEAG1QTUvEMBC991e8nvaiFfYoS7yo sLCo6MnjtJ1ugmkiyWRL/72z3T1YEQIJ8z4zA2Xp yPvt1qBpGrRFIJZkk9FyRyUzHCbKIHgn4hnZOrm1 TD0mG0HCCs+QGDGWziKXI6Wm2n++GYwUVH2mrGEE PnGCVQ8K8+JYfXA6URDEQfMZh5h6g5eoAlWJdeEI bbH2qYZf7XMUfw8f/Q0oMeZYNL9/WHF0uFEshvMr XYujd9SycFb+F18QcSOvlJauZ8ejqevdnV7/d550 e0t6prmunh73Bu+vz4c/XUeOQXfJgvKNkhf95U8/ Dtgmy5IBAAA=

### #4SeraphLance  Members   -  Reputation: 2358

Like
1Likes
Like

Posted 25 April 2014 - 12:26 AM

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, 25 April 2014 - 12:27 AM.

### #5GuyWithBeard  Members   -  Reputation: 1541

Like
0Likes
Like

Posted 25 April 2014 - 12:50 AM

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).

### #6Bacterius  Crossbones+   -  Reputation: 12913

Like
1Likes
Like

Posted 25 April 2014 - 01:11 AM

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!

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

### #7fastcall22  Crossbones+   -  Reputation: 9058

Like
2Likes
Like

Posted 25 April 2014 - 01:32 AM

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, 25 April 2014 - 01:41 AM.

gzip: H4sIAAAAAAAEAG1QTUvEMBC991e8nvaiFfYoS7yo sLCo6MnjtJ1ugmkiyWRL/72z3T1YEQIJ8z4zA2Xp yPvt1qBpGrRFIJZkk9FyRyUzHCbKIHgn4hnZOrm1 TD0mG0HCCs+QGDGWziKXI6Wm2n++GYwUVH2mrGEE PnGCVQ8K8+JYfXA6URDEQfMZh5h6g5eoAlWJdeEI bbH2qYZf7XMUfw8f/Q0oMeZYNL9/WHF0uFEshvMr XYujd9SycFb+F18QcSOvlJauZ8ejqevdnV7/d550 e0t6prmunh73Bu+vz4c/XUeOQXfJgvKNkhf95U8/ Dtgmy5IBAAA=

### #8duckflock  Members   -  Reputation: 1286

Like
2Likes
Like

Posted 25 April 2014 - 03:06 AM

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.

### #9GuyWithBeard  Members   -  Reputation: 1541

Like
0Likes
Like

Posted 25 April 2014 - 04:13 AM

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.

### #10SeraphLance  Members   -  Reputation: 2358

Like
0Likes
Like

Posted 25 April 2014 - 10:53 AM

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.

### #11Pink Horror  Members   -  Reputation: 2450

Like
0Likes
Like

Posted 25 April 2014 - 05:24 PM

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.

### #12alnite  Crossbones+   -  Reputation: 3049

Like
-1Likes
Like

Posted 25 April 2014 - 05:35 PM

edit: ok. apparently I misread the question.

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


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, 26 April 2014 - 05:28 PM.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

PARTNERS