Skip to the content.

BIGO

pluh

Big O and Algorithm Efficiency – Popcorn Hacks

Popcorn Hack #1

Task:
Given an array:
arr = [1, 2, 3, 4, 5]

arr = [1, 2, 3, 4, 5]
# Print the third item from the array using constant time (O(1)):
print(arr[2])  # O(1) – Direct index access

3
#Print all the items from the array using linear time (O(n)):
arr = [1, 2, 3, 4, 5]

for item in arr:
    print(item)  # O(n) – One operation per element

1
2
3
4
5

Popcorn Hack #2

arr = [1, 2, 3]

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

print_unique_pairs([1, 2, 3])
# O(n^2) – Two nested loops, each iterating through the array
(1, 2)
(1, 3)
(2, 3)

Time Complexity Explanation: This is O(n²) time complexity. The nested loop causes the number of operations to grow quadratically with the size of the input array.

Popcorn Hack #3

Which of these is inefficient for large inputs?

Answer:
b) Factorial Time

Explanation:
Factorial time (O(n!)) grows extremely fast and becomes impractical for even moderately large inputs.


Which of these can be represented by a nested loop?

Answer:
c) Quadratic Time

Explanation:
Nested loops often result in O(n²) time complexity.

Homework Hack

def simulate_time_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(f"({i}, {j})")
    else:
        print("Unknown time complexity.")

# Example usage:
arr = [5, 10, 15, 20, 25]
simulate_time_complexity(arr, "linear")

5
10
15
20
25