How does nested loop Big O is N^2 despite the below counter resulted in 30 steps ??
arr = [1,2,3,4,5]
counter = 0
for x in arr:
counter += 1
for y in arr:
counter += 1
print(counter) # Equals 30
How does nested loop Big O is N^2 despite the below counter resulted in 30 steps ??
arr = [1,2,3,4,5]
counter = 0
for x in arr:
counter += 1
for y in arr:
counter += 1
print(counter) # Equals 30
You should only count the counter in inner for loop. Because only in the inner loop, an instruction or an operation takes place. Hence, it will be 25.
The thing that is confusing you likely is that you are incrementing the counter in the for loop with the X. Change you code to:
arr = [1,2,3,4,5]
counter = 0
for x in arr:
# counter += 1 < --- omit this line
for y in arr:
counter += 1
print(counter) # Equals 30
You will see that the counter will now be 25. This better represents the question you are asking, which is why a nested for loop is O(N^2).
For this specific example, each element of the array is iterated through 5 times in the X for loop. If it were just this, this would be O(N). Due to the nested for loop, every time the for loop is iterated over, another for loop (y-loop) iterates over the entire list again, which is O(N) again.
Since both are O(N), you end up with a formula like so:
O(N * N) = O(N^2)
Here is a link to Big-O that I thought could be useful. It's in java, but the same concepts apply to python as well: https://developerinsider.co/big-o-notation-explained-with-examples/