0

I have this algorithm written where the while loop can vary from N to 0 depending on the input array, but we cannot give O(N*N) also because if the while loop is executed once for N times, then for the next iteration of x it will be 0 because we are removing it from the dictionary as a result the loop will break in the first iteration. So what is the time complexity of this algorithm in the worst case scenario. If you need to understand the algorithm this is the question for it.[https://www.youtube.com/watch?v=XitBQzqC1O0]

x=[5,4,4,3,3,2]
destroyedBaloons={}
count=0
for i in x:
    if(destroyedBaloons.get(i)):
        destroyedBaloons[i]+=1
    else:
        destroyedBaloons[i]=1
for i in x:
    if(not(destroyedBaloons.get(i))):
        continue
    height =i
    while(height>0):
        if(destroyedBaloons.get(height)):
            destroyedBaloons[height]-=1
            height-=1
        else:
            break
    count+=1    
print(count)```




 

1 Answers1

0

The worst scenario would be the balloons in non-decreasing order, so you would need one arrow for each balloon. First loop would be N iterations, then N - 1, N - 2, etc. so total iterations would be ½(N² + N) or O(N²).

Yimin Rong
  • 1,890
  • 4
  • 31
  • 48
  • Thanks Yimin , but even if the balloons are in increasing order when you see inside the while loop if we don't find any balloons to burst , it breaks in the first iteration as we are checking inside a dictionary, so how can we consider the while loop to be as N time complexity? – Raveen rex Apr 10 '21 at 13:53