Solution 4 – One hash table
func intersection(nums1 []int, nums2 []int) []int {
/*
make a map of seen elemnts for nums1
loop over nums2 check if present in map1
if yes add to result list and remove from map1
*/
m1 := make(map[int]struct{})
for _,val := range nums1{
m1[val]=struct{}{}
}
var seen []int
for _,val := range nums2{
if _,inM1:=m1[val];inM1{
seen=append(seen,val)
delete(m1,val)
}
}
return seen
}

Solution 3 – Binary Search + Hash table
func intersection(nums1 []int, nums2 []int) []int {
// sort larger of two nums1 or nums2
// loop over shorter array
// binary search element in each run, before check use hash to check if already seen
// if found add to result array
if len(nums1) > len(nums2) {
nums1, nums2 = nums2, nums1
}
sort.Ints(nums2)
seen := make(map[int]bool)
result := []int{}
for _, num := range nums1 {
if seen[num] {
continue
}
if binarySearch(nums2, num) {
result = append(result, num)
seen[num] = true
}
}
return result
}
func binarySearch(nums []int, target int) bool {
start, end := 0, len(nums)-1
for start <= end {
mid := (start + end) / 2
if nums[mid] == target {
return true
}
if nums[mid] < target {
start=mid+1
} else {
end=mid-1
}
}
return false
}

Solution 2 – Two pointers
func intersection(nums1 []int, nums2 []int) []int {
// two pointers approach sort both arrays
// use two pointers and if val at both equal add to result
// if val at firs ptr is small move forward
// if val at sec ptr is small move forward
// before adding to result check in a seen map to avoid dupes
sort.Ints(nums1)
sort.Ints(nums2)
var result []int
seen := make(map[int]struct{})
var ptr1, ptr2 int
for ptr1 < len(nums1) && ptr2 < len(nums2) {
if nums1[ptr1]==nums2[ptr2]{
if _,exists:= seen[nums1[ptr1]];!exists{
seen[nums1[ptr1]]=struct{}{}
result = append(result,nums1[ptr1])
continue
}
}
if nums1[ptr1]<nums2[ptr2]{
ptr1++
} else {
ptr2++
}
}
return result
}

Solution 1 – Two Hash tables
func intersection(nums1 []int, nums2 []int) []int {
/*
make two maps of seen elemnts for both
build seen map of seen elemts in num1
loop over num2 check if element exist in map1
if yes, check if it does in map2
if no, add to seen list
*/
m1 := make(map[int]struct{})
m2 := make(map[int]struct{})
for _,val := range nums1{
m1[val]=struct{}{}
}
var seen []int
for _,val := range nums2{
if _,inM1:=m1[val];inM1{
if _,inM2:=m2[val];!inM2{
seen=append(seen,val)
m2[val]=struct{}{}
}
}
}
return seen
}

Leave a Reply