Skip to the content.

BI 3 Big O

Popcorn Hacks

Popcorn Hack 1

# constant time (O(1))
arr = [1, 2, 3, 4, 5]
print(arr[2])
3
# linear time (O(n))
arr = [1, 2, 3, 4, 5]
for num in arr:
    print(num)
1
2
3
4
5

Popcorn Hack 2

arr = [1, 2, 3]
for i in range(len(arr)):
    for j in range(i + 1, len(arr)):
        print(arr[i], arr[j])
1 2
1 3
2 3

This function is has quadratic time complexity because there are two nested loops, causing the time to grow quadratically as mentioned in the lesson.

Popcorn Hack 3

Which of these is inefficient for large inputs?
a. Linear Time
b. Factorial Time
c. Constant Time
d. Linearithic Time

Which of these can be represented by a nested loop?
a. Logarithmic Time
b Linearithmic Time
c. Quadratic Time
d. Linear Time

Homework Hack

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

def simulate_complexity(arr, complexity):
    if complexity == "constant":
        return arr[0]
    
    elif complexity == "linear":
        for item in arr:
            print(item)
    
    elif complexity == "quadratic":
        for i in arr:
            for j in arr:
                print(i, j)
    
    else:
        print("Unknown complexity type.")

# Uncomment whichever complexity you want to test
simulate_complexity(arr, "constant")
# simulate_complexity(arr, "linear")
# simulate_complexity(arr, "quadratic")
1