Inactive Tutor answered 05/26/19
The solution requires additional memory.(It's a good solution of using Set)
Here is another approach for large dataset, you can sort both ArrayList, And have two iterators to iterator through both Lists one by one.
Inactive Tutor answered 05/26/19
The solution requires additional memory.(It's a good solution of using Set)
Here is another approach for large dataset, you can sort both ArrayList, And have two iterators to iterator through both Lists one by one.
Inactive Tutor answered 05/24/19
I assume your O(n2) solution involves traversing one of the ArrayLists, and for each element, traversing the other ArrayList in its entirety to see if that element is contained.
This can be done in O(n) using hash tables. Start by adding each element from one of the lists to a hash table - this is O(n) total. Then, for the other list, for each element, look it up in the hash table - lookup is a constant-time operation. If it's in the hash table, add it to your result. Thus, we have total runtime of O(n) + O(n) = O(n).
If you're unfamiliar with hash tables, check out the resources here: https://www.geeksforgeeks.org/hashtable-in-java/
Get a free answer to a quick problem.
Most questions answered within 4 hours.
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.