Amazon Interview Question
Data EngineersTeam: none
Country: india
Interview Type: Written Test
@Ankit Tomar's idea will not generally work - because arrays are not guaranteed to be unique. Of Course with unique array - where all elements are different it will work, but that is now as trivial as intersection and union of sets.
Solution to this problem is to imagine the generalised set operations.
Suppose an element valued "e" has count "count_a" in the "a" array or list, and "count_b" in the "b" array or list.
count of element "e" in the intersection of a,b will be defined as:
min( count_a, count_b)
count of element "e" in the union of a,b will be defined as:
max( count_a, count_b)
This generalised algorithm now can be used to Union/Intersection.You can generalised this to even find out set minus.
@NoOne : It was mentioned in Question - "elements of the two given array may be repeated but cannot be repeated in union and intersection array."
so i proposed the above solution. :)
Code for Union: putting all in one hashset
hash_dict={}
for value in list1:
hash_dict[value] = hash_dict.setdefault(value,0)+0
for value in list1:
hash_dict[value] = hash_dict.setdefault(value,0)+0
return(hash_dict.keys())
for intersection:
hash_dict={}
output = []
for value in list1:
hash_dict[value] = hash_dict.setdefault(value,0)+0
for value in list1:
if value in hash_dict:
output.append(value)
return(output)
Union : (Assuming order of element doesn't matter )
- Ankit Tomar October 04, 2019Put all the elements of both arrays in HashSet , now Hashset will have union of both the arrays.
Intersection: (Assuming order of element doesn't matter )
Put all the elements of one array in HashSet.
Iterate over other array and check whether element is present HashSet created in previous step if yes include it in intersection result else ignore.