11.9k views
1 vote
Design an algorithm to find all the common elements in two

sorted lists of numbers. For example, for the lists (2, 5, 5, 5)
and (2, 2, 3, 5, 5, 7), the output should be (2, 5, 5).

1 Answer

6 votes

Answer:

while list1 not empty AND list2 not empty {

if elements at leftmost positions are equal {

pop element from list1

pop element from list2

add element to result_list

} else {

pop lowest value from list1 or list2

}

}

User Woran
by
4.3k points