Big-O Notation: Algorithm Analysis

Learn to predict how the running time and memory use of an algorithm grow as its input grows. Count operations, tell apart the worst, best and average case, and describe growth with Big-O, Big-Omega and Big-Theta notation. Compare the common growth rates from constant to factorial, analyze loops, nested loops and Python built-in operations, measure extra memory and its trade-off with speed, and see why appending to a list is cheap over many operations even when a single append is slow.

IntermediateLesson 1 of 10 in Data Structures and Algorithms Course

What you will learn

  1. Describe an algorithm's running time as a count of basic operations that depends on the input size, and tell apart the worst, best and average case.
    • Choose an input size and a cost model
      Explain why algorithms are analyzed by counting operations rather than by timing alone, and decide what the input size is and which operations to count.
    • Count the operations in simple code
      Count how many times each statement runs in straight-line code, single loops and conditionals, and express the total as a function of the input size.
    • Distinguish worst, best and average cases
      Find the inputs of a given size that make an algorithm do the most and the least work, compute an average under a stated assumption, and say why the worst case is usually reported.
  2. Use Big-O, Big-Omega and Big-Theta to state upper, lower and tight bounds on how a cost grows, prove simple bounds from the definitions and simplify expressions correctly.
    • Define and prove Big-O upper bounds
      State the formal definition of Big-O, prove and disprove bounds by finding constants, and explain why constant factors and lower-order terms are dropped.
    • Use Big-Omega and Big-Theta for lower and tight bounds
      Define lower and tight bounds, prove them for simple functions and attach them correctly to the worst, best and average case.
    • Simplify expressions with the rules of asymptotic notation
      Apply the rules for constant factors, sums, products, polynomials, logarithms and several input sizes to reduce a cost expression to its simplest correct form.
  3. Rank the growth rates that appear most often in algorithms, recognize where logarithms come from, and use growth rates to predict running times and check them by experiment.
    • Rank the common growth rates and match them to algorithms
      Order the standard growth rates, name them, link each to a typical algorithm and judge which are practical for large inputs.
    • Recognize logarithmic growth
      Explain what a logarithm counts in an algorithm, count the iterations of halving and doubling loops, and see where logarithmic and linearithmic costs come from.
    • Predict performance and test it by timing
      Use a growth rate to predict how running time changes with input size, check the prediction with a doubling experiment, and explain when constant factors decide which algorithm is faster.
  4. Work out the running time of code with sequential, nested and dependent loops, including the cost hidden inside built-in operations, and state the result with the right notation and case.
    • Analyze sequential and nested loops
      Follow a step-by-step method to find the running time of code built from loops one after another and loops inside loops.
    • Count iterations of dependent and non-uniform loops
      Add up loop counts when an inner loop's range depends on the outer loop, using arithmetic and geometric series, and analyze while loops by tracking what changes each iteration.
    • Account for the hidden cost of built-in operations
      Recognize which Python list, set and dictionary operations take constant time and which hide a loop, and include their cost when analyzing a complete function.
  5. Measure how much extra memory an algorithm needs as the input grows, and choose between solutions that trade memory for time.
    • Measure the extra memory an algorithm uses
      Distinguish total from auxiliary space, find the space used by variables, new collections, copies, output and the call stack, and report it in asymptotic notation.
    • Trade memory for time
      Recognize time–space trade-offs, use stored information to speed up repeated work, and choose a solution that fits the time and memory available.
  6. Explain why some operations that are occasionally expensive are cheap when averaged over a sequence, and bound the total work of a sequence by counting how often each unit of work can happen.
    • Explain the amortized cost of appending to a dynamic array
      Show why appending to a growing array costs constant time per operation over any sequence of appends, and how the growth policy decides this.
    • Bound the total work of a sequence of operations
      Use aggregate counting to show that loops and data-structure operations which are sometimes expensive do only a limited amount of work in total.

Big-O Notation study guide

6 chapters

1

Measure the cost of an algorithm

Running time begins with a count of work. Choose what the input size measures, decide which operations matter, and follow how often they execute. Inputs of the same size can still produce different counts, so a useful analysis separates the best, worst and average cases. These choices turn a vague claim that code is "slow" into a cost function you can explain and compare before measuring an implementation.

1.1 Input size and the work you count

A useful performance question starts with what can grow. A function that scans a list has more work when the list contains more items. A function that compares two lists can depend on both lengths. Input size gives those quantities names so that the cost can be expressed as a function.

Choose the size before counting

Use n for a list's length or a string's character count. If two independent lists have lengths n and m, keep both names. Scanning each list once involves n+m item visits. Comparing every item of one with every item of the other involves nm comparisons. Replacing both lengths with one symbol would hide an important difference when one list is much longer.

For a whole-number input, distinguish its value from the length of its representation. A loop over range(2, n) makes n−2 visits for an integer n≥2. This is linear in the value. An extra decimal digit allows values about ten times as large, so that same count grows exponentially with the number of digits. The size measure belongs in the analysis.

State a cost model

A cost model says which work counts as a step. In the random-access machine, or RAM, model, reading a list slot, assigning a variable, and comparing or adding fixed-size numbers each take constant time. Calling a function has fixed overhead, but its body can still do work that grows with the input. Python integers can grow; the fixed-size-number model is what makes arithmetic a constant-time step in these examples.

Often one operation captures the growth: count comparisons in a search or additions in a sum. This is the dominant operation. It represents the whole running time when the remaining work is bounded by a fixed amount per counted operation, plus fixed setup work.

Consider:

def total(items):
    result = 0
    for value in items:
        result += value
    return result

Counting the initial assignment, each addition and the return gives T(n)=n+2. Counting each item fetch as well gives T(n)=2n+2. The exact counts differ because the cost models differ. Both grow in proportion to the list length.

Open up calls that hide work

A short expression can scan a large collection. sum(items), max(items) and items.copy() process the whole list. len(items) and items[i] take constant time for a Python list. Membership, target in items, can stop at a match: it checks one item when the target is first and up to n when it is last or absent. Counting each written line once misses these costs.

A timer answers a separate practical question. time.perf_counter() measures elapsed time on a particular machine and input. Other running programs, language overhead and hardware affect the result. Operation counts describe growth independently of those measured seconds; timing later checks how an implementation behaves in practice. Record time as T(n) and memory as S(n), since an algorithm can use little of one resource and much of the other.

Key Takeaways

  • Name every independent input size.
  • State what counts as one operation.
  • Include the work inside function calls.
  • Distinguish numeric value from representation length.

1.2 Count executions, then combine their costs

The cost of code depends on how many times its work executes. A line outside a loop may run once; the same line inside a loop may run thousands of times. Begin with an exact count when the code makes one available, then describe how that count grows.

Fixed work and repeated work

Swapping two list entries with a temporary variable takes three assignments. Those assignments take the same amount of work for a list of ten items and a list of a million items. A fixed loop can also have constant cost: visiting the 26 letters in 'abcdefghijklmnopqrstuvwxyz' always makes 26 visits.

A loop over items makes n visits for n items. If the body costs a fixed amount, the loop's cost is proportional to n. Loop bookkeeping also repeats: fetching the next item and testing whether work remains must be accounted for in a detailed count. These details change constant factors without changing linear growth.

For a running sum, count one initialization, n additions and one return. The chosen model gives n+2 steps. If an addition and its assignment are counted separately, the expression changes, but the dependence on n remains linear.

Check the endpoints

To find the largest item in a nonempty list, begin with best = items[0] and compare the remaining items with best. There are exactly n−1 comparisons, even if the list is already in increasing order. Updates to best depend on the data; the comparison count does not.

For range(0, n, 2), the visited indices are 0, 2, 4 and so on, stopping before n. The count is ⌈n/2⌉. With ten items it is 5; with eleven it is 6. The ceiling handles the leftover item. A step of 2 halves the work approximately but still leaves a count proportional to n.

Add sequential work
for value in items:
    inspect(value)
for value in items:
    record(value)

If each call has constant cost, this code makes 2n calls. The second loop runs after the first has finished. It is not run once for every iteration of the first loop. Sequential costs add; a loop inside another can multiply its work.

Now put a fixed three-iteration loop inside a loop over n items. The total is 3n visits, which is still linear. The presence of two loop statements alone is insufficient to conclude quadratic growth.

Count the branch that runs

An if/else executes its test and one branch. Suppose a true condition triggers a scan of all n items and a false condition returns immediately. An execution takes either the scan or the return, not both. A guaranteed upper bound must allow for the scan. A precise best-case analysis can use the immediate return when an input of that size reaches it.

When writing a count, identify the operation: comparisons, assignments or complete constant-time body executions. Saying "the loop takes 12 operations" is ambiguous if 12 counts only additions while each iteration also compares, fetches and assigns. A clear cost model makes exact counts useful without turning every analysis into a count of machine instructions.

Key Takeaways

  • Count loop iterations from their endpoints.
  • Multiply iteration count by body cost.
  • Add costs of sequential blocks.
  • Count the test and the branch actually taken.
  • A fixed loop bound gives constant work.

1.3 Cases compare inputs of the same size

Two lists of equal length can cause different amounts of work. A search may find its target immediately or scan to the end. Best, worst and average cases describe these differences while keeping the input size fixed.

Define the functions
CaseCost at a fixed size
BestSmallest cost among inputs of that size
WorstLargest cost among inputs of that size
AverageExpected cost under a stated distribution of inputs

The worst case gives a guarantee: no input of that size costs more. This makes it useful when a program has a time limit. The best case tells what is possible on favorable data, but those data may be rare. An average can describe typical use only when its probability model fits that use.

Work through linear search

Linear search checks items from the front and stops when the target is found. In a nonempty list of length n, the best case takes one comparison because the target is first. The worst takes n comparisons because the target is last or missing. A long list can still have the one-comparison best case. Choosing a smaller list changes the size, not the case at that size.

If the target is present and equally likely to occupy each position, the counts 1 through n have equal probability. Add and divide by the number of positions:

1+2+⋯+nn=n(n+1)/2n=n+12.

For ten items, the expected count is 5.5. No individual search takes half a comparison; an expected value summarizes many possible searches.

Change the input distribution and the average changes. If the target is absent half the time and otherwise uniformly placed, the absent searches cost n and the present ones average (n+1)/2:

12n+12n+12=3n+14.

At ten items this is 7.75 comparisons. Taking the midpoint of the best and worst costs would miss the extra probability of an unsuccessful search.

A larger gap between cases

Insertion sort builds a sorted prefix one item at a time. On sorted data, each new item is already in position, giving n−1 item comparisons. On reverse-sorted data, the new item is compared with all earlier items, giving n(n−1)/2 comparisons. For five items these counts are 4 and 10; at 1,000 items the reverse-order count is 499,500. The cases have different growth rates, not just different constants.

Keep the case separate from the bound

A case selects inputs. Asymptotic notation describes the resulting cost function. Linear search has worst-case Θ(n) time and best-case Θ(1) time. Big-O can give an upper bound on either case, and Big-Omega can give a lower bound on either case. Neither symbol chooses the case for you. State both parts of a performance claim when early stopping or data order affects the work.

Key Takeaways

  • Keep input size fixed when comparing cases.
  • An average needs a probability distribution.
  • Worst-case cost guarantees a bound for every input.
  • Case and bound are separate parts of a claim.
2

Describe growth with asymptotic notation

A cost function contains details that can obscure its long-term behavior. Asymptotic notation expresses which functions eventually bound it above and below, allowing fixed multipliers. Simple inequalities show why a bound holds; ratios show why some proposed bounds fail. The simplification rules connect those definitions to sums, products, logarithms and independent input sizes in real code.

2.1 Prove an upper bound with constants

Big-O describes an eventual upper bound on a cost function. It answers how fast the cost can grow, allowing a fixed multiplier. It does not claim an exact number of seconds or operations.

Read the definition

For functions nonnegative at sufficiently large sizes, f(n) is O(g(n)) when positive constants c and n0 exist such that

f(n)≤cg(n)for every n≥n0.

The multiplier c absorbs fixed factors. The threshold n0 allows a finite set of small sizes to behave differently. Both are fixed independently of n. Choosing a new multiplier for every size would defeat the definition: it would no longer give one bound for the whole tail of the function.

The notation f(n)=O(g(n)) means that f belongs to a set of bounded functions. Its equals sign is one-way shorthand. The statement n=O(n2) is true, but swapping its sides does not make n2=O(n) true.

Build a proof

Let f(n)=3n2+5n+2. For n≥1, both n≤n2 and 1≤n2. Bound each term using the same square:

3n2+5n+2≤3n2+5n2+2n2=10n2.

Thus c=10 and n0=1 prove f(n)=O(n2). The constants need not be the smallest possible. Another valid choice is c=4 and n0=6: the needed inequality becomes n2−5n−2≥0, which holds for every integer n≥6. One valid pair is enough.

A table of checks at a few values is not this proof. The definition requires every size past the threshold; an algebraic inequality supplies that guarantee.

Show when a proposed bound fails

Suppose n2 were O(n). Its required inequality would be n2≤cn beyond a fixed threshold. Dividing by positive n gives n≤c. But an integer larger than both c and n0 violates it. No fixed multiplier can cover the growing ratio, so the proposed linear upper bound fails.

Understand what simplification removes

At n=1,000, the leading term 3n2 contributes 3,000,000 of 3,005,002 steps, over 99.8%. The linear and constant terms become a shrinking fraction of the total. The leading factor 3 behaves differently: it stays a factor of 3. Big-O absorbs it into c; it does not become numerically unimportant.

Upper bounds can be loose. The function 2n+3 is O(n), O(n2) and O(2n). The linear bound communicates more. A tight bound will need a lower bound too.

Finally, O(1) means bounded by a constant independent of input size. A loop of a million iterations can be constant time if that count never changes with the input. It can still take longer on practical inputs than a small linear scan. Big-O describes growth, and applies to best-, worst- or average-case functions once you name the case.

Key Takeaways

  • Big-O needs one fixed multiplier and threshold.
  • Prove an inequality for all sizes beyond the threshold.
  • An unbounded ratio disproves a proposed upper bound.
  • Big-O can be loose.
  • Constant time need not mean fast.

2.2 Lower bounds and tight bounds

An upper bound alone leaves room for a cost to grow much more slowly. Big-Omega supplies a lower bound. Big-Theta combines upper and lower bounds to identify the growth rate tightly.

Put the inequalities in the right direction
NotationRequired inequality beyond a fixed thresholdMeaning
O(g(n))f(n)≤cg(n)Upper bound
Ω(g(n))f(n)≥cg(n)Lower bound
Θ(g(n))c1g(n)≤f(n)≤c2g(n)Tight bound

All constants in this table are positive. The functions are nonnegative at large input sizes. For Theta, the same threshold must work for both inequalities; take the larger threshold if the two proofs initially use different ones.

A lower bound can be loose, just as an upper bound can. The function n2 is Ω(n) and Ω(1) as well as Ω(n2). Only matching upper and lower rates establish Theta.

Prove a tight polynomial bound

For n≥1,

3n2≤3n2+5n+2≤10n2.

The first inequality follows because the added terms are nonnegative. The second follows by bounding each term with a multiple of n2. Choose c1=3, c2=10 and n0=1. The function is Θ(n2). More generally, a polynomial with positive leading coefficient and degree d has growth Θ(nd).

For a pair-counting loop, the cost n(n−1)/2 needs slightly more care because of the subtraction. The upper inequality is n(n−1)/2≤n2/2. For n≥2, use n−1≥n/2 to get

n24≤n(n−1)2≤n22.

This proves Θ(n2) with constants 1/4 and 1/2. A count of zero at size 1 causes no problem because the chosen threshold is 2.

Attach bounds to a case

For linear search, the worst-case comparison function equals n, so it is Θ(n). The best-case function equals 1 for nonempty lists, so it is Θ(1). Across all inputs its cost is bounded above by O(n) and below by Ω(1). Calling every execution Θ(n) would overlook a first-position match at any large size.

Insertion sort has best-case Θ(n) and worst-case Θ(n2) comparison counts. Saying its worst case is Ω(n2) means the hardest inputs really require quadratic work. Omega therefore does not mean "best case." It is a lower bound on the particular function you choose.

Programming discussions often use "Big-O" informally for the tight worst-case rate. In an analysis, make the claim explicit: identify the case, prove the direction you need, and use Theta when both directions are established. An upper bound cannot become tight just because no smaller one has yet been considered.

Key Takeaways

  • Omega bounds a function from below.
  • Theta requires matching upper and lower growth rates.
  • Loose lower bounds do not establish a tight rate.
  • Name the input case independently of the notation.

2.3 Simplify costs without losing a growing factor

A cost expression can contain several terms, factors and input sizes. Simplification keeps the part that determines large-input growth. It must preserve every factor that can grow independently.

Constants, sums and products

Multiplying a nonnegative cost by a positive constant leaves its tight rate unchanged. The functions 5n, n/2 and 1,000n are all Θ(n). A constant factor can still matter when comparing actual running times.

For nonnegative functions, a sum lies between its largest term and twice that term:

max⁡(f(n),g(n))≤f(n)+g(n)≤2max⁡(f(n),g(n)).

Thus the sum has the tight growth rate of the maximum. In n2+nlog⁡n+7, the square eventually dominates, so the result is Θ(n2). This is the rule for sequential blocks.

Products keep their growing factors. An outer loop with n iterations and an inner body of cost Θ(log⁡n) has total Θ(nlog⁡n). Dropping the logarithm would discard work that increases without bound. If only upper bounds are known for the factors, the product establishes an upper bound; a tight bound still needs a lower-bound argument.

Polynomials and logarithms

In a polynomial with positive leading coefficient, keep the highest power. The expression 0.001n3−50n2+106 is Θ(n3) at large sizes. A small cubic coefficient can delay the point where the cubic dominates; it cannot turn the cubic rate into a quadratic one.

Logarithm bases differ only by a constant multiplier:

log⁡an=log⁡bnlog⁡ba,a,b>1.

Consequently log⁡2n and log⁡10n have the same asymptotic rate. The identity log⁡(n3)=3log⁡n also gives Θ(log⁡n). Keep nlog⁡n separate: the factor n multiplies the logarithm and grows with the input.

Exponentials follow a different rule

The expression 2n+1=2⋅2n differs from 2n by a constant factor. But 4n has ratio 4n/2n=2n to 2n. That ratio is unbounded, so 4n is not O(2n). A fixed base in an exponential cannot be ignored the way a fixed logarithm base can.

Bounds are transitive. If f=O(g) and g=O(h), then f=O(h). For example, log⁡n=O(n) and n=O(nlog⁡n) imply log⁡n=O(nlog⁡n). Such a statement is correct even when loose.

Preserve independent sizes

Scanning lists of lengths n and m takes Θ(n+m) work. There is no single dominant variable unless a relationship is known. If m≤5n, the sum is bounded by 6n and becomes Θ(n). With no such restriction, m may grow while n stays small.

For n≥1, the expression nm+m is between nm and 2nm, so it is Θ(nm). The condition on n justifies absorbing the extra m. Write a simplified bound such as O(n2) once the reasoning is complete, instead of leaving O(n2+n) as unfinished arithmetic.

Key Takeaways

  • Constants can be absorbed; growing factors cannot.
  • Sequential costs simplify by the sum rule.
  • Nested repeated work follows the product rule.
  • Fixed logarithm bases share a rate; exponential bases do not.
  • Keep independent input sizes until a relationship justifies merging them.
3

Compare common growth rates

Input growth can turn a manageable computation into an impractical one. Learn the usual growth rates, see how repeated halving creates logarithms, and use a rate to predict what happens at larger sizes. Operation estimates help rule out costly approaches early. Timing experiments then check the prediction on an implementation, while constants explain why small inputs may favor a different method.

3.1 Growth rates and feasible input sizes

Growth rates reveal how quickly an algorithm's workload expands. A constant factor can make one implementation faster today, while a difference in growth rate can decide whether tomorrow's larger input is practical at all.

Put the rates in order

For sufficiently large n, the usual rates increase in this order:

1, log⁡n, n, n, nlog⁡n, n2, n3, 2n, n!.

Each is an upper bound for the ones before it, and grows strictly faster than them asymptotically. The names are constant, logarithmic, square root, linear, linearithmic, quadratic, cubic, exponential and factorial. A power nk with fixed k is polynomial. In a polynomial the input is the base; in 2n the input is the exponent.

PatternTypical cost
Read a list entry by indexConstant
Repeatedly halve a search rangeLogarithmic
Sum a listLinear
Efficient comparison sortLinearithmic worst-case upper bound
Examine every pairQuadratic
Examine every tripleCubic
Consider every subsetExponentially many subsets
Consider every orderingFactorially many orderings

Listing subsets or orderings in full can also require copying each result's items. The number of results already establishes why these searches grow so quickly.

Compare actual counts

The counts below use base-2 logarithms and rounded values where needed.

nlog⁡2nn log⁡2nn2n32nn!
103.3331001,0001,0243,628,800
1006.666410,0001,000,000About 1.3×1030About 9.3×10157
1,00010.09,966106109About 1.1×10301Beyond the scale of these smaller counts

At 1,000 items, linearithmic work is about 9,966 steps and quadratic work is a million. The logarithmic factor grows slowly; it does not make linearithmic work almost quadratic. The gap continues to widen. These are workload estimates when the step model matches the expression.

The order is eventual, not a comparison at every small value. For instance, n3 exceeds 2n for integer sizes 2 through 9. From size 10 onward, 2n exceeds n3. Every fixed polynomial is eventually outgrown by 2n.

Estimate feasibility

Assume a rate of 109 simple steps per second. For a million items, about 2×107 linearithmic steps take 0.02 seconds, while 1012 quadratic steps take 1,000 seconds, nearly 17 minutes. These are model-based estimates; different operations have different real costs.

With that same rate, 230 steps take about one second and 250 take about 13 days. Performing 20! steps takes roughly 77 years. A faster computer supplies a constant speed increase, but exponential or factorial growth quickly consumes it. Before implementing an exhaustive search, estimate its count at the largest expected input, including the work needed to produce each result.

Key Takeaways

  • Rank growth for large inputs, not every small input.
  • A variable exponent differs from a fixed power.
  • Linearithmic work grows much more slowly than quadratic work.
  • Use a stated step rate to estimate feasibility.
  • Count output work when listing many results.

3.2 Why halving and doubling produce logarithms

A logarithm counts repeated multiplication or division by a fixed factor. Since 210=1,024, it takes ten doublings to reach 1,024 from 1, or ten exact halvings to return to 1. This makes logarithms natural in algorithms that repeatedly shrink a remaining range.

Trace the stopping test
i = n
while i > 0:
    inspect(i)
    i //= 2

For n=16, inspect sees 16, 8, 4, 2 and 1. The next division produces 0 and the loop stops. The exact count for positive integer n is ⌊log⁡2n⌋+1. Including the visit at 1 explains the extra step. At 1,000 the count is ten; at a million it is twenty.

Now start at 1 and use while i < n: i *= 2. The updates must reach or pass n. The count is ⌈log⁡2n⌉, so reaching 16 takes four updates. Both loops are Θ(log⁡n) even though their endpoint counts differ.

Dividing by 3 each time gives about log⁡3n visits. The change of base only changes a constant factor. Subtracting 2 each time gives about n/2 visits, which is linear. The update rule, not the mere fact that a variable decreases, determines the count.

Even subtraction can produce logarithmic growth when the amounts double. Removing 1, then 2, then 4, then 8 consumes 1+2+4+8=15 after four iterations. After k iterations, 2k−1 has been removed. Reaching a value proportional to n therefore needs a logarithmic number of iterations.

Connect the count to binary search

Binary search checks the middle item of a sorted range. A comparison tells it which half can still contain the target. After k reductions, the remaining range has roughly n/2k items. That becomes about one item when 2k reaches n.

For a nonempty sorted list, the worst case checks at most ⌊log⁡2n⌋+1 middle items. A million-item list needs at most twenty, compared with up to a million for linear search. The best case can still be one check if the middle item is the target.

Sorting is part of the cost when the data is unsorted. An O(nlog⁡n) sort followed by one binary search is more work than one linear scan. Sorting once can be useful when many later searches reuse the sorted data.

Separate three related rates

One halving loop is logarithmic. Running it anew for each of n items gives Θ(nlog⁡n), called linearithmic. For a doubling loop with a limit of 1,000, each outer iteration makes ten inner updates; 1,000 outer iterations give 10,000 updates.

Two nested logarithmic loops instead give Θ((log⁡n)2). The square belongs to the logarithm, not to the input. In this material, an unspecified logarithm base is 2; inside asymptotic notation any fixed base greater than 1 gives the same rate.

Key Takeaways

  • Trace both the update and the stopping condition.
  • Fixed-factor changes lead to logarithmic counts.
  • Binary search requires sorted data.
  • Repeated logarithmic work per item gives linearithmic growth.

3.3 Predict time and test the prediction

A growth rate predicts how work changes when the input changes. It does not by itself predict seconds. Combine the rate with a timing at one size to make an estimate, then test whether larger measurements follow the predicted trend.

Scale the input

For a pure power cost proportional to nk, increasing size by a factor r increases time by approximately rk. A quadratic program taking 0.5 seconds at 1,000 items is predicted to take 0.5×42=8 seconds at 4,000 items. A linear program starting at the same time would take about 2 seconds.

Cost modelEffect of doubling input
ConstantNo growth
log⁡2nAdd 1 to the cost expression
nMultiply by 2
nlog⁡2nSlightly more than multiply by 2
n2Multiply by 4
n3Multiply by 8
2nSquare the cost expression

For linearithmic work from 1,000 to 2,000, the ratio is about 2.2. For exponential work, the exact identity 22n=(2n)2 explains why a fixed doubling ratio is inappropriate.

Run a doubling experiment

Use time.perf_counter() to measure elapsed time at sizes n, 2n, 4n and 8n. Keep the input family consistent: a worst-case pair-checking test needs data that forces all pairs at every size. Construct inputs outside the timed block if the aim is to time only the algorithm.

Repeat runs and use a typical or smallest time to reduce interference from other work on the machine. Choose sizes large enough to give clearly measurable runs. Then divide each time by the preceding time. Ratios approaching 2 suggest linear growth; ratios near 4 or 8 suggest quadratic or cubic growth.

These ratios are evidence from that implementation and machine. Fixed overhead can dominate tiny inputs, making a theoretically quadratic function appear almost constant at first. Another machine can give different times and finite-size ratios. One timing cannot establish a growth rate because growth describes change across sizes.

Check constant factors and crossover points

Suppose A takes 100n steps and B takes n2. For positive sizes, equality occurs when 100n=n2, or n=100. B uses fewer steps below that size; A uses fewer above it. Both statements follow from exact cost models, not merely from their asymptotic labels.

Libraries use such effects. Python's sort has an O(nlog⁡n) worst-case bound, yet uses binary insertion sort on short stretches where low overhead can outweigh its quadratic worst-case rate. The best large-input rate need not win on small inputs.

Before writing code, estimate the largest workload. Checking all pairs of 100,000 items requires 4,999,950,000 comparisons. A model based on nlog⁡2n needs about 1.7 million steps at that size. Compare estimated counts, the cost of each step and available time; a good asymptotic choice still needs a sensible implementation.

Key Takeaways

  • Scale power costs by the corresponding power of the size ratio.
  • Compare several sizes in a consistent timing experiment.
  • Small inputs can be dominated by fixed overhead.
  • Exact constants determine crossover sizes.
  • Estimate the largest workload before implementing it.
4

Analyze loops and complete functions

Loop analysis puts growth rules to work on code. Start inside the function, count repetitions and include the cost of each operation. Independent nested loops multiply their work, but changing bounds often need a sum, and a counter that never resets may advance only once through the input. Python calls and slices can conceal scans or copies, so a short function still needs a careful count.

4.1 Combine loop costs from the inside out

A complete function can contain fixed work, repeated work and several blocks in sequence. Analyze its structure from the inside out. The important questions are how often a body runs and how much that body costs.

Follow the code structure
  1. Name each independent input size.
  2. Find the cost of the innermost operation, including calls.
  3. Count its repetitions in each enclosing loop.
  4. Add the costs of blocks that run one after another.
  5. Simplify and state a bound, with the case when data affects the count.

This method avoids using indentation depth as a shortcut. Two nested loops can be linear, quadratic or something else depending on their bounds.

Multiply independent repetitions
count = 0
for x in items:
    for y in items:
        if y < x:
            count += 1

With n items, each outer visit starts a fresh inner scan of all n items. The comparison runs n⋅n=n2 times. Its truth value changes how often count increases, but not how often the comparison runs. Both best- and worst-case time are Θ(n2) under constant-time comparisons. At 1,000 items the code makes a million comparisons.

Three independent loops over range(n) give n3 body executions. At n=100 that is a million. If two nested loops visit separate lists of lengths n and m, their product is nm, not n2. Keep both sizes unless a relationship between them is supplied.

A nested loop can still be linear
for value in items:
    for offset in range(3):
        inspect(value, offset)

If inspect is constant time, the total is 3n calls, hence Θ(n). The inner loop adds a fixed factor. Replacing its bound with a doubling loop up to n instead gives logarithmic inner work and Θ(nlog⁡n) total work.

Add blocks in sequence

Suppose the all-pairs block is followed by a single scan. The comparison and visit counts together are proportional to n2+n, so the tight growth rate remains Θ(n2). A second independent scan adds work; it does not multiply the first block by n.

For two consecutive loops over different lists, the cost is Θ(n+m). For nested full scans of those same lists, it is Θ(nm). Looking at whether the inner work restarts on every outer visit distinguishes these shapes.

Account for early stopping

A pair check can return immediately after finding equal items. If its first pair matches, it needs only one comparison. If all items are distinct, it must reach every pair. Its best case can be constant while its worst case is quadratic.

To justify a worst-case tight bound, show both that no input causes more work and that some inputs of arbitrarily large size force the full count. An upper bound obtained by ignoring a break can be valid but loose. Read the stopping paths before assigning Theta to every execution.

Key Takeaways

  • Count repetitions, not indentation depth.
  • Multiply independent nested bounds.
  • Add sequential blocks before simplifying.
  • Include calls in the innermost cost.
  • Early exits can change the best case without changing the worst.

4.2 Add changing loop lengths

When an inner loop's bound changes with the outer variable, its work is a sum of different lengths. Multiplying the outer count by the largest inner count gives an upper bound, but the sum reveals whether that bound is tight.

Count pairs with a triangular sum
for i in range(n):
    for j in range(i + 1, n):
        inspect(i, j)

For the first index, there are n−1 later indices. For the next there are n−2, and the final index has none. The total is

(n−1)+(n−2)+⋯+1+0=n(n−1)2.

This visits every pair of distinct positions once, with i<j. At five items there are ten visits. At 1,000 there are 499,500. Halving a quadratic count leaves its rate Θ(n2).

The general arithmetic sum is 1+2+⋯+k=k(k+1)/2. Three loops constrained by i<j<k visit each triple once, giving n(n−1)(n−2)/6, or 120 visits at ten items. That count has cubic growth.

Distinguish two logarithmic outer patterns

For each of n items, a fresh inner counter starting at 1 and doubling until it reaches n makes ⌈log⁡2n⌉ updates. This count is the same on every outer visit, so multiplication is exact: n⌈log⁡2n⌉. At 1,000 items it is 10,000 updates.

Now consider:

i = n
while i > 0:
    for j in range(i):
        inspect(j)
    i //= 2

The inner lengths are n,⌊n/2⌋,⌊n/4⌋,…. This is a geometric pattern. Its sum is less than 2n and at least n because the first scan alone has length n. Therefore the total is Θ(n). At 16 it makes 16+8+4+2+1=31 visits; at 1,000 it makes 1,994.

Multiplying the logarithmic number of outer iterations by the largest scan length produces O(nlog⁡n). It is a correct upper bound, but misses the tighter linear bound because the later scans shrink.

Derive while-loop counts from the condition
i = 1
while i * i <= n:
    inspect(i)
    i += 1

The body runs for positive integers whose squares are at most n. There are ⌊n⌋ such values. A million permits 1,000 visits, so the loop is Θ(n) under fixed-size arithmetic.

Check whether a nested counter resets. A counter that keeps advancing through the input can advance at most n times over the entire function. Resetting it on every outer visit can turn that shared work into repeated work.

Key Takeaways

  • Sum inner counts when the bound changes.
  • A triangular pair count is quadratic.
  • Geometrically shrinking scans have a linear total.
  • Derive a while-loop count from its stopping inequality.
  • Check whether an inner variable resets.

4.3 Include the work hidden in Python operations

Python expressions can conceal scans, copying and movement of items. Price those operations before multiplying by a surrounding loop count. Here, hashing and comparisons of individual fixed-size items are constant-time operations.

Know the common costs
Operation on a list of length nTime cost
len(items), items[i], indexed assignmentO(1)
append(x), pop() at the endAmortized O(1)
Membership, index, count, min, max, sum, copyingO(n) worst case
insert(0, x), pop(0)O(n)
Slice of k itemsΘ(k)
sorted(items), items.sort()O(nlog⁡n) worst case

A list stores items in indexed slots. Front insertion or removal shifts later entries. End operations usually avoid those shifts, but occasional storage growth or shrinkage can copy the array. Their constant bound is amortized over operations, not a guarantee on every call.

Set and dictionary lookup, membership and updates have average-case O(1) costs under ordinary hashing assumptions. Colliding keys can make one operation linear in the container size. Building a hash table also includes resizing; average-case and amortized qualifications describe different sources of cost.

Find a hidden nested scan
result = []
for value in items:
    if value not in result:
        result.append(value)

When all n items are distinct, the membership scans have lengths 0, 1, 2, through n−1. They total n(n−1)/2 comparisons, hence quadratic time. The single visible for loop hides the second scan.

Keep a set seen for membership and a list result for output order. Each item then needs an average constant-time lookup and possible insertion, plus an amortized constant-time append. The whole pass is Θ(n) on average and uses linear extra storage. The set needs hashable items.

Include copying and shifting

Repeatedly replacing items with items[1:] copies n−1,n−2,…,0 entries. Reassigning the variable does not make the slice free: creating the new list already did the copying. A direct iteration visits all items in linear time without these suffix copies.

Building a reversed list with front insertion shifts 0+1+⋯+(n−1) entries and costs quadratic time. Appending all items and reversing once takes linear total time. A collections.deque supports constant-time appendleft when adding at the front is the required operation.

For [x for x in a if x in b], lengths n and m give worst-case O(nm) time with lists. Converting b to a set once costs average O(m), after which the n checks cost average O(n). Include preparation to report average O(n+m) overall.

For duplicate detection, all-pairs comparison is quadratic in the worst case; sorting a copy and checking neighbors has an O(nlog⁡n) upper bound; a set gives average linear time. These methods require compatible items: sorting needs orderable items and sets need hashable ones. Nested lists can be compared and sorted but cannot be inserted into a set.

Key Takeaways

  • A short expression can hide a scan or a copy.
  • List end operations have amortized constant cost.
  • Hash lookup has an average-case constant bound.
  • Include preparation when replacing scans with a set.
  • Check hashability and orderability when choosing a method.
  • Repeated front shifts or suffix copies can make a loop quadratic.
5

Analyze memory use

Memory use is a resource to analyze alongside time. Distinguish supplied input from extra storage, count the collections and call frames that exist together, and include built outputs and hidden copies. Stored information can replace repeated computation, but its benefit depends on how often it is reused. Comparing both costs helps choose a method that fits the workload and memory budget.

5.1 Measure memory that is live at the same time

Time counts work performed; space counts memory held. A function can revisit the same input many times while storing only a few variables, or finish quickly by creating a large collection. Report the two resources separately.

Name the space measure

Total space includes the input. Auxiliary space counts memory beyond that input. Summing an existing list needs a running total and a loop variable, giving O(1) auxiliary space in the fixed-size-number model. Including the list makes total space linear in its length.

Count the largest amount of memory live at once. Creating and discarding a temporary list in each iteration can cost much copying time without keeping all those lists simultaneously. If the program saves every copy, their sizes must be added to its peak storage.

A comprehension producing n entries uses Θ(n) space. A set of distinct values seen so far can hold up to n entries. A stored square grid with n rows and n cells per row needs Θ(n2) cells; a 1,000-by-1,000 grid has a million cells.

Distinguish mutation from constant extra space

Reversing a list by swapping its first and last entries, then the next pair inward, needs only indices and a temporary value. It uses O(1) auxiliary space, as does items.reverse(). An in-place algorithm changes the input with little extra memory, often constant.

The expressions items[::-1] and list(reversed(items)) instead construct new lists of n references, using Θ(n) space. items.sort() changes the original list but can need temporary space for about half its entries during merging, giving linear worst-case auxiliary space. sorted(items) also returns a separate list. Merely modifying the input is not a constant-space proof.

Count outputs and call frames

A function returning every distinct-position pair stores n(n−1)/2 pairs if it builds them all in memory. That output alone takes Θ(n2) space and at least Ω(n2) time to write. An algorithm cannot produce that many explicit results in constant time.

State whether output storage is included when reporting auxiliary space. Here, built output is counted as memory beyond the supplied input. This keeps a function that builds a huge result distinct from one that only stores a few counters.

Recursive calls keep frames containing local state. If n calls are active together at maximum depth, constant-sized frames use Θ(n) stack space. Count maximum active depth, not the total number of calls made during execution. CPython has a configurable recursion limit; inspect it with sys.getrecursionlimit() when diagnosing a program.

Translate growth into a storage estimate

On a 64-bit CPython build with 8-byte references, a million list entries need at least 8,000,000 bytes, or 8 MB, for references alone. List overhead, spare capacity and the referenced objects add memory. Asymptotic notation hides these byte factors, but a memory budget cannot.

An all-pairs duplicate check uses quadratic worst-case time and constant auxiliary space. A set-based check uses average linear time and linear auxiliary space. Include both measures when choosing between them; a faster pass may need storage that the environment cannot provide.

Key Takeaways

  • Distinguish input storage from auxiliary storage.
  • Measure peak live memory.
  • Count copies, built outputs and active call frames.
  • Temporary storage can grow even when the function changes its input.
  • Byte estimates include more than the stored references.

5.2 Spend memory to avoid repeated work

Many faster algorithms store information that would otherwise have to be found again. A time–space trade-off compares the time saved with the memory needed. The useful choice depends on input size, repeated queries, memory limits and whether data can be changed or reread.

Compare duplicate checks
MethodTimeExtra space
Compare every pairWorst-case Θ(n2)O(1)
Sort a copy and check neighborsWorst-case O(nlog⁡n)O(n)
Store seen items in a setAverage Θ(n)O(n)

The set remembers earlier values so that each new value need not scan them all. The sorted copy puts equal values next to each other. The pair method avoids storing either structure. For 100,000 distinct items, the pair method examines about five billion pairs, while the set method processes about 100,000 items with average constant-time set work per item. Sets require hashable items; the sort method requires orderable items.

Precompute range sums

For data = [3, 1, 4, 1, 5], construct a table of prefix sums:

prefix = [0]
for value in data:
    prefix.append(prefix[-1] + value)

The table becomes [0, 3, 4, 8, 9, 14]. Entry prefix[k] sums the first k input items. The leading zero handles a range starting at index 0 without a special case.

To sum indices i through j−1, subtract prefix[i] from prefix[j]. The latter includes all items before j; subtraction removes exactly those before i. For indices 1 through 3, prefix[4] - prefix[1] is 9−3=6, matching 1+4+1.

Building the table takes Θ(n) time and n+1 stored numbers. Each query then takes constant time. For q queries, the total is O(n+q), compared with worst-case O(nq) when summing each requested range directly. Count preprocessing once, not once per query. The table represents the data values used to build it; changing them can require updating or rebuilding stored information.

Store counts or stream a summary

For n words with k distinct values, a frequency dictionary updates one count per word. This gives average Θ(n) time and O(k) extra space under constant-cost hashing and comparison of the words. Rescanning the input for each distinct word can take O(nk) time. Caching and memoization use the same broad idea: retain a result to avoid computing it again.

A stream can be processed with only a running total or maximum. This saves storage, but keeps less information. A total can answer whether the total exceeds a limit; it cannot reveal how many individual values lie in a newly requested range. That question needs more stored detail or another pass if the data is available again.

At 8 bytes per item, a billion entries require 8 GB before overhead. An asymptotically faster method may fail that budget. For a small input or a single query, the preparation and storage of a table may provide no practical benefit.

Key Takeaways

  • Stored information can remove repeated scans.
  • Include preprocessing in the total time.
  • Prefix subtraction answers a range sum in constant time.
  • A compact summary loses some detail.
  • Choose a method that fits both time and memory limits.
6

Explain amortized cost

An occasional expensive operation need not make a whole sequence expensive. Dynamic arrays spread resizing work across appends, and aggregate counting tracks work that each item can trigger only a limited number of times. These arguments give guarantees about total cost without assuming random inputs. They also explain why a good amortized bound still permits a slow individual response.

6.1 Why occasional resizing still gives cheap appends

A dynamic array reserves more slots than it currently uses. Its length is the number of stored entries; its capacity is the number of available slots. Appending to a free slot is cheap, but an append to a full array may need a larger allocation and a copy of existing entries.

Count a sequence, not just one call

Use a simple model whose capacity starts at 1 and doubles whenever full. Count one unit for writing an appended item and one for copying an existing item. The first append uses the initial slot. The second copies one item into capacity 2; the third copies two into capacity 4; the fifth copies four into capacity 8.

Through sixteen appends, copying happens at appends 2, 3, 5 and 9:

1+2+4+8=15 copies.

Add sixteen writes to get 31 units. The seventeenth append needs another resize and copies sixteen entries. Its sequence total becomes 31+16+1=48 units. That individual call is expensive even though most calls perform only a write.

Bound the geometric total

For any positive number n of appends from empty, copied capacities form a doubling series. The last copied capacity is less than n, and the sum of all copied capacities is less than twice that last capacity, hence less than 2n. Adding n writes gives fewer than 3n units overall.

The total cost divided by the sequence length is bounded by a constant. This is an amortized constant-time append bound. It applies to every such append sequence, with no probability distribution over inputs.

A credit picture helps explain why the total works. Charge three units per append: spend one on writing and save two. Between resizes from capacity k to 2k and from 2k to 4k, another k items arrive and save 2k credits, enough for the next copy. Equivalently, when capacity k has just filled, its newest k/2 items supply the k credits needed to copy it. Initial small capacities can be paid directly.

The growth policy decides the result

If capacity increases by ten slots each time, 1,000 appends copy 10+20+⋯+990=49,500 entries. Doubling from capacity 1 copies only 1,023 entries through the same number of appends. Fixed-increment growth gives quadratic total copying and linear amortized cost per append. Any fixed multiplicative growth factor greater than 1 gives a geometric sum and constant amortized append cost.

CPython lists use proportional over-allocation, not this exact doubling schedule. The model explains the constant amortized result without claiming that Python resizes at those particular lengths.

Keep the guarantee precise

Worst-case time for one resizing append is linear in the current length. Amortized time is constant over a sequence. Average-case analysis instead takes an expectation under an input distribution. These claims answer different questions.

A strict response deadline for every call needs the individual worst-case bound as well. Also, front insertion remains linear because entries shift on every call; reserving spare capacity cannot remove that repeated movement.

Key Takeaways

  • Length and capacity describe different quantities.
  • A resizing append can have linear individual cost.
  • Geometric copying totals give constant amortized append cost.
  • Fixed-increment growth gives quadratic total copying.
  • Amortized guarantees need no input probabilities.
  • A per-call deadline still requires a worst-case bound.

6.2 Bound total work by what can happen only once

Multiplying an operation's largest possible cost by the number of operations gives a safe upper bound, but can overcount work that cannot repeat. Aggregate counting finds a tighter total by following items or counters through the whole sequence.

An item can leave a stack only once

A stack supports push and multipop(k), which removes up to k current items. One multipop can be expensive. But in a sequence starting with an empty stack, every popped item must first have been pushed. No item can be popped twice unless a later push puts an item back.

For r operations, there are at most r pushes and therefore at most r successful pops. Include constant overhead per operation and the total remains O(r). The amortized cost is O(1), despite a possible linear-cost multipop. Starting empty matters: items already present would add to the available pop work.

A moving boundary advances only n times

For positive input values and a nonnegative limit:

left = 0
total = 0
for right in range(len(values)):
    total += values[right]
    while total > limit:
        total -= values[left]
        left += 1

One new value can cause many removals. Across the run, however, left never moves backward and advances at most n times. The right loop also advances n times. Including tests gives linear total time, Θ(n). The nonnegative limit ensures removing the whole current window can satisfy the test before another removal tries to pass its end.

Resetting left to zero for each outer visit would discard this argument: the same positions could be revisited, producing a quadratic total. Track the lifetime of a counter, not just its location inside nested code.

Move each queue item a bounded number of times

A two-stack queue appends new items to inbox. It removes items from outbox. Only when outbox is empty does it move all inbox entries into outbox, reversing their order. That puts the oldest entry at the removal end.

Each item enters inbox once, transfers once, and leaves outbox once. Thus any valid sequence of r enqueues and dequeues from an empty queue costs O(r) in total. A single dequeue can transfer many items; the amortized cost per operation is still constant. Count the underlying stack appends and end pops with their own amortized bounds.

The same progress idea explains merging sorted lists of lengths n and m. Each step writes an item and advances one of two indices. Neither index retreats, so producing the merged list takes Θ(n+m) time.

Choose the bound for the requirement

Aggregate counting is useful when total processing time matters, such as building a collection or processing a file. A system with a strict deadline for each individual response also needs a per-operation worst-case analysis. A linear total is compatible with one slow operation followed by many cheap ones. State the initial condition, count the total possible work, then divide only if an amortized cost is wanted.

Key Takeaways

  • Count how many times each item can be processed.
  • State the initial condition for a sequence bound.
  • Monotone counters can make nested work linear.
  • Two-stack queue items transfer at most once.
  • A total guarantee permits slow individual operations.

Big-O Notation examples

6 Walkthroughs

1

From Python code to a cost function

12 steps
Choose a size, count executions, and calculate search costs under different input cases.
  1. 1
    IntroductionAsk what changes with the input

    A program can take different amounts of time on two inputs of equal length. Before comparing implementations, decide what grows, what work to count, and which input case matters. We will count a scan and then follow a search whose stopping position changes. The result will be a function of input size, with a clear meaning for every counted operation.

  2. 2
    ExplanationName the size and the operation

    Let n be the number of readings in a list. If the function totals them, count fixed-size additions as the dominant operation. There is one addition per reading. This model leaves out exact machine instructions but captures growth when fetching items and controlling the loop add only constant work per visit. It also makes the count independent of the speed of one computer.

  3. 3
    ExampleLook inside one line

    The expression sum(readings) is one line, but it processes all n readings. In contrast, len(readings) reads the stored list length without scanning its entries. The right cost comes from the operation performed, not the number of lines written. A function call has fixed control overhead; any growing work in its body must still be counted.

  4. 4
    ChallengeChoose sizes for two inputs

    A function checks every label in one list against every label in a second list. Their lengths vary independently. What sizes should its analysis keep?

    ---reveal---

    Keep two sizes, n and m. The full comparison count is nm. Using one shared length would assume a relationship the lists do not have; an input with one short list and one long list should remain distinguishable.

  5. 5
    ExampleCount the summing loop

    For this function, count initialization, additions and return:

    def total(readings):
        result = 0
        for value in readings:
            result += value
        return result
    

    Initialization runs once. The addition runs once per entry, or n times. The return runs once. Under this model, the total is n+2. Counting item fetches too would alter the coefficient, not the linear growth.

  6. 6
    Key InsightA second scan adds work

    Suppose a separate loop checks all readings after the total has been computed. It adds another n visits. It does not repeat the summing function for every reading.

    The combined count is proportional to n+n=2n. Sequential blocks add. Multiplication becomes appropriate when one block's work restarts inside every iteration of another loop.

  7. 7
    ChallengeCount a stepped range

    How many times does the body execute in for i in range(1, 14, 4)?

    ---reveal---

    It executes four times, at indices 1, 5, 9 and 13. The starting value is included, and the stopping value is excluded. Finding the sequence of permitted indices prevents an off-by-one error; dividing the endpoint by the step without considering the start would not reliably count this loop.

  8. 8
    ExplanationKeep the size fixed

    A linear search checks list entries from the front until a match occurs. For a nonempty n-item list, a first-entry match needs one comparison; a last-entry match or absent target needs n. These are the best and worst cases at the same size. An empty list is a different size, so it cannot explain the best case for a long list.

  9. 9
    ExampleCalculate a present-target average

    For a list of eight entries, suppose the target is present and equally likely to occupy each position. The comparison counts 1 through 8 then have equal weight.

    1+2+⋯+88=368=4.5.

    The expectation can be fractional although each individual search uses a whole number of comparisons. This calculation depends on the stated position probabilities.

  10. 10
    ChallengeChange the input distribution

    Keep the eight-entry list. Now the target is absent one quarter of the time and otherwise uniformly placed. What is the expected count?

    ---reveal---

    Absent searches cost 8, and present searches average 4.5. Weight both groups:

    14⋅8+34⋅4.5=5.375.

    Using 4.5 alone would ignore the extra probability assigned to searches that inspect the whole list.

  11. 11
    ConnectionChoose the claim a time limit needs

    A system must finish a search within a fixed operation budget. The average count helps describe a workload, but a limit that must hold for every input needs the worst case. For linear search, that means allowing n comparisons. When you report a bound, keep the case visible: worst-case Θ(n) and best-case Θ(1) describe different cost functions.

  12. 12
    RecapA count needs a clear meaning

    An analysis now has three ingredients: an input-size measure, a cost model and an input case. Exact loop counts come from actual executions, including the work inside calls. Sequential work adds, and an average weights costs by stated probabilities. These choices give the cost function that asymptotic notation will describe; timing can later test how the implementation performs.

2

Build and test asymptotic bounds

13 steps
Prove a polynomial bound, add a lower bound, and simplify costs without losing growing factors.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn a count into a growth statement
  2. 2
    ExplanationRead an upper-bound inequality
  3. 3
    ExampleBound each polynomial term
  4. 4
    ExampleChoose valid proof constants
  5. 5
    ChallengeReject a linear upper bound
  6. 6
    ExplanationAdd the matching lower bound
  7. 7
    ChallengeDoes a loose lower bound suffice?
  8. 8
    TipKeep notation separate from cases
  9. 9
    ExampleSimplify a sum and a logarithm
  10. 10
    Key InsightExponential bases behave differently
  11. 11
    ChallengeKeep both list lengths
  12. 12
    ChallengeCombine a proof and a simplification
  13. 13
    RecapState only the bound you have proved
3

Predict which algorithms scale

12 steps
Rank growth rates, trace logarithmic loops, and compare timing predictions with measured ratios.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionUse growth to plan for larger inputs
  2. 2
    ExplanationRead the eventual growth order
  3. 3
    ExampleTranslate steps into seconds
  4. 4
    ChallengeCompare complete candidate searches
  5. 5
    ExampleTrace a halving process
  6. 6
    ConnectionHalve a sorted search range
  7. 7
    ChallengeRepeat a logarithmic loop
  8. 8
    ExampleScale a quadratic timing
  9. 9
    TipMake a timing comparison meaningful
  10. 10
    ChallengeRead measured ratios
  11. 11
    Key InsightSmall constants can decide the winner
  12. 12
    RecapCombine a model with evidence
4

Analyze a function from its inner work outward

15 steps
Count independent and dependent loops, then uncover the cost of Python membership and copying.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart where the work happens
  2. 2
    ExampleMultiply independent scans
  3. 3
    ExplanationAdd a later pass
  4. 4
    ChallengeTest the nesting shortcut
  5. 5
    ExampleList changing inner lengths
  6. 6
    ExampleSum the triangular count
  7. 7
    Key InsightShrinking scans form a different sum
  8. 8
    ChallengeCount a fresh doubling inner loop
  9. 9
    ExampleFind a scan inside membership
  10. 10
    ExampleAdd the hidden comparison counts
  11. 11
    ConnectionRemember seen values in a set
  12. 12
    ChallengeDetect repeated copying
  13. 13
    TipCheck an operation and its item requirements
  14. 14
    ChallengeAnalyze a whole function
  15. 15
    RecapMatch the count to the code structure
5

Compare memory use and stored results

11 steps
Measure peak extra storage and decide when a prefix table is worth preparing.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAdd memory to the performance claim
  2. 2
    ExplanationChoose auxiliary or total space
  3. 3
    ExampleCompare reversal with a reversed copy
  4. 4
    Key InsightSpace measures simultaneous storage
  5. 5
    ChallengeCount an explicitly built output
  6. 6
    ExampleBuild the prefix table
  7. 7
    ExampleSubtract off the unwanted prefix
  8. 8
    ChallengeInclude preparation and repeated queries
  9. 9
    ConnectionKnow what a summary retains
  10. 10
    ChallengeChoose under a memory limit
  11. 11
    RecapCompare the resources that matter
6

Spread expensive operations across a sequence

13 steps
Count dynamic-array copies, stack removals, moving boundaries and queue transfers.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow the work across operations
  2. 2
    ExplanationSeparate length from reserved capacity
  3. 3
    ExampleTrace the doubling resizes
  4. 4
    ExampleBound the whole copy series
  5. 5
    AnalogySave credits before the copy
  6. 6
    ChallengeCompare growth policies
  7. 7
    TipUse the right guarantee for a deadline
  8. 8
    ExplanationCount successful stack removals
  9. 9
    ChallengeTrack what a batch removal can consume
  10. 10
    ConnectionCharge work to forward movement
  11. 11
    ExampleTransfer a queue item only once
  12. 12
    ChallengeConnect the sequence arguments
  13. 13
    RecapFind the limited source of repeated work

Big-O Notation practice questions

40 Practice Questions in 4 sets

Set 1: Count work and describe its growth10 Practice Questions

Question 1 of 10

A function compares every character of a string with every character of a second string. The lengths vary independently. What input-size description preserves the information needed to analyze it?
  1. One length n for both strings.
  2. Only n+m, the combined character count.
  3. Lengths n and m, one for each string.
  4. Only max⁡(n,m), the larger length.
Show answerHide answer
Answer: C
Keep a separate length for each string because each can vary without the other. The comparison count is their product. A combined length alone hides how the characters are split: two pairs of strings can have the same combined length but different comparison counts.

Question 2 of 10

How many body executions occur in for i in range(0, 17, 3)?
  1. 6
  2. 5
  3. 7
  4. 17
Show answerHide answer
Answer: A
The visited indices are 0, 3, 6, 9, 12 and 15, so the body executes six times. Counting only complete groups of three gives five and misses the initial visit at zero. The endpoint 17 is excluded, as it is in every range stopping bound.

Question 3 of 10

Linear search examines a 12-item list. The target is absent with probability 1/3; otherwise it is equally likely to occupy any position. What is the expected number of comparisons?
  1. 13/2
  2. 9
  3. 8
  4. 25/3
Show answerHide answer
Answer: D
An absent search costs 12 comparisons, while a uniformly placed present target averages 6.5. The expectation is one third of 12 plus two thirds of 6.5, or 25/3. Using 6.5 alone ignores the unsuccessful searches, which always reach the end.

Question 4 of 10

With the threshold fixed at n0=1, what is the smallest positive constant c proving 7n+4≤cn for every positive integer n?
  1. 7
  2. 11
  3. 4
  4. 12
Show answerHide answer
Answer: B
Divide by positive n to obtain 7 + 4/n ≤ c. This expression is largest at n = 1, where it equals 11, so 11 works for all allowed sizes and is the smallest possible choice. Choosing 7 keeps only the leading term and fails at every finite n.

Question 5 of 10

A cost satisfies 2n2≤T(n)≤9n2 for every integer n≥4. What tight asymptotic bound follows?
  1. Θ(n)
  2. Θ(n2)
  3. Θ(n3)
  4. Θ(9n)
Show answerHide answer
Answer: B
The two inequalities trap the cost between positive constant multiples of n squared beyond one fixed threshold. That is exactly a quadratic Theta bound. A cubic upper bound would be valid, but a cubic tight bound would require a cubic lower bound that the stated upper inequality rules out.

Question 6 of 10

What is the tight rate of T(n)=5nlog⁡2(n4)+12n?
  1. Θ(n)
  2. Θ(n4)
  3. Θ(n2log⁡n)
  4. Θ(nlog⁡n)
Show answerHide answer
Answer: D
The logarithm identity gives log⁡2(n4) = 4 log⁡2n, so the leading term becomes 20n log⁡2n. It eventually dominates the linear term. Treating the fourth power inside the logarithm as a fourth power outside it would change the function and produce the wrong rate.

Question 7 of 10

A model performs exactly n2 steps at a sustained 108 steps per second. About how long does it take for n=20,000?
  1. 4 seconds
  2. 2 seconds
  3. 40 seconds
  4. 0.4 seconds
Show answerHide answer
Answer: A
Squaring 20,000 gives 400,000,000 model steps. Dividing by 100,000,000 steps per second gives four seconds. Forty seconds comes from a power-of-ten error in that division; the stated execution rate must be applied to the complete squared count.

Question 8 of 10

How many body executions occur for the code below?

i = 48
while i > 0:
    i //= 2
  1. 5
  2. 7
  3. 6
  4. 24
Show answerHide answer
Answer: C
The positive values at the start of the body are 48, 24, 12, 6, 3 and 1. After the sixth division the value is zero and the loop stops. Counting five loses the final body execution at 1; a positive stopping test still admits that value.

Question 9 of 10

A quadratic time model fits a function taking 0.8 seconds on 600 items. What time does that model predict for 1,800 items?
  1. 7.2 seconds
  2. 2.4 seconds
  3. 6.4 seconds
  4. 9.6 seconds
Show answerHide answer
Answer: A
The input grows by a factor of three, so a quadratic model multiplies time by three squared, or nine. Multiplying 0.8 by nine gives 7.2 seconds. A prediction of 2.4 seconds applies a linear size factor and misses the quadratic growth.

Question 10 of 10

A 15-item linear search always starts at the front. The target is first with probability 1/5, absent with probability 3/10, and otherwise uniformly placed among positions 2 through 15. What is its expected comparison count?
  1. 8.00
  2. 9.25
  3. 8.70
  4. 8.95
Show answerHide answer
Answer: D
Positions 2 through 15 average 8.5 comparisons and together have probability one half. Weighting the three cases gives 0.2×1+0.3×15+0.5×8.5=8.95. Using 8 as the present-position mean incorrectly includes position 1 again inside the final group.
Set 2: Trace loops and hidden Python work10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Two separate loops scan the same n-item list once each. Each loop body is constant time. What is the tight total time?
  1. Θ(n2)
  2. Θ(n)
  3. Θ(log⁡n)
  4. Θ(1)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

How many calls to visit occur when n = 9?

for i in range(n):
    for j in range(i):
        visit(i, j)
  1. 45
  2. 81
  3. 18
  4. 36
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What tight time bound holds for positive integer n if visit is constant time?

k = n
while k > 0:
    for j in range(k):
        visit(j)
    k //= 2
  1. Θ(n)
  2. Θ(nlog⁡n)
  3. Θ(log⁡n)
  4. Θ(n2)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

How many body executions occur?

i = 1
while i * i <= 80:
    i += 1
  1. 9
  2. 40
  3. 8
  4. 7
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A nonempty n-item list is repeatedly replaced by items[1:] until empty. What is the tight total copying time?
  1. Θ(n)
  2. Θ(nlog⁡n)
  3. Θ(n2)
  4. Θ(1)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Lists a and b contain n and m fixed-size integers. What average time bound includes building seen = set(b) once and then testing every item of a in seen?
  1. O(n+m)
  2. O(nm)
  3. O(n)
  4. O(m)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A function takes Θ(n+m) time. Its inputs always satisfy m≤6n and n≥1. What one-variable tight bound follows?
  1. Θ(m)
  2. Θ(nm)
  3. Θ(n2)
  4. Θ(n)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A positive integer counter starts at n. Iteration 1 subtracts 1, iteration 2 subtracts 2, iteration 3 subtracts 4, and each later subtraction doubles. The loop stops when the counter is nonpositive. What is its tight iteration growth?
  1. Θ(n)
  2. Θ(log⁡n)
  3. Θ(n)
  4. Θ(nlog⁡n)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What tight time bound holds for constant-time visit?

k = 1
while k < n:
    for j in range(k):
        visit(j)
    k *= 2
for j in range(n):
    visit(j)
  1. Θ(n)
  2. Θ(nlog⁡n)
  3. Θ((log⁡n)2)
  4. Θ(n2)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An n-item list of fixed-size values is repeatedly replaced by items[1:] until empty. No earlier suffix is saved, and automatic reclamation releases unused lists. What are the tight total time and peak auxiliary-space bounds?
  1. Time Θ(n); space Θ(n).
  2. Time Θ(n2); space Θ(n2).
  3. Time Θ(n2); space Θ(n).
  4. Time Θ(n); space Θ(1).
Show answerHide answer

Save this lesson to see this answer.

Set 3: Compare storage and sequence costs10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

An unchanged n-item array receives q arbitrary range-sum queries. What total time bound includes a prefix table and all queries?
  1. O(nq)
  2. O(q)
  3. O(n+q)
  4. O(nlog⁡q)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A dynamic array starts empty with capacity 1 and doubles only when full. Count one unit per copied entry and one per appended write. What is the total for 10 appends?
  1. 25
  2. 19
  3. 31
  4. 20
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A function sums an existing n-item list using two fixed-size variables and creates no collections. What is its auxiliary-space bound?
  1. O(n)
  2. O(n2)
  3. O(log⁡n)
  4. O(1)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A prefix table begins with zero and stores sums of the first k entries. For data = [6, 2, 5, 3, 8, 4], what subtraction answers the sum of indices 2 through 4?
  1. prefix[4] - prefix[2]
  2. prefix[5] - prefix[2]
  3. prefix[5] - prefix[1]
  4. prefix[4] - prefix[1]
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What total copying growth results from increasing a dynamic array's capacity by a fixed five slots on every resize across n appends from empty?
  1. Θ(n2)
  2. Θ(n)
  3. Θ(nlog⁡n)
  4. Θ(log⁡n)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An empty stack receives 11 pushes, multipop(7), 4 pushes, and multipop(20). How many successful pops occur in total?
  1. 27
  2. 20
  3. 11
  4. 15
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What tight time bound holds for positive n and constant-time visit?

j = 0
for i in range(n):
    while j < n and j * j <= i:
        visit(j)
        j += 1
  1. Θ(nn)
  2. Θ(n)
  3. Θ(n)
  4. Θ(n2)
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two lists of fixed-size integers have lengths n and m, both at least 1. A function builds a set of the second list, then for each item of the first list copies that whole second list and tests membership in the set. Copies are discarded after each iteration. What are its average time and peak extra space?
  1. Time Θ(n+m); space Θ(m).
  2. Time Θ(nm); space Θ(nm).
  3. Time Θ(nm); space Θ(m).
  4. Time Θ(n+m); space Θ(n+m).
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

The best-case cost of a search is 1 and its worst-case cost is n. What tight bound describes its worst-case function?
  1. Θ(1)
  2. Θ(n2)
  3. Θ(log⁡n)
  4. Θ(n)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An unchanged n-item array receives n2 queries, each covering at least half its items. Compare direct summation with building a prefix table once. What are the tight total time bounds?
  1. Direct Θ(n2); prefix Θ(n).
  2. Direct Θ(n3); prefix Θ(n2).
  3. Direct Θ(n3); prefix Θ(n).
  4. Direct Θ(n2); prefix Θ(n2).
Show answerHide answer

Save this lesson to see this answer.

Set 4: Analyze complete functions and guarantees10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What eventual growth order places square-root, logarithmic, linearithmic and linear rates from slowest to fastest?
  1. n,log⁡n,n,nlog⁡n
  2. log⁡n,n,n,nlog⁡n
  3. log⁡n,n,n,nlog⁡n
  4. log⁡n,n,nlog⁡n,n
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What tight rate describes 3log⁡2(n5)+2(log⁡2n)2?
  1. Θ((log⁡n)2)
  2. Θ(log⁡n)
  3. Θ(n5)
  4. Θ(nlog⁡n)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Exact model costs are A(n)=24n and B(n)=n2. For what positive integer sizes does A use strictly fewer steps?
  1. n<24
  2. n≥24
  3. n>576
  4. n>24
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A recursive computation makes 500,000 calls overall, but at most 30 are active together. Each active call holds a constant-sized frame and no growing local collection. What determines its peak call-stack space?
  1. 500,000 simultaneous frames.
  2. 30 simultaneous frames.
  3. 500,030 simultaneous frames.
  4. One reusable frame.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What tight time bound holds for constant-time visit?

k = n
while k > 0:
    j = 1
    while j < k:
        visit(j)
        j *= 2
    k //= 2
  1. Θ((log⁡n)2)
  2. Θ(log⁡n)
  3. Θ(n)
  4. Θ(nlog⁡n)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What are the tight worst-case time and peak auxiliary-space bounds for fixed-size integers, counting the output?

def collect(a):
    out = []
    for i in range(len(a)):
        tail = a[i:]
        out.append(sum(tail))
    return out
  1. Time Θ(n); space Θ(n).
  2. Time Θ(n2); space Θ(n2).
  3. Time Θ(nlog⁡n); space Θ(n).
  4. Time Θ(n2); space Θ(n).
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A valid queue sequence starts empty, enqueues r items, dequeues half of them, enqueues r more, then dequeues until empty. It uses two stacks and transfers only when the removal stack is empty. What are the total transfers and largest possible transfer in one dequeue, for even positive r?
  1. Total 3r; largest 2r.
  2. Total r; largest r.
  3. Total 2r; largest r.
  4. Total 2r; largest 2r.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An n-item list of fixed-size integers cannot be modified. A duplicate test may keep at most a fixed number of extra values and must return one Boolean. Among pair comparisons, sorting a copy, and building a seen set, what method meets the memory limit and what is its worst-case time?
  1. Sorting a copy; O(nlog⁡n).
  2. Pair comparisons; Θ(n2).
  3. A seen set; O(n).
  4. Pair comparisons; Θ(n).
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A collection documents amortized constant-time append, with linear worst-case time for an individual call. What time guarantee does this give for the next append?
  1. It must finish in constant time.
  2. It has constant expected time under every input distribution.
  3. It may take linear time in the current length.
  4. It takes linear time on every call.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

For positive integer n, a function costs T(n)=n2 when n is even and T(n)=n when n is odd. What are the smallest polynomial upper rate and largest polynomial lower rate that bound it at every sufficiently large size?
  1. Upper O(n2) and lower Ω(n).
  2. Upper O(n2) and lower Ω(n2).
  3. Upper O(n) and lower Ω(n).
  4. Upper O(n2) and lower Ω(1).
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

69 Key Terms, each with its definition

A

Aggregate counting
Aggregate counting bounds a sequence's total work by counting how often each item or unit of progress can contribute across the whole run.
Successful multipop removals cannot outnumber pushes when the stack begins empty.
Amortized cost
An amortized cost bounds total work over every allowed sequence divided by its length, permitting some expensive individual operations.
A resizing append can be linear even though a sequence of appends has constant amortized cost.
Arithmetic series
An arithmetic series adds terms separated by a fixed difference; adding the integers from 1 through a bound gives a quadratic total.
Scan lengths 1, 2, 3 and onward produce a triangular count, not a linear total.
Asymptotic analysis
Asymptotic analysis describes resource growth for sufficiently large inputs, absorbing fixed factors and disregarding a finite initial range.
A method can have better asymptotic growth while taking longer on small inputs.
Auxiliary space
Auxiliary space is storage used beyond the supplied input; an analysis should state whether newly built output is counted in it.
A running sum over an existing list uses constant auxiliary space in the fixed-size-number model.
Average case
The average case is the expected cost over inputs of a fixed size, calculated using a stated probability distribution.
A uniformly placed present target gives a different search expectation from a frequently absent target.

B

Best case
The best case at a fixed input size is the smallest cost among all inputs of that size, describing the most favorable data.
A first-position match gives linear search one comparison even when the list is very long.
Big-O
Big-O states an eventual upper bound: a function stays below a fixed positive multiple of another beyond some fixed input size.
A quadratic upper bound can be true for a linear function while providing less useful information.
Big-Omega
Big-Omega states an eventual lower bound: a function stays above a fixed positive multiple of another beyond a fixed input size.
A quadratic lower bound on a worst-case function shows that some inputs really need quadratic work.
Big-Theta
Big-Theta states a tight growth rate by bounding a function above and below with positive constant multiples of the same rate.
Matching quadratic upper and lower bounds establishes a quadratic Theta claim.
Binary search
Binary search checks the middle of a sorted candidate range and removes the half that cannot contain the target after each comparison.
A million-entry sorted list needs at most twenty middle-item checks in the worst case.

C

Call stack
The call stack holds frames for currently active function calls, including local state that must remain available until each call returns.
A recursive chain of linear depth uses linear stack space with constant-sized frames.
Capacity
The capacity of a dynamic array is its number of reserved entry slots, which can exceed the number of currently stored entries.
An array of length five and capacity eight can accept three more entries before it becomes full.
Case witness
A case witness is an input or input family that demonstrates a claimed amount of work is actually reached in the specified case.
Lists of distinct values force a pairwise duplicate check to examine every index pair.
Change of base
The change-of-base identity expresses one logarithm as a constant multiple of another when both bases are fixed and greater than 1.
Base-2 and base-10 logarithmic loop counts belong to the same asymptotic class.
Conditional branch
A conditional branch is a path selected by a test; an execution pays for the test and the selected path's work.
A function that either scans a list or returns immediately has data-dependent running time.
Constant factor
A constant factor multiplies a cost by an amount independent of input size and is absorbed by asymptotic bounding constants.
A loop visiting every other entry changes a linear scan's constant factor but keeps its rate.
Cost model
A cost model states which operations count as basic work, making a step count meaningful and allowing consistent comparisons.
A search can be analyzed by counting item comparisons without counting each machine instruction.
Credit argument
A credit argument saves part of each operation's assigned charge to pay later expensive work, illustrating an amortized total bound.
Three units per append can pay for writes and future copying in a simple doubling model.
Crossover point
A crossover point is an input size at which two exact cost models tie, separating regions where one or the other requires less work.
A low-overhead quadratic method can win before a linear method reaches their crossover.

D

Dependent loop
A dependent loop has an iteration count that changes with an enclosing loop's variable, so its total work often requires a sum.
Starting the inner index just after the outer index visits each distinct-position pair once.
Dominant term
The dominant term is the part of an expression that controls its eventual growth, with lower-order terms becoming small in comparison.
In a positive quadratic-plus-linear cost, the square determines the asymptotic rate.
Doubling experiment
A doubling experiment compares measured running times at successively doubled input sizes to assess a proposed growth model.
Consecutive time ratios near four support quadratic growth for the tested input family.
Dynamic array
A dynamic array stores entries in indexed slots and increases its reserved storage when more entries need to be appended.
A Python list can append into spare slots until a growth operation reserves more storage.

E

Early exit
An early exit ends a loop or function before its usual endpoint, allowing some inputs to avoid work that others must perform.
A duplicate check can stop at its first matching pair while distinct data forces a full search.
Exponential growth
Exponential growth places the input size in an exponent, so each fixed increase in size multiplies the model's work by a fixed factor.
The number of subsets doubles whenever one more distinct item becomes available.

F

Factorial growth
Factorial growth follows the product of the positive integers up to the input size and arises when considering every possible ordering.
Adding an eleventh distinct item multiplies the number of orderings of ten items by eleven.
Feasibility estimate
A feasibility estimate compares an expected operation count with a stated execution rate and time budget for the planned input size.
Dividing a billion model steps by a billion steps per second predicts about one second.
Fixed overhead
Fixed overhead is work whose cost does not grow with input size, such as setup or function-call control in the chosen model.
At tiny input sizes, fixed overhead can obscure the growth visible in larger timing runs.

G

Geometric series
A geometric series adds terms related by a fixed ratio; shrinking terms by one half keeps their total below twice the first term.
Halving the length of each later scan gives linear total work despite repeated scans.

H

Halving loop
A halving loop repeatedly divides a changing quantity by 2, giving logarithmically many iterations before a fixed small stopping size.
The positive integer values 8, 4, 2 and 1 are four visits before integer division reaches zero.
Hash collision
A hash collision occurs when different keys map to the same hash location or hash value, causing additional work to distinguish them.
Many colliding keys can make a lookup linear even though its usual average bound is constant.
Hashability
Hashability is the property that lets an object serve as a set entry or dictionary key with a stable hash and compatible equality behavior.
A list of lists cannot be deduplicated with a set because its inner lists are unhashable.
Hidden scan
A hidden scan is traversal performed inside a library operation or expression, so its cost grows even without an explicit loop at that point.
Membership in a Python list can scan every entry before reporting that a target is absent.

I

In-place algorithm
An in-place algorithm rearranges its input using little additional memory, often a constant amount independent of input length.
Swapping entries to reverse a list needs only indices and one temporary reference.
Independent sizes
Independent sizes measure input dimensions with no stated relationship, so one size cannot be removed from a cost bound without justification.
Scanning lists of lengths n and m keeps both variables in the combined bound.
Input distribution
An input distribution assigns probabilities to possible inputs and determines how their individual costs contribute to an expected cost.
Giving unsuccessful searches probability one half changes the average comparison count.
Input size
The input size measures the quantity that can grow in a problem, such as the number of list entries or characters being processed.
Comparing two lists may require separate sizes for the shorter and longer collection.
Iteration
An iteration is one execution of a loop body; its work and the number of repetitions together determine the loop's cost.
A loop visiting alternate indices makes about half as many iterations as a complete scan.

L

Linearithmic growth
Linearithmic growth is proportional to the input size times its logarithm, larger than linear but much smaller than quadratic eventually.
Efficient comparison sorting has a linearithmic worst-case upper bound.
Logarithmic growth
Logarithmic growth increases by a fixed amount when input size is multiplied by a fixed factor, as in repeated range halving.
Doubling a sorted search range adds only about one more reduction to binary search.
Loop body cost
The loop body cost includes all work in one iteration, including growing operations called inside otherwise short code.
When a loop over one list tests membership in another list, one outer iteration can be linear in that other list's length.
Loop bookkeeping
Loop bookkeeping is the repeated control work that advances a loop and checks whether another iteration should execute.
Including loop bookkeeping changes an exact operation count but may leave its growth rate unchanged.
Loose bound
A loose bound is valid but leaves a gap between the bounding function's growth rate and the actual function's growth rate.
A cubic upper bound on a quadratic count is safe but hides how the work actually grows.

M

Monotone counter
A monotone counter moves in only one direction; its total movement can bound work shared across many outer iterations.
A boundary that only advances through a list can make at most one advance per position.
Multipop
A multipop removes up to a requested number of available stack entries in one operation, stopping if the stack becomes empty.
One multipop may remove many entries, but it cannot remove an item twice without another push.

N

Nested loops
Nested loops place one loop inside another, repeating the inner work for each outer iteration unless control flow prevents it.
Two complete independent scans nested together multiply their lengths in the visit count.

O

Orderability
Orderability means values support the comparisons a sorting method needs, allowing it to arrange them consistently by order.
Sorting-based duplicate checks need orderable items, while pairwise equality checks do not.

P

Peak live memory
Peak live memory is the largest amount of storage held at one time during execution, including simultaneous temporary objects.
Discarding one temporary copy before building the next avoids keeping all copies together.
Polynomial growth
Polynomial growth has a fixed power of the input size, with quadratic and cubic growth as common examples of its different rates.
Checking each triple of positions has cubic growth, which is polynomial rather than exponential.
Prefix sum
A prefix sum is the total of an initial portion of a sequence; a table of these totals answers range sums by subtraction.
Starting a prefix table with a zero lets a query begin at the first item without a special case.
Preprocessing
Preprocessing performs preparation once so later operations can reuse its result, with its time and memory included in the full cost.
Building a prefix table pays a linear setup cost before constant-time range queries.
Primitive operation
A primitive operation takes constant time in the selected model, such as reading an indexed slot or adding fixed-size numbers.
A call to sum(items) includes a scan, so its whole body is not one primitive operation.
Product rule
The product rule combines repeated costs by multiplying their bounds, retaining every factor that grows with the input.
A fresh logarithmic inner loop for every item yields linearithmic total work.
Proportional growth
Proportional growth increases array capacity by a fixed factor greater than 1, producing a geometric sequence of resize-copy costs.
Doubling capacity makes the total number of copied entries linear over appends from empty.

R

RAM model
The RAM model is a computation model that gives constant cost to direct memory access and basic operations on fixed-size values.
Reading one list slot costs the same model unit at the start or near the end of the list.

S

Sequential blocks
Sequential blocks are pieces of code executed one after another, so their resource costs over an execution add together.
Two separate scans of the same list do linear total work because the scans run in sequence.
Slice copy
A slice copy creates a new collection from selected entries and costs time and memory proportional to the number of entries copied.
Repeatedly copying the remaining suffix of a list gives quadratic total copying time.
Sliding window
A sliding window tracks a contiguous part of an input with boundaries that move as items enter or leave the current range.
For positive values and a nonnegative limit, advancing each boundary only forward gives linear total work.
Space complexity
Space complexity describes how memory needs grow with input size, using a stated measure such as total or auxiliary peak storage.
A function may have quadratic running time while storing only a fixed number of counters.
Streaming
Streaming processes data as it arrives or in one pass while retaining a limited summary instead of storing every original item.
A stream's running maximum answers a maximum query but does not preserve all individual values.
Sum rule
The sum rule says that a sum of nonnegative functions has the tight growth rate of their maximum, up to constant factors.
A full pair check followed by a single scan still has a quadratic total cost.

T

Threshold
A threshold in an asymptotic proof is a fixed input size beyond which its required inequality holds for every larger size.
A bound may fail at size 1 yet remain valid with a threshold of 2 or another fixed value.
Tight bound
A tight bound matches a cost's growth from both directions, so the rate neither overstates nor understates its asymptotic order.
Counting the pairs of distinct positions in a list has a tight quadratic bound even though the count is roughly half a square.
Time complexity
Time complexity describes how an algorithm's amount of work grows with its input size under a stated model and input case.
A sum of all list entries has linear time complexity even when implemented in one Python line.
Time–space trade-off
A time–space trade-off reduces computation by keeping more information, or saves memory by allowing more work to be repeated.
A seen set speeds duplicate detection while requiring storage for earlier distinct items.
Total space
Total space includes both the input storage and the additional memory required while the algorithm executes.
Including an existing list makes total space linear even when the function adds only a counter.
Two-stack queue
A two-stack queue enqueues into one stack and dequeues from another, transferring entries only when the removal stack is empty.
Each entry transfers once, so many queue operations share a linear total amount of transfer work.

W

Worst case
The worst case at a fixed input size is the largest cost among all inputs of that size, supplying an upper guarantee for each input.
A missing target forces linear search to inspect every entry in a nonempty list.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started