Skip to content

Instantly share code, notes, and snippets.

@mugizico
Created May 19, 2016 18:37
Show Gist options
  • Save mugizico/7ab8bd2a9af014426254c9a5d268fff0 to your computer and use it in GitHub Desktop.
Save mugizico/7ab8bd2a9af014426254c9a5d268fff0 to your computer and use it in GitHub Desktop.
Find an Intersection between two integer arrays
/*
* Example Arr1 = {2,3,7,9,20,35} ; Arr2 = { 3,9,21,35,89,100,200}, Intersection = {3,9,35}
* Assumptions:
* Both Arrays are sorted
* Both Arrays contain at least one element
* Arr2 >> Arr1
* n is Arr1.length, m is Arr2.length
* Possible Solutions:
* (1) Brute-force : run O(nm) - inefficient
* (2)HashSet/Map : O(n+m) runtime, O(k) additional space k = size of hashset/map
* (3)Merge subroutine of merge sort : O(n+m) run, O(k) additional array space
* Better solution(4)linear search Arr1, binary search Arr2: O(nlogm) since m >> n and logm >> logn
*/
public class IntersectionSearch {
public static List<Integer> findIntersection(int [] arr1, int [] arr2){
List<Integer> intersection = new ArrayList<>();
for(int i = 0; i < arr1.length; i++){
int item = arr1[i];
if(binarySearch(arr2, item)) intersection.add(item);
}
return intersection;
}
public static boolean binarySearch(int [] arr2, int key){
int begin = 0;
int end = arr2.length-1;
while(begin <= end){
int mid = begin + ((end - begin)/2);
if(key == arr2[mid]) return true;
if(key > arr2[mid]) begin = mid + 1;
if(key < arr2[mid]) end = mid - 1;
}
return false;
}
//test harness
public static void main(String [] args){
int [] arr1 = {2, 3,35,89,150};
int [] arr2 = {3, 9, 21, 35, 89, 100,150, 200};
List<Integer> inter = findIntersection(arr1, arr2);
for(Integer i : inter){
System.out.print(i + ",");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment