java - For N equally sized arrays with integers in ascending order, how can I select the numbers common to arrays? -


i asked algorithmic question today in interview , love members' input on same. question follows;

given equally sized n arrays integers in ascending order, how select numbers common n arrays.

at first thought iterate on elements starting first array trickling down rest of arrays. result in n power n iterations if right. came solution add count map keeping element key , value counter. way believe time complexity n. following implementation in java of 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 did 3 arrays see how work. question talks n arrays though think still hold.

my question is, there better approach solve problem time complexity in mind?

treat 3 queues. while values different, "remove" (by incrementing array index) smallest. when match, "remove" (and record) matches.

int i1 = 0; int i2 = 0; int i3 = 0;  while (i1 < array1.size && i2 < array2.size && i3 < array3.size) {     int next1 = array1[i1];     int next2 = array2[i2];     int next3 = array3[i3];      if (next1 == next2 && next1 == next3) {         recordmatch(next1);         i1++;         i2++;         i3++;     }     else if (next1 < next2 && next1 < next3) {         i1++;     }     else if (next2 < next1 && next2 < next3) {         i2++;     }     else {         i3++;     } } 

easily generalized n arrays, though n large you'd want optimize compares somehow (npe's "heap").


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -