I have String arrays of arrays.
List<String[]> mainList = new ArrayList<String[]>();
String[] row1 = {"foo", "bar", "moo"}
String[] row2 = {"cocoa", "zoo", "milk", "coffee"}
mainList.add(row1);
mainList.add(row2);
Let’s say I want to find an element “milk”.
I could do with N^2.
for(int i=0, j=mainList.size(); i<j; i++) {
for(int x=0, y=mainList.get(i).length(); x<y; x++) {
String item = mainList.get(i)[x];
if(item.equals("milk")) {
return true; //found milk
}
}
}
I tried to make it faster by putting all elements as Map key.
//put all elements to map key
Map m = new HashMap<String, String>();
for(int i=0, j=mainList.size(); i<j; i++) {
for(int x=0, y=mainList.get(i).length(); x<y; x++) {
m.put(mainList.get(i)[x], "whatever");
}
}
//now iterate and see if key "milk" is found
if(m.contains("milk")) { return true; }
But I figured this is still N^2 (i.e. for loop inside of for loop, as the number of rows added to mainList like row3[‘item1’, ‘item2’, ‘item3’], the iteration increments in N^2)
how can I optimize this without N^2 ?
Neither algorithm is N^2 since you visit the elements only once. However, the first algorithm, is O(N) for each lookup, but the second algorithm is O(N) to populate the map and O(1) for each subsequent lookup.