Skip to the content.

Big O and Algorithm Efficiency

None

None

Popcorn Hack 1

# statement 1
arr = [1, 2, 3, 4, 5]


# statement 2
print(arr[2])

for num in arr:
    print(num)

3
1
2
3
4
5

The reason that the first print statement is faster than the other one is that it has constant time complexity and will always directly access the chosen number while the second print statement inside the for loop needs to cycle through every element in the list. With larger input values, the amount of time will stay the same for statement one but for statement two it will take increasingly longer.

Popcorn Hack 2

arr = [1, 2, 3]

for x in arr:
    for y in arr:
        if x < y:
            print(x, y)
1 2
1 3
2 3

This code segment has a quadratic time complexity as it will go through the entire list again for each number in the list.

Popcorn Hack 3

q1: b - Factorial Time (grows heavily with increased input size)

q2: c - Quadratic Time (see above example)

Homework Hack 1

def bigo(array, string):
    if string == "constant":
        print(arr[0])
    elif string == "linear":
        for x in array:
            print(x)
    elif string == "quadratic":
        for x in array:
            for y in array:
                if x < y:
                    print(x, y)

arr = [5, 10, 15, 20, 25]
complexity = "quadratic"

bigo(arr, complexity)
5 10
5 15
5 20
5 25
10 15
10 20
10 25
15 20
15 25
20 25