Skip to the content.

Big O Notation

Homework and Hacks

Popcorn Hack 1

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

# Constant time (O(1)) - directly accessing the 3rd item (index 2)
print("Third item (O(1)):", arr[2])

# Linear time (O(n)) - printing all items using a loop
print("All items (O(n)):")
for item in arr:
    print(item)

Third item (O(1)): 3
All items (O(n)):
1
2
3
4
5

Popcorn Hack 2

def print_unique_pairs(arr):
    n = len(arr)
    for i in range(n):
        for j in range(i + 1, n):
            print(f"({arr[i]}, {arr[j]})")

# Example usage
arr = [1, 2, 3]
print_unique_pairs(arr)

(1, 2)
(1, 3)
(2, 3)

The time complexity is O(n²) because it uses two nested loops to iterate through the array. For each element it pairs it with every following element, resulting in about n(n-1)/2 operations. This quadratic growth means the number of operations increases quickly as the array gets larger.

Popcorn Hack 3

B, C

Homework Hack

def perform_operation(arr, complexity):
    if complexity == "constant":
        # O(1) - Return the first item
        return arr[0] if arr else None

    elif complexity == "linear":
        # O(n) - Print all items
        for item in arr:
            print(item)

    elif complexity == "quadratic":
        # O(n^2) - Print all unique pairs
        for i in range(len(arr)):
            for j in range(len(arr)):
                print(f"({arr[i]}, {arr[j]})")

    else:
        print("Unsupported complexity type.")

# Example usage
arr = [5, 10, 15, 20, 25]

print("Constant time result:", perform_operation(arr, "constant"))
print("\nLinear time output:")
perform_operation(arr, "linear")
print("\nQuadratic time output:")
perform_operation(arr, "quadratic")

Constant time result: 5

Linear time output:
5
10
15
20
25

Quadratic time output:
(5, 5)
(5, 10)
(5, 15)
(5, 20)
(5, 25)
(10, 5)
(10, 10)
(10, 15)
(10, 20)
(10, 25)
(15, 5)
(15, 10)
(15, 15)
(15, 20)
(15, 25)
(20, 5)
(20, 10)
(20, 15)
(20, 20)
(20, 25)
(25, 5)
(25, 10)
(25, 15)
(25, 20)
(25, 25)