简体   繁体   中英

Time complexity of while inside for loop?

I have the following algorithm:

for(int i=0; i<list.size(); i++){
 String cur = list.get(i);
 int cnt =0;
 while(output.contains(cur)){
  cur= cur.substring(0,5) + String.valueOf(cnt);
  cnt++;
 }
 output.add(cur);
}

Not that "list" and "output" are ArrayLists.

I'm thinking that the Time complexity is O(n^2). But what about the while loop that has a output.contains(cur) inside?

The complexity of this algorithm seems to be depending on the initial contents of output list:

  • output is empty, while loop is not executed, complexity is O(N) , where N is the size of list

  • list and output are crafted to comply with output.contains(cur) condition For example,

List<String> list = Arrays.asList("abcde0", "abcde1", "abcde2", "abcde3", "abcde4", "abcde5", "abcde6");
List<String> output = new ArrayList<>(list);

The size of output will be growing thus the number of iterations will be like this:

1) n+1
2) n+1 + n+2 = 2 (n+1) + 1
3) n+1 + n+2 + n+3 = 3 (n+1) + 3
4) n+1 + n+2 + n+3 + n+4 = 4 (n+1) + 6
...
n) n (n+1) + (1 + n-1)*(n-1)/2 = n (n+1) + n (n - 1)/2 = n (3n + 1)/2 

Thus, in this (possibly not the worst case) the complexity can be O(N^2).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM