My suggestion would be to slurp the large list into a hash set, then use that to match items from the small list.

A hash set is a structure that stores elements in an indexable memory structure, like an array, where the position of the element is equal to some hash value calculated using the object. That means that looking for a value in the hashset is a relatively fast operation; calculate the hash of the object you're looking for, go to that index, and check the actual objects stored there, which for a good implementation will be a very small number (hashset implementations have to strike a balance between the size of the hash and therefore the number of first-dimension elements, and the number of collisions and therefore the average number of items in each element).

Ideally, hashsets approach a constant lookup time (specifically it's O(log2^HN) where H is the bitsize of the hash function, so for all N < 2^H it's effectively constant), so overall, your matching algorithm would approach linear complexity. Two major downsides are first that unless you have access to a built-in efficient implementation (Java's HashMap is built on this structure, as is .NET's Dictionary class), you have to roll your own which is quite a bit of code, and second, hashsets are real memory hogs because there's virtually guaranteed to be a lot of empty spaces in the array unless your implementation varies its hash function based on expected or actual capacity (which could, if naively done, involve re-hashing every element several times as the first dimension is extended to limit growth in the second dimension).

Answer from KeithS on Stack Exchange
Top answer
1 of 4
11

My suggestion would be to slurp the large list into a hash set, then use that to match items from the small list.

A hash set is a structure that stores elements in an indexable memory structure, like an array, where the position of the element is equal to some hash value calculated using the object. That means that looking for a value in the hashset is a relatively fast operation; calculate the hash of the object you're looking for, go to that index, and check the actual objects stored there, which for a good implementation will be a very small number (hashset implementations have to strike a balance between the size of the hash and therefore the number of first-dimension elements, and the number of collisions and therefore the average number of items in each element).

Ideally, hashsets approach a constant lookup time (specifically it's O(log2^HN) where H is the bitsize of the hash function, so for all N < 2^H it's effectively constant), so overall, your matching algorithm would approach linear complexity. Two major downsides are first that unless you have access to a built-in efficient implementation (Java's HashMap is built on this structure, as is .NET's Dictionary class), you have to roll your own which is quite a bit of code, and second, hashsets are real memory hogs because there's virtually guaranteed to be a lot of empty spaces in the array unless your implementation varies its hash function based on expected or actual capacity (which could, if naively done, involve re-hashing every element several times as the first dimension is extended to limit growth in the second dimension).

2 of 4
9

Sort both lists with an efficient sorting algorithm (or ensure that the lists are "pre-sorted" by whoever/whatever created them).

Then, if the first name in both lists is the same you've found a match, otherwise discard whichever name is "earlier"; and do that until one of the lists are empty.

Some crude pseudo-code:

    do {
        status = compare(shortList[i], longList[j]);
        if(status == EQUAL) {
            // Found match!
            i++;
            j++;
        } else if(status == EARLIER) {
            // No match, discard first entry in short list
            i++;
        } else {
            // No match, discard first entry in long list
            j++;
        }
    } while( (i < shortListEntries) && (j < longListEntries) );
Discussions

java - Algorithm for comparing two lists - Stack Overflow
I have a list of objects that I am displaying on the screen. The user can change them as they like, and then hit submit. In the submit method I am taking the original list, which I stored, and the More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 24, 2017
Python algorithm to compare two sorted lists and count how many elements are the same - Stack Overflow
I have to design an algorithm that compares two sorted lists of the same length and return the number of common values between them. So if I have two lists a = [2, 9, 15, 27, 36, 40] and b = [9, 1... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Algorithm to compare two large sets - Computational Science Stack Exchange
An algorithm which achieves this limit (on sorted lists of data) is as follows: Given input sets A,B, each a strictly ascending list. Initialize A\B and B\A as empty lists. Until A or B is empty, compare the heads of both lists If the heads are equal, remove them. More on scicomp.stackexchange.com
๐ŸŒ scicomp.stackexchange.com
Is it faster to find matches between two lists by iterating over the 2nd list over every element in the 1st or by "remembering" stuff from past iterations?
Both of these appear to be O(nm) in worst case (assuming no elements match, and "if a in temp" can be evaluated in constant time with something like a hash map) An alternative algorithm could sort the 2 lists, then iterate through them simultaneously, only moving forward in the lists, never back. This would result in an O(nlogn + mlogm) running time in the worst case. Even better could involve hashing the 2 arrays and checking for a collision. O(m + n) More details would be needed to ensure this is feasible for your problem though. EDIT: Typo in alternative algorithm runtime More on reddit.com
๐ŸŒ r/compsci
18
12
May 16, 2017
People also ask

How do I compare two lists online?
Using our tool to compare two lists is simple. Paste your first list in the 'List A' section and your second list in the 'List B' section, select your separator, and click the 'Compare' button. Our tool will instantly show you items unique to each list, items common to both lists, and a combined set of all items. You can further customize the comparison with options for case sensitivity, whitespace trimming, and more.
๐ŸŒ
comparelists.org
comparelists.org
Compare Lists Online | Free List Comparison Tool
Can I compare Excel lists with this comparison tool?
Yes, our tool is perfect for comparing Excel lists. Simply copy your data from Excel and paste it directly into our comparison tool, or upload your Excel files. The tool automatically processes the data and shows differences, matches, and duplicates between your Excel lists. This works for data exported from any spreadsheet program including Microsoft Excel, Google Sheets, and others.
๐ŸŒ
comparelists.org
comparelists.org
Compare Lists Online | Free List Comparison Tool
Can I compare lists containing special characters or formatted text?
Absolutely. Our list comparison tool handles all types of text content including special characters, formatted text, alphanumeric strings, and international characters. Whether you're comparing product codes, URLs, multilingual content, or data with special formatting, our tool processes everything accurately while preserving the original formatting.
๐ŸŒ
comparelists.org
comparelists.org
Compare Lists Online | Free List Comparison Tool
๐ŸŒ
Medium
medium.com โ€บ swlh โ€บ common-elements-between-two-lists-53cc8588fec8
Common Elements Between Two Lists | by Salil Jain | The Startup | Medium
July 18, 2020 - A brute force method to compare two list has O(k*l) complexity, where k and l is the length of list_a and list_b respectively. If both k and l equal to n then complexity would be O(nยฒ).
๐ŸŒ
Oreate AI
oreateai.com โ€บ blog โ€บ methods-for-comparing-two-lists โ€บ ea623b85b4a9f0df1c00574cdeec0546
Methods for Comparing Two Lists - Oreate AI Blog
December 22, 2025 - Hash Table Comparison Method: A faster alternative that constructs a hash table containing all elements from one list while traversing the other list to check for matches using the hash table lookup process. With a time complexity of O(n), this method offers high efficiency but requires additional memory space for storing the hash table, making it less suitable under memory constraints. Set Operations Comparison Method: Utilizing set operations allows quick calculations such as intersections or unions between two lists based on their unique properties; thus enabling rapid identification of differences or similarities without specific limitations on element counts within either list.
Find elsewhere
Top answer
1 of 2
6

If ordering doesn't matter and all you care about is whether the elements were added or removed, you might want to consider changing your data structures and using Set rather than List. The Set type is specifically designed to determine whether or not elements exist and to do so efficiently, at the cost that you no longer remember the order of the elements.

For example, using HashSet, you could do the following:

Set<T> oldElems = new HashSet<T>(originalList);
Set<T> newElems = new HashSet<T>(currentList);

for (T obj : oldElems) {
    if (!newElems.contains(obj)) {
        /* ... this object was removed ... */
    }
}

for (T obj : newElems) {
    if (!oldElems.contains(obj)) {
        /* ... this object was added ... */
    }
}

Hope this helps!

2 of 2
3

You can do it with one loop, by continuously maintaining the 3-way result list. If you can override equals() to depend on ids, that's fine. If not, check the code under update.

Here's the code, see the explanation below:

List<T> origList = ...;
List<T> newList = ...;

List<T> addedList = new ArrayList<T>();
List<T> deletedList = new ArrayList<T>();
List<T> changedList = new ArrayList<T>();

deletedList.addAll(origList);

for(T t : newList) {
    int origIndex = deletedList.indexOf(t);
    if (origIndex < 0) {
        addedList.add(t);
    } else {
        T origT = deletedList.remove(origIndex);
        if(t.compareTo(origT) != 0) {
            changedList.add(t);
        }
    }
}

Note that I presumed that equals() will check the id, and compareTo() will check all other fields.

Explanation:

You remove all elements from deletedList that were also present in newList, so the result is the deleted items.

You add all new elements to the addedList that were not present in the original list.

If both are present and the objects differ, they'll go to the changedList.

If both are present and the objects are the same then we don't add it anywhere.

Notes:

If new objects have an ID of 0, they will not be present in origList (since we suppose they have been already created).

When I last time implemented this, I created a separate method to compare the objects field-by-field, so I could separate the comparison logic from standard Java methods (actually it was also declared on an interface)

I created this with Lists, but actually you can use it with any type of Collection. Using with List will preserve the original order.

Update:

Try overriding your equals this way (I skipped the typecheck and the casting):

public boolean equals(T other) {
    if (this.id == 0) {
        return this == other;
    }
    return this.id == other.id;
}

The not-yet-created instances are equal to themselves only. The already-created ones are checked by id.

๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ how-to-compare-two-lists-in-python
How to Compare Two Lists in Python | DigitalOcean
July 22, 2025 - For comparing list contents regardless of order, collections.Counter is the most efficient and reliable method as it correctly handles duplicate elements. Leverage Pythonโ€™s set operations (&, -, ^) for a highly efficient way to find common elements, differences, or unique items between two lists.
๐ŸŒ
Comparelists
comparelists.org
Compare Lists Online | Free List Comparison Tool
Our list comparison algorithm provides 100% accuracy in matching and differentiating items between lists.
Top answer
1 of 3
2

Okay if I read your question correctly you want to find common elements in two sorted list of equals lengths and return the number of common elements. I am a little confused by the use of merge here.

Anyways if that is what you want your algorithm to do. Since it is already sorted we can simply iterate over both the lists and find the common elements in linear time.

Algorithm:

  • Let i and j be the indices of a1 and a2 respectively initialized to 0
  • If a1[i] < a2[j] we know that the a1[i] does not exist in a2 as i and j point to the smallest element in the respective arrays. So we move i forward.
  • Same with a2[j] < a1[i].
  • If a1[i] == a2[j] then we have found a common element and we advance both i and j by 1 and continue till the end of either of the array.

the code

def find_common(a1, a2):
    list_len = len(a1)
    a3 = []
    i = j = 0
    while i < list_len and j < list_len:
        if a1[i] < a2[j]:
            i += 1
        elif a2[j] < a1[i]:
            j += 1
        else:
            a3.append(a1[i])    
            i +=1
            j +=1
    return a3

a = [2, 9, 15, 27, 36, 40]
b = [9, 11, 15, 23, 36, 44]
print(find_common(a, b))
2 of 3
1

Using hash table you can solve this in linear time.

You could store one list in a hash table using python dictionary where the key would be the element (in this case an integer) and the value would be the number of occurrences of the element. Running time: O(n)

Then iterate through the other list and do a hash table lookup for each element. Keep a variable for counting the common values. Running time: O(n).

To avoid counting duplicates, as you iterate check if the previous element is the same, in which case move to the next element. You will need an extra variable to keep track of the previous element.

๐ŸŒ
GitHub
github.com โ€บ livoras โ€บ list-diff
GitHub - livoras/list-diff: Diff two lists in O(n). ยท GitHub
Diff two lists in time O(n). I The algorithm finding the minimal amount of moves is Levenshtein distance which is O(n*m).
Starred by 184 users
Forked by 70 users
Languages ย  JavaScript
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ -compare-two-lists-algorithms
How to Compare Two Lists in Programming? - CodingTechRoom
Learn how to effectively compare two lists in programming using algorithms with examples and tips for common mistakes.
๐ŸŒ
List Compare Tool
listcomparetool.com
List Compare Tool โ€” Free Online Diff & Merge
The "Deduplicate" option automatically removes duplicate entries within each individual list before comparing them. This ensures that you are comparing unique sets of items. When "Case Sensitive" is checked, "Apple" and "apple" are treated as different items. If unchecked (default), they are considered equality. "Ordered Mode" uses the Longest Common Subsequence algorithm to find items that appear in both lists in the same relative order, which is useful for comparing versions of code or text.
๐ŸŒ
Quora
quora.com โ€บ What-is-an-effective-method-for-comparing-two-lists-with-multiple-columns-and-thousands-of-entries-in-each-column
What is an effective method for comparing two lists with multiple columns and thousands of entries in each column? - Quora
Answer: Depends on why and what you are comparing but generally you are going to have to walk through the lists until you find a match or a difference. For efficiency I like to compare the largest chunk of data the machine allows. For example if I were comparing 8 bit character strings on a 64bit...
๐ŸŒ
Quora
quora.com โ€บ Which-is-the-best-method-or-algorithm-to-compare-two-large-lists-of-email-addresses-in-a-short-time
Which is the best method or algorithm to compare two large lists of email addresses in a short time? - Quora
Answer (1 of 2): I would go with the hashing (no need for the lists to have the same size). I would hash all the email addresses in list A. Then for each address in list B, if it's hash is already present in the hash list obtained from the first list, I would output that email address. I am not ...
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ the most pythonic way to compare two lists in python
The Most Pythonic Way to Compare Two Lists in Python - Be on the Right Side of Change
June 27, 2020 - We start with five ways to perform ... way to check if two ordered lists l1 and l2 are identical, is to use the l1 == l2 operator for element-wise comparison....
๐ŸŒ
MetaCPAN
metacpan.org โ€บ pod โ€บ List::Compare
List::Compare - Compare elements of two or more lists - metacpan.org
To determine whether any two particular lists are equivalent to each other, provide is_LequivalentR with their index positions in the list of arguments passed to the constructor (ignoring any unsorted option).
๐ŸŒ
Comparelists
comparelists.net
Compare Two Lists Online - Instagram Analysis & List Diff Tool
Our tool uses advanced algorithms to compare lists and analyze differences between two lists of items. It identifies common elements, unique items in each list, and can detect duplicates. The comparison can be customized with options for case sensitivity, whitespace handling, and custom delimiters.
๐ŸŒ
CompareTwoLists.com
comparetwolists.com
Compare two lists - easy online listdiff tool
Want to compare lists of Instagram followers, names, e-mails, domains, genes or something else? This tool shows you the unique and shared values in your two lists.