Big O and Algorithmic Efficiency
Homework Hacks and Popcorn Hacks
Popcorn Hacks
Popcorn Hack 1
arr = [1, 2, 3, 4, 5]
# Constant time O(1): Accessing the third item (index 2)
print("Third item (O(1)):", arr[2])
# Linear time O(n): Printing all items
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
arr[2] accesses the third element in constant time, no matter the size of the array. This means that once the number is found, the program ends.
The for loop goes through each item once, resulting in linear time complexity, which is why it’s better to use constant time.
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)
Explanation:
The outer loop runs n times. For each iteration of the outer loop, the inner loop runs fewer times (n - i - 1), but in the worst case this still results in a total of roughly n(n-1)/2 iterations — which is quadratic time. This is generating all combinations of 2 elements from n, which is (n2)(2n) and scales as O(n²)
Popcorn Hack 3
Question 1: B
Factorial time gets larger at a rate greater than exponentially with the increase of a single number. Quadratic and exponential are also inefficient.
Question 2: C
Quad
Homework Hack
Homework Hack 1
def operate(arr, complexity):
if complexity == "constant":
return arr[0] if arr else None
elif complexity == "linear":
for item in arr:
print(item)
elif complexity == "quadratic":
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
print(f"({arr[i]}, {arr[j]})")
else:
print("Unsupported time complexity")
arr = [5, 10, 15, 20, 25]
print("Constant Time Output:", operate(arr, "constant"))
print("\nLinear Time Output:")
operate(arr, "linear")
print("\nQuadratic Time Output:")
operate(arr, "quadratic")
Constant Time Output: 5
Linear Time Output:
5
10
15
20
25
Quadratic Time Output:
(5, 10)
(5, 15)
(5, 20)
(5, 25)
(10, 15)
(10, 20)
(10, 25)
(15, 20)
(15, 25)
(20, 25)