In an interview, I was asked an algorithmic question, and I would like to get the same thing as the SO members. The question was as follows:
For arrays with the same size N with integers in ascending order, how would you choose the numbers common to all N arrays.
At first, I thought about iterating over the elements, starting with the first array flowing down to the rest of the arrays. But then this will lead to N-nuclear iterations, if I am right. So, I came up with a solution to add an account to the card, saving the element as a key and value as a counter. So I believe that time complexity is just N. Next is the Java implementation of my approach
public static void main(String[] args) { int[] arr1 = { 1, 4, 6, 8,11,15 }; int[] arr2 = { 3, 4, 6, 9, 10,16 }; int[] arr3 = { 1, 4, 6, 13,15,16 }; System.out.println(commonNumbers(arr1, arr2, arr3)); } public static List<Integer> commonNumbers(int[] arr1, int[] arr2, int[] arr3) { Map<Integer, Integer>countMap = new HashMap<Integer, Integer>(); for(int element:arr1) { countMap.put(element, 1); } for(int element:arr2) { if(countMap.containsKey(element)) { countMap.put(element,countMap.get(element)+1); } } for(int element:arr3) { if(countMap.containsKey(element)) { countMap.put(element,countMap.get(element)+1); } } List<Integer>toReturn = new LinkedList<Integer>(); for(int key:countMap.keySet()) { int count = countMap.get(key); if(count==3)toReturn.add(key); } return toReturn; }
I just did it for three arrays to see how it would work. The question is talking about N arrays, although I think it will be anyway.
My question is, is there a better approach to solving this problem taking into account time complexity?