Skip to content
PythonAlgorithms and Capstone Practicebeginner30 min read

Complexity: Time and Space

Analyze how algorithms scale using Big O, common growth rates, auxiliary space, loops, and recursion.

In this lesson, you will learn

  • ✓Explain time complexity, space complexity, and auxiliary space in simple terms.
  • ✓Understand Big O notation and distinguish constant, logarithmic, linear, linearithmic, quadratic, and exponential growth.
  • ✓Analyze single loops, nested loops, sequential loops, and loops that repeatedly halve their input.
  • ✓Estimate the time and auxiliary space complexity of common Python operations and algorithms.
  • ✓Analyze best-case, average-case, and worst-case behavior where appropriate.
  • ✓Recognize the space costs of creating collections and making recursive calls.
  • ✓Compare alternative solutions and justify a suitable approach using complexity analysis.

1. What are time and space complexity?

Suppose you need to find a number in a list. If the list contains five elements, checking them one by one is usually easy. If it contains five million elements, the amount of work may be much greater. Complexity analysis studies how the required resources grow as the input becomes larger.

Time complexity describes how the amount of computational work grows with input size. It is not the exact time in seconds that a program takes. Actual runtime also depends on the computer, Python implementation, operating system, and other factors.

Space complexity describes how memory requirements grow with input size. Auxiliary space is the additional working memory an algorithm uses, excluding the input storage itself under the common interview convention. Some problems ask for total space instead, which includes input storage and other memory used by the algorithm.

We usually represent the input size with n. For a list, n commonly means the number of elements. For a string, n may mean its number of characters. For a matrix, the relevant sizes may be its number of rows and columns.

A function that checks every element

A function that checks every element
python
def print_items(items):
for item in items:
print(item)
 
print_items([10, 20, 30])
Output
10 20 30

If the list contains three elements, the loop body executes three times. If it contains n elements, the loop body executes n times. The running work grows proportionally to n, so the time complexity is O(n). The function does not create another collection proportional to the input size. Ignoring the output device and fixed runtime overhead, its auxiliary space is O(1).

Note

Always identify what n represents before analyzing an algorithm. Complexity statements are meaningful only when the input-size assumption is clear.

2. Understand Big O notation

Big O notation describes an upper bound on how an algorithm's resource usage grows, ignoring constant factors and lower-order terms. In introductory algorithm analysis, it is commonly used to communicate the dominant growth rate, often for the worst case.

For example, an algorithm that performs 3n + 5 basic operations has O(n) growth. As n becomes large, the linear term dominates the fixed overhead. Big O does not say that the algorithm takes exactly n operations or n seconds.

When simplifying a growth expression, retain its dominant term. For example, O(n² + n + 10) simplifies to O(n²). Similarly, O(4n + 20) simplifies to O(n).

Big O is not the only asymptotic notation. Big Omega, written Ω, expresses an asymptotic lower bound, while Big Theta, written Θ, expresses a tight asymptotic bound when both upper and lower bounds match. For a beginner, focus first on recognizing the common Big O growth patterns.

Ignore constants and smaller terms

Ignore constants and smaller terms
python
def example(n):
for i in range(n):
print(i)
 
for i in range(n):
print(i)
 
print("Finished")
Output
For non-negative n: O(n) time.

The first loop executes n times and the second loop also executes n times. Together, the loops perform 2n iterations, followed by one fixed print operation. The work can be represented as 2n + 1, which simplifies to O(n). Two sequential linear loops are still linear; their iteration counts are added, not multiplied.

Note

Big O describes growth, not a benchmark. Two O(n) algorithms can have very different actual runtimes because of constants, implementation details, and the operations performed.

3. The most common complexity classes

Different algorithms grow at different rates. Learning the common patterns helps you estimate complexity by looking at code structure.

O(1), constant time, means the amount of work remains bounded as n grows. O(log n), logarithmic time, often appears when an algorithm repeatedly reduces a problem by a constant factor. O(n), linear time, commonly appears when each input element is processed a constant number of times.

O(n log n), linearithmic time, appears in many efficient comparison-sorting algorithms. O(n²), quadratic time, often appears when each element is compared with many other elements using nested loops. O(2ⁿ), exponential time, can appear in algorithms that branch into two recursive subproblems at each level without avoiding repeated work.

These are common patterns, not universal rules. The actual complexity depends on how many operations execute and how the input changes.

Recognize common growth patterns

Recognize common growth patterns
python
# O(1): one fixed-index access
value = values[0]
 
# O(n): process each element once
for item in values:
print(item)
 
# O(n^2): compare every pair of positions
for i in range(n):
for j in range(n):
print(i, j)
Output
The three patterns are O(1), O(n), and O(n²), respectively, under the usual assumptions.

A valid list access at a fixed index takes constant time under the usual Python list model. The single loop processes n elements, giving linear work. The nested loops execute n times for each of n outer iterations, giving n × n = n² iterations. The code is illustrative: values and n must be defined before running it, and the list must contain the indexed element.

Note

For two different input dimensions, use both variables when needed. For example, traversing a matrix with r rows and c columns takes O(r × c) time, rather than automatically writing O(n²).

4. Constant time: O(1)

An operation is O(1) when its work does not grow with the input size under the chosen computational model. It may perform several instructions; the important point is that their number remains bounded.

Accessing an existing Python list element by a valid integer index is typically O(1). Assigning a value to an existing list position is also typically O(1).

Be careful not to classify an entire function as O(1) merely because it contains one indexed access. If the function also loops over the list, the loop may dominate the total complexity.

Access one element by index

Access one element by index
python
values = [10, 20, 30, 40]
print(values[2])
Output
30

Python retrieves the element at index 2, which is 30. For a built-in list, indexed access is typically O(1). The access does not scan the list from the beginning to locate the third element. The list must contain a valid index; an invalid index raises IndexError.

5. Linear time: O(n)

Linear time means the amount of work grows in proportion to the input size. A loop that visits every element once is the standard example.

Searching for a target using a simple linear scan is O(n) in the worst case because the target may be absent or appear at the final position.

Best-case complexity can be different. If a linear search finds the target at the first position, it performs one comparison, giving O(1) best-case time. Its worst-case time remains O(n).

A loop may stop early, so analyze the number of iterations for the case you are describing. Do not assume every execution of a loop visits every element.

Linear search

Linear search
python
def contains_value(items, target):
for item in items:
if item == target:
return True
return False
 
print(contains_value([2, 4, 6], 4))
print(contains_value([2, 4, 6], 9))
Output
True False

For target 4, the function checks 2 and then 4 before returning True. For target 9, it checks all three elements before returning False. The best case is O(1), when the first comparison succeeds. The worst case is O(n), when the target is absent or found at the last position. The algorithm uses O(1) auxiliary space because it does not build another collection.

6. Logarithmic time: O(log n)

Logarithmic growth often occurs when each step reduces the remaining problem by a constant factor, such as dividing the search range in half.

Binary search is a classic example. It requires sorted data and repeatedly compares the target with the middle element, discarding half of the remaining search range after each comparison.

If the number of candidates is n, repeatedly halving the range takes approximately log₂(n) steps. Changing the logarithm's base changes only a constant factor, so the base is normally omitted in Big O notation.

A loop that repeatedly divides a positive integer by two is another common O(log n) pattern. Be precise about the input domain and stopping condition when analyzing such loops.

Count how many times a number can be halved

Count how many times a number can be halved
python
def count_halvings(n):
steps = 0
while n > 1:
n //= 2
steps += 1
return steps
 
print(count_halvings(16))
print(count_halvings(10))
Output
4 3

For 16, the values are 16, 8, 4, 2, and 1. The loop executes four times. For 10, the values are 10, 5, 2, and 1. The loop executes three times. For positive n, the number of iterations grows logarithmically, so the time complexity is O(log n). The function uses O(1) auxiliary space because it maintains only a fixed number of variables.

Note

Binary search is not automatically applicable to an unsorted list. Its usual O(log n) search time relies on being able to discard half the remaining candidates after each comparison.

7. Nested loops and quadratic time: O(n²)

Nested loops often produce quadratic time when both loops execute n times for each input of size n.

If the outer loop executes n times and the inner loop executes n times for every outer iteration, the total number of inner executions is n × n = n².

Nested loops do not always imply O(n²). The inner loop may run a fixed number of times, may shrink, or may depend on a different input size. Always count the actual iterations.

Quadratic algorithms can be perfectly reasonable for small inputs, but their growth can become expensive as n increases.

Print every ordered pair of positions

Print every ordered pair of positions
python
def print_pairs(n):
for i in range(n):
for j in range(n):
print(i, j)
 
print_pairs(2)
Output
0 0 0 1 1 0 1 1

The outer loop runs twice when n is 2. For each outer iteration, the inner loop also runs twice. The total number of print operations is 2 × 2 = 4. For general n, the function prints n² pairs, giving O(n²) time. The loops themselves use O(1) auxiliary space, excluding the output stream and runtime overhead.

8. Sequential loops, dependent loops, and different input sizes

When loops execute one after another, add their work. A loop that runs n times followed by another loop that runs n times performs approximately 2n iterations, which is O(n), not O(n²).

When the inner loop's range depends on the outer loop, count the total iterations carefully. For example, if the inner loop runs i times on outer iteration i, the total is 0 + 1 + 2 + ... + (n - 1), which equals n(n - 1)/2 and therefore grows as O(n²).

When the algorithm processes two different inputs, such as two lists of lengths n and m, the complexity may be O(n + m) or O(n × m). Do not combine the variables unless you have a justified relationship between their sizes.

Sequential loops

Sequential loops
python
def process_two_lists(first, second):
for item in first:
print(item)
 
for item in second:
print(item)
 
process_two_lists([1, 2], [8, 9, 10])
Output
1 2 8 9 10

Let the first list contain n elements and the second contain m elements. The first loop performs n iterations and the second performs m iterations. The total work grows as n + m, so the time complexity is O(n + m). If both lists have n elements, this becomes O(2n), which simplifies to O(n).

9. Linearithmic and exponential growth

O(n log n) is called linearithmic growth. It commonly appears in efficient comparison-based sorting algorithms, including Python's built-in sorting implementation in typical worst-case analysis. The exact guarantees depend on the algorithm being analyzed.

O(2ⁿ) is exponential growth. A simple recursive algorithm that explores two branches for each input position can produce a number of calls proportional to 2ⁿ if it repeats work without pruning or memoization.

Exponential algorithms can become impractical quickly even when n is not particularly large. However, not every recursive algorithm is exponential: the number and size of subproblems determine the recurrence and its complexity.

Python sorting

Python sorting
python
numbers = [8, 3, 6, 1, 5]
print(sorted(numbers))
Output
[1, 3, 5, 6, 8]

sorted() returns a new list containing the values in ascending order. Python uses Timsort for list sorting. Its worst-case time complexity is O(n log n), and it can perform better on data with existing ordered runs. Because sorted() creates a new result list, it uses additional storage proportional to the input size. Its auxiliary space usage can depend on the sorting implementation and input pattern. This is a practical example of choosing a well-implemented standard-library operation rather than writing a sorting algorithm without a reason.

Note

Repeated subproblems can make recursion much slower than necessary. Memoization or dynamic programming may reduce the number of repeated calculations, depending on the problem.

10. Space complexity and auxiliary space

Space complexity measures how memory use grows with input size. In interview discussions, clarify whether you are measuring auxiliary space or total space.

Auxiliary space is the extra working memory beyond the input, using the common convention that input storage is excluded. A function that keeps only a few counters and references can use O(1) auxiliary space even when it processes a list of n elements.

A new list that stores n results typically uses O(n) additional space. A two-dimensional n by n collection can use O(n²) space because it stores n² entries.

Space includes more than named lists and dictionaries. Recursive calls consume call-stack space, and temporary data structures may consume memory even if they are not returned.

Constant auxiliary space

Constant auxiliary space
python
def count_positive(numbers):
count = 0
for number in numbers:
if number > 0:
count += 1
return count
 
print(count_positive([-2, 4, 0, 7, -1]))
Output
2

The function visits each input number and updates a single counter. It does not build a new list containing the positive values. The time complexity is O(n) because each element is inspected once. The auxiliary space complexity is O(1), excluding the input list.

11. Recursion and space complexity

Recursive functions use the call stack. Each call remains active while it waits for the next call to finish, so the maximum number of simultaneous calls matters for auxiliary space.

A simple recursive function that decreases n by one until it reaches zero usually has O(n) call-stack space. An iterative version of the same computation may need only O(1) auxiliary space.

The total number of recursive calls is not always the same as the maximum call-stack depth. A branching recursive function can make exponentially many calls over its entire execution while maintaining only a linear maximum depth.

The recursion limit can constrain the size of inputs a recursive Python solution can handle. Increasing the recursion limit without understanding the risks is not a general solution to an inefficient or deeply recursive algorithm.

Recursive and iterative sums

Recursive and iterative sums
python
def recursive_sum(n):
if n == 0:
return 0
return n + recursive_sum(n - 1)
 
def iterative_sum(n):
total = 0
for number in range(1, n + 1):
total += number
return total
 
print(recursive_sum(4))
print(iterative_sum(4))
Output
10 10

Both implementations calculate the same result for the non-negative input 4. Both perform O(n) work in the usual analysis. The recursive implementation uses O(n) call-stack space because it creates a chain of active calls. The iterative implementation uses O(1) auxiliary space because it maintains only a fixed number of variables. For large inputs, the iterative approach avoids the recursive call-depth limitation.

12. Best case, average case, and worst case

An algorithm's complexity can depend on the input, even when the input size is the same. Best-case complexity describes the most favorable inputs, worst-case complexity describes the least favorable inputs, and average-case complexity describes expected behavior under a specified input distribution.

For linear search, the best case is O(1) when the target is the first element. The worst case is O(n) when the target is absent or at the end. An average-case claim requires assumptions about how likely each position is and whether the target is present.

Always state which case you are describing when it matters. A statement such as 'linear search is O(n)' usually refers to its worst-case running time in introductory interview analysis, but the best case is different.

Count comparisons in linear search

Count comparisons in linear search
python
def comparisons_for_search(items, target):
comparisons = 0
for item in items:
comparisons += 1
if item == target:
return comparisons
return comparisons
 
print(comparisons_for_search([5, 8, 9, 12], 5))
print(comparisons_for_search([5, 8, 9, 12], 12))
print(comparisons_for_search([5, 8, 9, 12], 99))
Output
1 4 4

The first search succeeds immediately, so it performs one comparison. The second search finds the target at the final position and performs four comparisons. The third search never finds the target and also performs four comparisons. These results illustrate the O(1) best case and O(n) worst case for linear search.

13. Analyze Python operations carefully

Knowing common Python operation costs helps you analyze real code. These are typical complexities for Python's built-in data structures under the usual algorithm-analysis model, not guarantees for every possible object or runtime situation.

List indexing is typically O(1). Searching a list with membership, such as target in items, is O(n) in the worst case. Appending to a Python list is amortized O(1), meaning most appends are constant time while occasional resizes take longer.

Inserting at the beginning of a list or deleting an element near the beginning generally takes O(n), because later elements may need to be shifted. Dictionary key lookup is typically O(1) on average and O(n) in the worst case, depending on hashing and collisions.

A function's total complexity must account for the operations it calls. For example, using target in a list inside a loop over another list can produce O(n × m) time when the list lengths are n and m.

A nested search can become quadratic

A nested search can become quadratic
python
def common_items(first, second):
result = []
for item in first:
if item in second:
result.append(item)
return result
 
print(common_items([1, 2, 3], [2, 3, 4]))
Output
[2, 3]

The outer loop visits each element of first. If first has n elements, it runs n times. The expression item in second performs a list membership search. In the worst case, it scans m elements of second. The combined worst-case search work is O(n × m). If both lists have n elements, this becomes O(n²). The result list can contain up to n elements, so the auxiliary space is O(n), excluding the input lists. For large inputs, converting second to a set may improve average membership lookup performance, but creating the set uses additional memory and requires hashable elements.

Note

Average-case dictionary lookup and amortized list append are useful interview distinctions. Avoid describing them as unconditional worst-case O(1) operations.

14. A practical method for analyzing complexity

You do not need to guess complexity from the appearance of code. Follow a repeatable process: identify the input size, count the repeated work, combine the costs, simplify the dominant term, and analyze additional memory.

For loops, estimate the number of iterations. For nested loops, multiply iteration counts when each inner loop repeats fully, or sum the counts when the inner loop depends on the outer index. For recursion, examine how many calls are made and how deep the call chain becomes.

Finally, state your assumptions. Are you analyzing worst-case time? Does the input already exist? Are you counting the returned collection as auxiliary space? Clear assumptions make the complexity claim more useful and less ambiguous.

Analyze a simple algorithm

Analyze a simple algorithm
python
def transform(numbers):
result = []
for number in numbers:
result.append(number * 2)
return result
 
print(transform([1, 2, 3]))
Output
[2, 4, 6]

Step 1: Let n be the number of elements in numbers. Step 2: The loop runs n times, and each iteration performs constant work plus an amortized constant-time append. Step 3: Total time grows linearly, so time complexity is O(n). Step 4: The result list can hold n elements, so auxiliary space is O(n). Step 5: The function returns a new list and leaves the input list unchanged.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Thinking Big O tells you the exact number of seconds a program takes.

Why it happens: Big O describes how resource use scales with input size, not an exact runtime in seconds; real timing also depends on hardware, implementation, and data.

Incorrect Approach
script.py
python
Thinking Big O tells you the exact number of seconds a program takes.
Correct Solution
script.py
python
Big O describes how resource requirements grow as input size increases. Actual runtime also depends on hardware, implementation, and constant factors.

Key takeaway: Big O describes how resource requirements grow as input size increases. Actual runtime also depends on hardware, implementation, and constant factors.

#2 Multiplying the complexity of all loops, even when they run sequentially.

Why it happens: Sequential loops contribute additive costs, which are often simplified by the dominant term, rather than multiplying their complexities.

Incorrect Approach
script.py
python
Multiplying the complexity of all loops, even when they run sequentially.
Correct Solution
script.py
python
Add the costs of sequential loops. Multiply iteration counts for genuinely nested loops when their work repeats for each outer iteration.

Key takeaway: Add the costs of sequential loops. Multiply iteration counts for genuinely nested loops when their work repeats for each outer iteration.

#3 Assuming every nested loop is O(n²).

Why it happens: A nested loop is quadratic only when the total number of iterations grows proportionally to n squared; loop bounds and dependencies matter.

Incorrect Approach
script.py
python
Assuming every nested loop is O(n²).
Correct Solution
script.py
python
Count how many times the inner loop runs. A fixed three-iteration inner loop inside an n-iteration outer loop is O(n), not O(n²).

Key takeaway: Count how many times the inner loop runs. A fixed three-iteration inner loop inside an n-iteration outer loop is O(n), not O(n²).

#4 Calling list membership O(1).

Why it happens: List membership usually scans elements and is O(n) on average, unlike average-case set or dictionary membership which is typically O(1).

Incorrect Approach
script.py
python
Calling list membership O(1).
Correct Solution
script.py
python
Membership testing on a list is O(n) in the worst case. Average dictionary or set membership is typically O(1), subject to hashing assumptions.

Key takeaway: Membership testing on a list is O(n) in the worst case. Average dictionary or set membership is typically O(1), subject to hashing assumptions.

#5 Confusing time complexity with space complexity.

Why it happens: Time complexity describes operation growth, while space complexity describes memory growth; an algorithm can be fast but memory-intensive.

Incorrect Approach
script.py
python
Confusing time complexity with space complexity.
Correct Solution
script.py
python
Analyze the amount of work and the memory used separately. An algorithm can take O(n) time and use either O(1) or O(n) auxiliary space.

Key takeaway: Analyze the amount of work and the memory used separately. An algorithm can take O(n) time and use either O(1) or O(n) auxiliary space.

#6 Ignoring a new list, dictionary, or recursive call stack.

Why it happens: New collections and recursive calls can allocate additional memory, so account for auxiliary data structures and call-stack depth.

Incorrect Approach
script.py
python
Ignoring a new list, dictionary, or recursive call stack.
Correct Solution
script.py
python
Count additional collections and active recursive calls when analyzing auxiliary space.

Key takeaway: Count additional collections and active recursive calls when analyzing auxiliary space.

#7 Dropping important input dimensions.

Why it happens: When input dimensions vary independently, such as rows and columns, retain each dimension in the analysis instead of assuming they are equal.

Incorrect Approach
script.py
python
Dropping important input dimensions.
Correct Solution
script.py
python
Use O(n + m) or O(n × m) when two input sizes vary independently. Only simplify to one variable when their relationship is justified.

Key takeaway: Use O(n + m) or O(n × m) when two input sizes vary independently. Only simplify to one variable when their relationship is justified.

#8 Assuming O(n) always means slower than O(log n) for every possible input.

Why it happens: Asymptotic growth describes behavior as input grows; constant factors and small inputs can make an O(n) method faster for some practical cases.

Incorrect Approach
script.py
python
Assuming O(n) always means slower than O(log n) for every possible input.
Correct Solution
script.py
python
Asymptotic growth describes behavior as inputs become large. Constants and small-input overhead can affect actual performance on small datasets.

Key takeaway: Asymptotic growth describes behavior as inputs become large. Constants and small-input overhead can affect actual performance on small datasets.

#9 Assuming every recursive algorithm is exponential.

Why it happens: Recursive algorithms can have linear, logarithmic, exponential, or other complexity depending on the recurrence and repeated work.

Incorrect Approach
script.py
python
Assuming every recursive algorithm is exponential.
Correct Solution
script.py
python
Analyze the number of recursive calls and the recurrence. Linear recursion, divide-and-conquer recursion, and branching recursion can have very different complexities.

Key takeaway: Analyze the number of recursive calls and the recurrence. Linear recursion, divide-and-conquer recursion, and branching recursion can have very different complexities.

#10 Claiming O(1) auxiliary space while creating a result proportional to the input.

Why it happens: Auxiliary space includes temporary results and other extra storage, so creating a list proportional to input size is not O(1) auxiliary space.

Incorrect Approach
script.py
python
Claiming O(1) auxiliary space while creating a result proportional to the input.
Correct Solution
script.py
python
If an algorithm creates a list that can contain n elements, count O(n) additional storage unless the problem explicitly excludes that output.

Key takeaway: If an algorithm creates a list that can contain n elements, count O(n) additional storage unless the problem explicitly excludes that output.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is time complexity?
Answer:
Time complexity describes how an algorithm's computational work grows with input size. It is commonly expressed using asymptotic notation such as O(1), O(log n), O(n), and O(n²). It does not directly specify the runtime in seconds.
Q2:What is space complexity, and how does auxiliary space differ?
Answer:
Space complexity describes how memory requirements grow with input size. Auxiliary space refers to additional working memory beyond the input under the common interview convention. State clearly whether your analysis includes the input and returned output.
Q3:What does Big O notation mean?
Answer:
Big O expresses an asymptotic upper bound on growth. In introductory analysis, it is often used to describe worst-case growth. Constant factors and lower-order terms are omitted, so 3n + 5 is O(n), and n² + n is O(n²).
Q4:What is the difference between O(1), O(log n), and O(n)?
Answer:
O(1) describes bounded work independent of input size. O(log n) often occurs when each step reduces the remaining problem by a constant factor. O(n) describes work proportional to the number of input elements, such as a full linear scan.
Q5:Why are two sequential loops usually O(n), but two fully nested loops often O(n²)?
Answer:
Sequential loops perform approximately n + n = 2n iterations, which simplifies to O(n). Fully nested loops with n inner iterations for each of n outer iterations perform n × n = n² iterations. The actual loop bounds must be examined before making this conclusion.
Q6:What is the worst-case time complexity of linear search?
Answer:
O(n), because the target may be absent or appear at the final position. Its best case is O(1) if the first element matches.
Q7:Why is binary search O(log n)?
Answer:
Binary search repeatedly eliminates approximately half of the remaining candidates. The number of halvings needed to reduce n candidates to one is logarithmic. The standard algorithm requires sorted data and appropriate access to the middle element.
Q8:What are the typical complexities of Python list indexing, membership, and append?
Answer:
Valid integer-index access is typically O(1). List membership is O(n) in the worst case because elements may need to be checked one by one. Appending to a Python list is amortized O(1), with occasional resizing operations that take longer.
Q9:What is the time and space complexity of a recursive sum that calls itself with n - 1 until zero?
Answer:
For a function that performs constant additional work per call, the time complexity is O(n). Its maximum call-stack depth is O(n), so its auxiliary stack space is also O(n).
Q10:How do you analyze a function that loops through one list and checks membership in another list?
Answer:
If the first list has n elements and the second has m elements, the outer loop executes n times. Each list membership test can take O(m) worst-case time, giving O(n * m) total worst-case time. The result's storage must be analyzed separately.
Q11:What is the difference between O(n log n) and O(n²)?
Answer:
O(n log n) grows more slowly than O(n²) as n becomes large. Many efficient comparison-based sorting algorithms have O(n log n) worst-case time, while algorithms that compare every pair using two full nested loops commonly take O(n²).
Q12:Does a recursive algorithm always have exponential time complexity?
Answer:
No. Complexity depends on the recurrence and how many subproblems are solved. A single recursive call on n - 1 can lead to O(n) time, while branching into two recursive calls of size n - 1 without eliminating repeated work can lead to O(2ⁿ) time.

Key takeaways

  • Time complexity describes how computational work grows; space complexity describes how memory requirements grow.
  • Big O describes asymptotic growth, not exact runtime in seconds.
  • Common growth rates include O(1), O(log n), O(n), O(n log n), O(n²), and O(2ⁿ).
  • Sequential loops add their work; fully nested loops often multiply their iteration counts.
  • Always count actual iterations rather than judging complexity from the number of loops alone.
  • Python list indexing is typically O(1), list membership is O(n) in the worst case, and list append is amortized O(1).
  • A new list containing up to n elements uses O(n) additional storage.
  • Simple recursion that decreases n by one typically takes O(n) time and O(n) call-stack space.
  • State whether you are discussing best-case, average-case, or worst-case behavior when the distinction matters.
  • For multiple input sizes, use expressions such as O(n + m) or O(n * m) when appropriate.
  • Analyze time and space separately, and make your input and memory assumptions explicit.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: