Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndrew Stevens
11,083 PointsHow do you identify if a function has the same best-case or worse-case complexity?
for x in data:
for y in data:
print(x, y)
The above is a very simple example of O(N^2), but if I were asked to identify whether this code had the same best-case or worse-case complexity how would I go about calculating that?
1 Answer
hannahgibson2
30,777 PointsThis does have the same best/worst case complexity because it will always run x * y times.
That would not be true for something like this algorithm which searches for an element in a 2D array:
for x in data:
for y in data[x]:
if data[x][y] == "my element":
print("found it")
break
The worst case complexity is x * y, the element is at the end so it has to search through the whole array The best case complexity is 1, the element is at the beginning so it can stop the search