Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I efficiently determine if two lists contain elements ordered in the same way?

I have two ordered lists of the same element type, each list having at most one element of each value (say ints and unique numbers), but otherwise with no restrictions (one may be a subset of the other, they may be completely disjunct, or share some elements but not others).

How do I efficiently determine if A is ordering any two items in a different way than B is? For example, if A has the items 1, 2, 10 and B the items 2, 10, 1, the property would not hold as A lists 1 before 10 but B lists it after 10. 1, 2, 10 vs 2, 10, 5 would be perfectly valid however as A never mentions 5 at all, I cannot rely on any given sorting rule shared by both lists.

like image 672
SoftMemes Avatar asked Oct 23 '10 20:10

SoftMemes


People also ask

How do you know if two lists contain the same element?

So, to check if two lists are equal or not, we can create Counter objects from both the lists and then compare them to check if both lists contain similar unique elements with the same frequency.

How do you compare two lists with the same value?

Using Counter() , we usually are able to get frequency of each element in list, checking for it, for both the list, we can check if two lists are identical or not.

How can you tell if two ArrayList has the same element?

You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.

How do you check if two elements in a list are the same Python?

A straightforward way to check the equality of the two lists in Python is by using the equality == operator. When the equality == is used on the list type in Python, it returns True if the lists are equal and False if they are not.


1 Answers

You can get O(n) as follows. First, find the intersection of the two sets using hashing. Second, test whether A and B are identical if you only consider elements from the intersection.

like image 165
jonderry Avatar answered Oct 12 '22 22:10

jonderry