Skip to the content.

3.18 Popcorn Hacks

My answers for the popcorn hacks

CSP Big Idea 3.18

Popcorn Hack #1

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

  1. print the third item from the array using constant time (O(1))
  2. Print all the items from the array using linear time(O(n))
arr = [1, 2, 3, 4, 5]
print(arr[2]) 
3
arr = [1,2,3,4,5]
for num in arr:
    print (num)
1
2
3
4
5

Popcorn Hack #2

Given the array of numbers from 1-3 (arr = [1,2,3]). Write a function that prints all the different unique pairs of numbers from the array. For example the output of this array should be: (1,2) (1,3) (2,3)

Addtionally, what time complexity is this code? Write a small explanation.

def unique_pairs(arr):
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            print((arr[i], arr[j]))

# Example usage:
unique_pairs([1, 2, 3])

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

The outer loop picks one number, and the inner loop pairs it with all the numbers after it. As the list gets bigger, the number of pairs grows like the square of the list size. The time complexity is O(n²) because it grows as fast as n increases.

Popcorn Hack #3

Which of these is inefficient for large inputs?

a) linear time b) factorial time c) constant time d) linearithic time

Factorial time, as it grows very fast

which of these can be represented by a nested loop? a) logarithmic time b) linearithmic time c) quadratic time d) linear time

Quadratic time is represented by a nested loop