![]() |
VOOZH | about |
Given two arrays a[] and b[], find their intersection — the unique elements that appear in both. Ignore duplicates, and the result can be in any order.
Input: a[] = [1, 2, 1, 3, 1], b[] = [3, 1, 3, 4, 1]
Output: [1, 3]
Explanation: 1 and 3 are the only common elements and we need to print only one occurrence of common elementsInput: a[] = [1, 1, 1], b[] = [1, 1, 1, 1, 1]
Output: [1]
Explanation: 1 is the only common element present in both the arrays.Input: a[] = [1, 2, 3], b[] = [4, 5, 6]
Output: []
Explanation: No common element in both the arrays.
Table of Content
The idea is to find all unique elements that appear in both arrays by checking each element of one array against the other and ensuring no duplicates are added to the result.
Step By Step Implementation:
2 3
The idea is to find common elements between two arrays without duplicates by:|
– Using a hash set to track already added elements,
– Checking each element of a[] against b[], and only adding it to the result if it's present in b[] and not already recorded.
Step By Step Implementation:
2 3
The idea is to use hash sets to efficiently find the unique elements that are common to both arrays. One set (as) stores elements from the first array, and the other (rs) ensures each common element is added only once to the result.
Step By Step Implementations:
3 2
We can optimize the above approach by avoiding creation of rs hash set. To make sure that duplicates are not added, we simply delete items from as (Set of a[] elements) rather than checking with rs.
3 2
Related Articles: