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?
Watch Linear Search in Action
Adjust the list size and start a search. Notice how many checks are needed!
Observe: When you double the list size, the worst-case checks also double. That's the hallmark of O(n)!
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
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?
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?
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.