简体   繁体   中英

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

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)?

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

list.contains(i*j) happens in O(n^2) as i and j are dependents on n ( if linear search is used ). Basically it will be 2 loops in O(n) nested and an operation of of O(n^2) inside the nested loop and hence O(n^4) .

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