๐ŸŽฏ HOOK

The Lost Key Problem

You dropped your key somewhere in a long hallway with 100 doors. You need to check each door to find it. If you double the hallway length to 200 doors, how does your search time change?

๐Ÿงช EXPLORE

Watch Linear Search in Action

Adjust the list size and start a search. Notice how many checks are needed!

Searching for: ?
Items Checked
0
Total Items
10
Time
0ms

Observe: When you double the list size, the worst-case checks also double. That's the hallmark of O(n)!

๐Ÿ’ก EXPLAIN

What is O(n)?

Linear time means the operations grow in direct proportion to the input size (n).

๐Ÿšถ

Think of it like walking a line

  • โœ“ Linear search through an array
  • โœ“ Counting items in a list
  • โœ“ Finding max/min value
  • โœ“ Summing all elements

The straight diagonal line shows direct proportionality: 10 items โ†’ 10 operations, 100 items โ†’ 100 operations, 1000 items โ†’ 1000 operations.

โœ“ When O(n) is Good

  • โ€ข Small to medium datasets
  • โ€ข One-time operations
  • โ€ข When you must check everything

โš ๏ธ When to Optimize

  • โ€ข Very large datasets (millions)
  • โ€ข Repeated lookups (use hash map)
  • โ€ข Real-time systems with strict limits
โœ๏ธ PRACTICE

Test Your Understanding

1. Which operation is O(n)?

2. An algorithm processes 1000 items in 2 seconds. How long for 5000 items?

(Assume O(n) complexity)

3. What's the complexity of this code?

def find_max(arr):
  max_val = arr[0]
  for num in arr:
    if num > max_val:
      max_val = num
  return max_val

4. True or False: O(n) is always slow

5. Match the scenario to the correct statement

Scenario: Checking if a name exists in an unsorted list of 1 million names

6. Predict the growth

Use the simulator above. Set list size to 10, then 20. How do the checks change?

7. Code challenge: What's the complexity?

function printPairs(arr) {
def print_pairs(arr):
  for item in arr:
    print(item)
  for item in arr:
    print(item)
๐Ÿค” REFLECT

Think Deeper

๐Ÿ’ญ When is O(n) unavoidable?

๐Ÿ’ญ O(n) vs O(1): When would you use a hash map instead of an array?

๐ŸŽ‰

Well Done!

You've mastered O(n) linear time โ€” algorithms that scale in direct proportion to input size.