Easy · Hash Set Intersection
Understand → Visualise → Practice.
Return the distinct values appearing in both arrays in ascending order.
Duplicates don't matter, so convert both arrays to sets and keep values present in both, then sort them.
Put the values of one array into a set.
Collect each distinct value of the other array that is also in the set.
Return the common values in ascending order.
O(n + m) time plus O(k log k) to sort k results, and O(n) space.
Returning a value once per occurrence produces duplicates such as [2, 2].
Read the full guide first: Hash Maps and Hash Sets.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.