I have 2 lists of strings
List1 = [["Hey there"], ["hi"], ["hello"]]
List2 = [["hi"], ["hello"]]
Is there a O(n) way to remove elements of List2 from List1?
Desired output = [["Hey there"]]
I have 2 lists of strings
List1 = [["Hey there"], ["hi"], ["hello"]]
List2 = [["hi"], ["hello"]]
Is there a O(n) way to remove elements of List2 from List1?
Desired output = [["Hey there"]]
You can do this with two O(n) steps:
List2_set = set(map(tuple, List2))
List1_filtered = [row for row in List1 if tuple(row) not in List2_set]
Convert the list of items to exclude to a set of tuples
set is required because checking membership for sets is O(1) instead of O(n)tuple is required for set items instead of list, because tuple is hashableCheck membership for each element of List1
set collection uses a hash table to allow O(1) membership testingThe total then is O(n) + O(n) => O(n), that is, the performance is linear with number of total elements of List1 + List2.