I am having trouble understanding how while loops affect the Big O time complexity.
For example, how would I calculate the time complexity for the code below? Since it has a for loop that traverses through each element in the array and two nested while loops my initial thought was O(n^3) for the time complexity but I do not think that is right.
HashMap<Integer,Boolean> ht = new HashMap<>(); for(int j : array){ if(ht.get(j)) continue; int left = j-1; //check if hashtable contains number while(ht.containsKey(left)){ //do something left--; } int right = j+1; //check if hashtable contains number while(ht.containsKey(right)){ //do something right++; } int diff = right - left; if(max < diff) { //do something } }
O(n^3)would be applicable if you have three nested loops. You only have two levels of nesting, as the inner loops are side-by-side, not nested.whileloops. There must be some something that constrains how farrightandleftcan go, but we don't know what. For all I know, there is a bug, and one or both of thewhileloops are infinite loops.