I'm given two sorted arrays, arr1
and arr2
. They can either be of the same length or arr2
will be longer than arr1
. I implemented a method findDuplicates
that returns an array of all numbers that are both in arr1
and arr2
. Note that the output array should be sorted in an ascending order.
I know there are better solutions than the one I came up with. What I'm trying to understand is the space complexity of the solution I came up with.
static int[] findDuplicates(int[] arr1, int[] arr2) {
// your code goes here
HashMap<Integer, Integer> table = new HashMap<>();
ArrayList<Integer> returnlist = new ArrayList<Integer>();
int arr1Length = arr1.length;
int arr2Length = arr2.length;
// this is for the first array
for(int i=0; i<arr1Length; i++){
int n = arr1[i];
table.put(n, 1);
}
for(int i=0; i<arr2Length; i++){
int n = arr2[i];
if(table.containsKey(n)){
returnlist.add(n);
}
}
int[] arr = new int[returnlist.size()];
for(int i=0; i<=returnlist.size()-1; i++){
arr[i] = returnlist.get(i);
}
return arr;
} // end of method
Since I created a temporary Hashtable and an ArrayList, and then another array to return the duplicates is my space complexity \$O(n^3)\$. I know its greater than \$O(n)\$. If someone can help me understand this better, I would really appreciate it.