01 / 20

Recognizing
Optimization Needs

Learn to identify when your Python algorithm is too slow and understand the concepts behind making it faster.

Python

What Is Algorithm Efficiency?

Algorithm efficiency measures how the running time or memory usage of a program grows as the input size increases. Two programs can produce the same correct output, but one might take seconds while the other takes hours on large data.

Introducing Big-O Notation

Big-O notation describes the worst-case growth rate of an algorithm. We write \( O(f(n)) \) to say "this algorithm's time grows at most proportionally to \( f(n) \) for large \( n \)."

\( O(1) \)
Constant time: same speed regardless of input size.
\( O(n) \)
Linear time: doubles work when input doubles.
\( O(n^2) \)
Quadratic time: 4x work when input doubles.

Visualizing Growth Rates

Input Size (n) Operations 0 25 50 75 100 O(1) O(n) O(n log n) O(n²) O(2ⁿ)

The Core Rule: Counting Nested Loops

The most common source of slow algorithms in Python is nested iteration. Each additional loop that iterates over the input multiplies the total work:

1 loop
\( O(n) \): scan a list once
2 nested loops
\( O(n^2) \): compare every pair
3 nested loops
\( O(n^3) \): compare every triple

When Is "Too Slow"?

A modern computer can execute roughly \( 10^8 \) simple operations per second. Use this rule of thumb to judge whether your algorithm can finish in time:

Fast Enough < 10⁸ operations Runs in ~1 second Needs Optimization > 10⁸ operations Takes minutes/hours |

Correct vs. Efficient

A correct algorithm produces the right answer. An efficient algorithm produces it fast. The first step is always correctness, but when dealing with large inputs, efficiency becomes critical.

Correct but Slow Correct and Fast
Approach Brute-force: try everything Clever: exploit structure
Small input (\( n = 100 \)) ✓ Works fine ✓ Works fine
Large input (\( n = 10^6 \)) ✕ Times out ✓ Finishes quickly
Priority Good starting point Goal for production code

Red Flags: Signs You Need Optimization

1
Nested loops over the same data. A for i in range(n) inside another for j in range(n) means \( O(n^2) \).
2
Repeated searching. Using x in list inside a loop is \( O(n) \) per check: \( O(n^2) \) total.
3
Recomputing the same values. Recursive functions that solve the same sub-problem multiple times (e.g., naive Fibonacci).
4
Input size exceeds \(10,000\) and your algorithm feels slow. Estimate total operations: \( n^2 \) at that size is already \( 10^8 \).

How to Diagnose a Slow Algorithm

1
Identify the input size \( n \). What variable controls how much data your algorithm processes?
2
Count nested loops. How many loops depend on \( n \)? One loop = \( O(n) \). Two nested = \( O(n^2) \).
3
Look for hidden \( O(n) \) operations inside loops: in on lists, .index(), list slicing, or string concatenation.
4
Estimate total operations. Multiply: operations per iteration × number of iterations. Compare against \( 10^8 \).
5
Decide if optimization is needed. If total operations > \( 10^8 \) for your expected input size, the algorithm is too slow.

Example 1: Finding Duplicates

def has_duplicate(lst): for i in range(len(lst)): for j in range(i + 1, len(lst)): if lst[i] == lst[j]: return True return False

Example 2: Hidden \( O(n) \) Inside a Loop

def count_common(list_a, list_b): count = 0 for item in list_a: # O(n) loop if item in list_b: # \( O(n) \) search! count += 1 return count

Example 3: Recursive Explosion

def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)
f(5) f(4) f(3) f(3) f(2) f(2) f(1) f(2) f(1) Duplicate calls!

Common Optimization Strategies

Use a Set or Dict
Replace \( O(n) \) list lookups with \( O(1) \) hash-based lookups.
Sort First
Sorting in \( O(n \log n) \) enables binary search and two-pointer techniques.
Memoize Results
Cache computed values so recursive calls don't repeat work.

Common Mistakes

✕ Ignoring Hidden Costs
Using in on a list inside a loop looks like one line of code but adds an entire \( O(n) \) scan per iteration.
✕ Premature Optimization
Optimizing before confirming the algorithm is correct, or optimizing code that's already fast enough for the input size.
✕ Confusing Time and Space
An algorithm can be fast but use too much memory. Always consider both dimensions of efficiency.

Summary: Complexity at a Glance

Complexity Operations at \( n = 10,000 \) Fast Enough? Common Pattern
\( O(1) \) 1 ✓ Always Dict lookup
\( O(\log n) \) ~13 ✓ Always Binary search
\( O(n) \) \( 10^4 \) ✓ Yes Single loop
\( O(n \log n) \) ~\( 1.3 \times 10^5 \) ✓ Yes Sorting
\( O(n^2) \) \( 10^8 \) ~ Borderline Nested loops
\( O(2^n) \) \( 10^{3010} \) ✕ Never Naive recursion

Question 1 of 5

You have a list of \( n = 50,000 \) numbers and a for loop that checks if x in my_list for each element. What is the time complexity?

Question 2 of 5

Which of the following is the best reason to optimize an algorithm?

Question 3 of 5

A function has three nested loops, each iterating over a list of size \( n \). What is the time complexity?

Question 4 of 5

You convert a list to a set before a loop that checks membership. What changes?

Question 5 of 5

The naive recursive Fibonacci function fib(n) calls itself twice at each step. Approximately how many function calls does fib(40) make?