I have two sorted lists, both in non-decreasing order. For example, I have one sorted linked list with elements [2,3,4,5,6,7...]
and the other one with elements [5,6,7,8,9...]
.
I need to find all common elements in both lists. I know I can use a for loop and a nested loop to iterate all matches to find the same two elements. However, is there another way to do this that has running time less than O(n^2)
?
Convert the first list to a
HashSet
; then iterate through the second list checking whether each element is in theHashSet
.In the main loop, take the first elements from both lists and compare. If they are not equal, scan the list with less element until it gets equal or more than the element of the other loop. If it gets equal, this means you found a common element. Read both list sequentially until the common element is passed. Continue the main loop. The complexity of this approach is O(n+m).
Actually you can do a little better:
You can do it in O(n) time. Pseudocode: