Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the difference between two slices of strings

Tags:

go

Here is my desired outcome

slice1 := []string{"foo", "bar","hello"} slice2 := []string{"foo", "bar"}  difference(slice1, slice2) => ["hello"] 

I am looking for the difference between the two string slices!

like image 770
samol Avatar asked Oct 15 '13 05:10

samol


1 Answers

Assuming Go maps are ~O(1), here is an ~O(n) difference function that works on unsorted slices.

// difference returns the elements in `a` that aren't in `b`. func difference(a, b []string) []string {     mb := make(map[string]struct{}, len(b))     for _, x := range b {         mb[x] = struct{}{}     }     var diff []string     for _, x := range a {         if _, found := mb[x]; !found {             diff = append(diff, x)         }     }     return diff } 
like image 99
peterwilliams97 Avatar answered Oct 17 '22 13:10

peterwilliams97