Ahaan

Big O Lesson

Popcorn Hack 1

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


3
1
2
3
4
5

Explanation: Looping through every element grows linearly with the size of the input.

Popcorn Hack #2

# Popcorn Hack #2
# Task: Print all unique pairs from arr = [1, 2, 3]

def print_unique_pairs(arr):
    # Loop through each index in the array
    for i in range(len(arr)):
        # Loop through the next indices to avoid duplicates and self-pairs
        for j in range(i + 1, len(arr)):
            print(f"({arr[i]}, {arr[j]})")

# Example array
arr = [1, 2, 3]

# Function call
print_unique_pairs(arr)


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

Explanation: The function uses nested loops, where each element is compared with every following element — this results in quadratic growth.

Popcorn Hack 3

Q1: Which is inefficient for large inputs? ✅ Correct Answer: b) Factorial Time

  • Explanation: Factorial time grows extremely fast as the input size increases, making algorithms with this complexity impractical for large inputs. For example, an algorithm with O(n!) complexity can easily become unmanageable for n > 20.

Q2: Which can be represented by a nested loop? ✅ Correct Answer: c) Quadratic Time

  • Explanation: Quadratic time (O(n²)) often comes from algorithms that involve two nested loops iterating over the same dataset, such as bubble sort or nested loops checking pairs of elements. Each additional layer of nesting increases the time complexity.

Homework Hack

def run_by_complexity(arr, complexity):
    if complexity == "constant":
        return arr[0]  # O(1)
    
    elif complexity == "linear":
        for item in arr:  # O(n)
            print(item)
    
    elif complexity == "quadratic":
        for i in arr:         # O(n²)
            for j in arr:
                print(f"({i}, {j})")

# Example usage:
arr = [5, 10, 15, 20, 25]
print("Constant:")
print(run_by_complexity(arr, "constant"))

print("\nLinear:")
run_by_complexity(arr, "linear")

print("\nQuadratic:")
run_by_complexity(arr, "quadratic")


Constant:
5

Linear:
5
10
15
20
25

Quadratic:
(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)

Explanation: This code uses two nested loops to iterate through the array and print all unique pairs without repeating or pairing the same elements. The outer loop picks the first number, and the inner loop picks the second number from the remaining elements. Since each element is paired with every other element after it, the time complexity is O(n²)

Scroll to top