I have a problem to find common elements in two arrays and that’s of different size.
Take , Array A1 of size n and Array A2 of size m, and m != n
So far, I’ve tried to iterate lists one by one and copy elements to another list. If the element already contains mark it, but I know it’s not a good solution.
Sort the arrays. Then iterate through them with two pointers, always advancing the one pointing to the smaller value. When they point to equal values, you have a common value. This will be O(n log n+m log m) where n and m are the sizes of the two lists. It’s just like a merge in merge sort, but where you only produce output when the values being pointed to are equal.
outputs
If the elements aren’t comparable, throw the elements from one list into a hashmap and check the elements in the second list against the hashmap.