Why does nested loop with list.add gives O(n^4) time complexity?

user3437460 :

I came across this question for the Big O time complexity of this code snippet: It is guaranteed that the time complexity for the following code is O(n^4).

ArrayList<Integer> list = new ArrayList<Integer>();

for(int i = n; i>=1; i--)           //n 
    for(int j = 1; j<=i; j++)       //n     
        if(!list.contains(i*j))     //n?    
            list.add(i*j);          //1?

My Question: Why is it O(n^4) instead of O(n^3)?

k5_ :

list has about n^2/2 entries[*], so the lookup list.contains(i*j) is O(n^2) not O(n)

*: some less because duplicates are not added, but i guess enough to count as n^2

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87686&siteId=1