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 one by one
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):
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            print(f"({arr[i]}, {arr[j]})")

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

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

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 Write a function that takes the following inputs:

An array: arr = [5, 10, 15, 20, 25] A string representing the time complexity: “constant”, “linear”, “quadratic”, etc. The function should perform operations on the array based on the given time complexity. For example:

If the string is “constant”, return the first item of the array. If the string is “linear”, print all the items in the array. If the string is “quadratic”, print all pairs of items in the array.

def perform_operation(arr, complexity):
    if complexity == "constant":
        # O(1) - Access first item
        return arr[0]
    
    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:
        return "Unsupported time complexity"

# Example usage:
arr = [5, 10, 15, 20, 25]
print("Constant:", perform_operation(arr, "constant"))
print("\nLinear:")
perform_operation(arr, "linear")
print("\nQuadratic:")
perform_operation(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)