1. Home
  2. Explore
  3. Computer Science
  4. MIT Programming Fundamentals Review

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

MIT Programming Fundamentals Review

Algorithmic Efficiency and Orders of Growth

Why Efficiency Matters

As computing power increases, the size of problems being tackled grows even faster. Data sets like web indexes, genomic databases, and surveillance feeds have become massive — Google served 30 trillion pages in 2014, covering 100 million gigabytes. A simple sequential search through such data would be impossibly slow, regardless of computer speed. Therefore, understanding how to design and evaluate efficient algorithms is essential.

Two key goals drive this study:

  • Predict performance: Given an algorithm tested on small inputs, how long will it take on much larger inputs?

  • Guide design choices: How do recursive vs iterative choices, or different data structures, affect runtime?

The lecture focuses on time efficiency (as opposed to space efficiency), though a trade-off often exists: using more memory can speed up computation (e.g., caching intermediate Fibonacci values).


Approaches to Measuring Efficiency

There are three common methods, each with strengths and weaknesses.

Timing (Empirical Measurement)

Python’s time module can measure elapsed time for a function call. For example:

import time
start = time.clock()
result = celsius_to_fahrenheit(100)
end = time.clock()
elapsed = end - start

Problems with timing:

  • Depends on the implementation (e.g., for loop vs while loop with extra steps)

  • Depends on the machine (processor speed, memory, etc.)

  • Small-scale tests may not predict large-scale behavior due to caching or memory hierarchy

Timing conflates algorithm efficiency with implementation and hardware details.

Counting Operations

Abstract one level: identify a set of primitive operations (arithmetic, comparisons, assignments, memory access) and assume each takes roughly the same time. Then count how many operations an algorithm executes as a function of input size.

Example: Sum of integers from 0 to x:

def sum_iter(x):
    total = 0               # 1 operation
    for i in range(x+1):    # loop runs x+1 times
        total += i          # 2 operations (add + assign)
    return total            # 1 operation

Count ≈ 1 + 3(x+1) + 1 = 3x + 5 operations.

Advantages:

  • Independent of machine speed

  • Reflects the algorithm more than implementation details

Disadvantages:

  • Still influenced by minor implementation differences (e.g., while loop vs for loop adds an extra test per iteration)

  • Assumes all primitive operations take equal time (memory access vs. arithmetic may differ)

To remove implementation dependence, we move to a more abstract measure: order of growth.


Order of Growth (Big O Notation)

Order of growth describes how runtime (or operation count) scales as the input size becomes arbitrarily large (asymptotic behavior). Focus is on the dominant term that grows fastest when input size grows.

Key idea: Ignore additive constants and multiplicative constants. Only care about the shape of the growth curve.

Why Constants Don’t Matter

  • If an algorithm takes 5n+25n + 25n+2 steps vs 6n+16n + 16n+1 steps, both are linear — doubling n roughly doubles runtime.

  • The constant factors are irrelevant for large n and vary with implementation.

Notation

  • O(n)O(n)O(n) — linear growth

  • O(n2)O(n^2)O(n2) — quadratic growth

  • O(1)O(1)O(1) — constant

  • O(log⁡n)O(\log n)O(logn) — logarithmic

  • O(nlog⁡n)O(n \log n)O(nlogn) — log-linear (linearithmic)

  • O(2n)O(2^n)O(2n) — exponential

Rule for polynomials: Keep the highest-order term, drop lower-order terms and constant factors.
n2+2n+2→O(n2)n^2 + 2n + 2 \rightarrow O(n^2)n2+2n+2→O(n2)
n+1000log⁡n→O(n)n + 1000\log n \rightarrow O(n)n+1000logn→O(n)
2n2+100n→O(n2)2n^2 + 100n \rightarrow O(n^2)2n2+100n→O(n2)
0.1n3+1000n2→O(n3)0.1n^3 + 1000n^2 \rightarrow O(n^3)0.1n3+1000n2→O(n3)
n30+3nn^{30} + 3^nn30+3n: exponential dominates — O(3n)O(3^n)O(3n).

Visual Comparison of Growth Rates

A log-log plot shows the differences:

  • Constant O(1)O(1)O(1): flat line, independent of n.

  • Logarithmic O(log⁡n)O(\log n)O(logn): grows slowly, flattens as n increases.

  • Linear O(n)O(n)O(n): straight line.

  • Log-linear O(nlog⁡n)O(n \log n)O(nlogn): slightly steeper than linear.

  • Quadratic O(n2)O(n^2)O(n2): grows more quickly.

  • Exponential O(2n)O(2^n)O(2n): extremely rapid growth, quickly infeasible.

(Below is a conceptual diagram of growth curves — an actual plot would show yyy-axis as runtime, xxx-axis as input size.)


This graph illustrates how runtime increases with input size for different complexity classes. Exponential growth quickly dwarfs all others.


Worst-Case vs. Average vs. Best Case

Many algorithms have runtime that depends on the specific input.

Example: Linear search for an element e in a list L:

  • Best case: e is the first element → constant time (O(1)O(1)O(1))

  • Average case: e is found halfway → linear time (O(n)O(n)O(n))

  • Worst case: e is not in the list → must examine all elements → linear time (O(n)O(n)O(n))

Why focus on worst case?

  • Gives an upper bound — a guarantee that the algorithm will finish within that time.

  • The worst case often dominates real-world performance (e.g., repeated failed searches).

  • Average case can be harder to analyze and may not always apply.

Therefore, Big O notation typically refers to the worst-case runtime.


Analyzing Code for Order of Growth

Two fundamental laws help break down composite code into its order of growth.

Law of Addition (Sequential Code)

If a program consists of two blocks run one after another, the overall order is the sum of the orders of the blocks. Since we keep only the dominant term, this is equivalent to taking the maximum order.

Example:

# Block A: O(n)
for i in range(n):
    print(i)

# Block B: O(n²)
for i in range(n):
    for j in range(n):
        print(i, j)

Overall: O(n)+O(n2)=O(n2)O(n) + O(n^2) = O(n^2)O(n)+O(n2)=O(n2) (quadratic dominates).

Law of Multiplication (Nested Code)

If one block is inside another (e.g., a loop inside a loop), the overall order is the product of the orders of the inner and outer blocks.

Example:

for i in range(n):        # outer: O(n)
    for j in range(n):    # inner: O(n)
        print("Hey")      # O(1)

Total: O(n)×O(n)=O(n2)O(n) \times O(n) = O(n^2)O(n)×O(n)=O(n2).

This rule applies generally to nested structures, not just loops — any operation that repeats another operation multiplies the orders.


Constant-Time List Access

When analyzing L[i], why is it O(1)O(1)O(1)?

Python lists store references (or values) in a contiguous block of memory. The address of element i is:

address=base_address+i×size_of_pointer\text{address} = \text{base\_address} + i \times \text{size\_of\_pointer}address=base_address+i×size_of_pointer

This calculation takes constant time — no matter how large the list, accessing any single element is O(1)O(1)O(1). This assumption underlies all loop analyses where indexing into a list is considered a constant operation.


Examples of Common Algorithmic Complexities

Simple Iterative Loops — Linear O(n)O(n)O(n)

1. Linear search (unsorted list):

def linear_search(L, e):
    found = False
    for i in range(len(L)):
        if L[i] == e:
            found = True
    return found

Loop runs n times (worst case), each iteration constant → O(n)O(n)O(n).

Even with early return:

def linear_search_early(L, e):
    for i in range(len(L)):
        if L[i] == e:
            return True
    return False

Worst case still examines all n elements → O(n)O(n)O(n) (though average improves).

2. Summing digits of a string:

def sum_digits(s):
    total = 0
    for char in s:
        total += int(char)
    return total

Loop runs len(s) times, constant work per character → O(n)O(n)O(n) where n=len(s)n = \text{len}(s)n=len(s).

3. Iterative factorial:

def fact_iter(n):
    answer = 1
    while n > 1:
        answer *= n
        n -= 1
    return answer

Loop executes n−1n-1n−1 iterations, each with constant operations → O(n)O(n)O(n).

Why these are all O(n)O(n)O(n):

  • Each contains a loop that iterates n times (or proportional to input size)

  • Inside the loop, a constant number of primitive operations

Using a Sorted List — Still Linear

If the list is sorted, we can stop early:

def search_sorted(L, e):
    for i in range(len(L)):
        if L[i] == e:
            return True
        if L[i] > e:
            return False   # since sorted, no need to continue
    return False
  • Average case improves (stop halfway on average)

  • Worst case: element larger than all list elements, or element not present and larger than last element — must examine entire list → O(n)O(n)O(n).

Thus sorting does not change the asymptotic worst-case complexity of linear search, though it improves practical runtime. (Next lecture: better algorithms for sorted data.)

Nested Loops — Quadratic O(n2)O(n^2)O(n2)

1. Subset check: Is list L1 a subset of list L2?

def is_subset(L1, L2):
    for e1 in L1:                # O(len(L1))
        match = False
        for e2 in L2:            # O(len(L2))
            if e1 == e2:
                match = True
                break
        if not match:
            return False
    return True
  • Outer loop: len(L1) times

  • Inner loop: up to len(L2) times per outer iteration

  • Worst case: L1 and L2 have same length n, and no elements of L1 are in L2 → inner loop runs fully each time → O(n2)O(n^2)O(n2)

2. Intersection of two lists:

def intersect(L1, L2):
    temp = []
    for e1 in L1:
        for e2 in L2:
            if e1 == e2:
                temp.append(e1)
                break
    # Remove duplicates:
    result = []
    for e in temp:
        if e not in result:   # implicit O(len(result))
            result.append(e)
    return result
  • First nested loop: O(n2)O(n^2)O(n2) (if lists size n)

  • Second loop: iterates temp (max length n), and e not in result can be O(n)O(n)O(n) — so second part is also O(n2)O(n^2)O(n2).

  • Overall: O(n2)O(n^2)O(n2)

Why nested loops tend to be quadratic:

If the outer loop runs n times and the inner loop runs m times (often ~n), the total work is O(n×m)O(n \times m)O(n×m). When m=nm = nm=n, we get O(n2)O(n^2)O(n2).


Summary of Complexity Classes

Class

Symbol

Description

Example

Constant

O(1)O(1)O(1)

Runtime independent of input size

Accessing a list element L[i]

Logarithmic

O(log⁡n)O(\log n)O(logn)

Grows slowly, each step cuts problem size

Binary search (next lecture)

Linear

O(n)O(n)O(n)

Runtime proportional to input size

Linear search, iterative sum

Log-linear

O(nlog⁡n)O(n \log n)O(nlogn)

Common in efficient sorting algorithms

Merge sort, quicksort average

Quadratic

O(n2)O(n^2)O(n2)

Runtime proportional to square of input size

Nested loops, all pairs

Exponential

O(2n)O(2^n)O(2n)

Grows extremely fast; often infeasible

Recursive Fibonacci without memoization

Numeric comparison (approximate operations for given n):

n

O(1)O(1)O(1)

O(log⁡n)O(\log n)O(logn)

O(n)O(n)O(n)

O(nlog⁡n)O(n \log n)O(nlogn)

O(n2)O(n^2)O(n2)

O(2n)O(2^n)O(2n)

10

1

~3

10

~33

100

1024

100

1

~7

100

~664

10,000

~10³⁰

1,000

1

~10

1,000

~9,966

1,000,000

enormous

1,000,000

1

~20

1,000,000

~19,931,568

10¹²

astronomical

The goal when designing algorithms is to achieve a complexity as close to the top of this table as possible. Exponential algorithms are typically impractical for any but the smallest inputs.


Key Takeaways for Algorithm Analysis

  1. Identify the input size parameter (e.g., length of list, value of integer, number of nodes).

  2. Decide worst-case scenario — the input that leads to the most operations.

  3. Count operations in terms of that input size, but drop constants and lower-order terms.

  4. Use the laws of addition and multiplication to combine blocks.

  5. Recognize common patterns:

    • Single loop → O(n)O(n)O(n)

    • Nested loops → often O(n2)O(n^2)O(n2)

    • Constant-time operations (indexing, arithmetic) inside loops don't change the order.

  6. A more sophisticated algorithm (e.g., using divide and conquer or a sorted structure) can often move a problem from a worse class to a better one, which is far more impactful than optimizing constant factors.

Next lecture: exploring logarithmic and log-linear algorithms, recursion analysis, and the trade-off between time and space.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent