Big-O Notation: Algorithm Analysis
IntermediateLesson 1 of 10 in Data Structures and Algorithms Course
What you will learn
- 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 modelExplain 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 codeCount 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 casesFind 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.
- Choose an input size and a cost model
- 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 boundsState 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 boundsDefine 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 notationApply the rules for constant factors, sums, products, polynomials, logarithms and several input sizes to reduce a cost expression to its simplest correct form.
- Define and prove Big-O upper bounds
- 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 algorithmsOrder the standard growth rates, name them, link each to a typical algorithm and judge which are practical for large inputs.
- Recognize logarithmic growthExplain 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 timingUse 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.
- Rank the common growth rates and match them to algorithms
- 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 loopsFollow 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 loopsAdd 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 operationsRecognize which Python list, set and dictionary operations take constant time and which hide a loop, and include their cost when analyzing a complete function.
- Analyze sequential and nested loops
- 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 usesDistinguish 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 timeRecognize time–space trade-offs, use stored information to speed up repeated work, and choose a solution that fits the time and memory available.
- Measure the extra memory an algorithm uses
- 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 arrayShow 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 operationsUse aggregate counting to show that loops and data-structure operations which are sometimes expensive do only a limited amount of work in total.
- Explain the amortized cost of appending to a dynamic array
Big-O Notation study guide
1Measure 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 for a list's length or a string's character count. If two independent lists have lengths and , keep both names. Scanning each list once involves item visits. Comparing every item of one with every item of the other involves 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 visits for an integer . 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 . Counting each item fetch as well gives . 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 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 and memory as , 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 visits for items. If the body costs a fixed amount, the loop's cost is proportional to . 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, additions and one return. The chosen model gives steps. If an addition and its assignment are counted separately, the expression changes, but the dependence on 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 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 . The count is . 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 .
Add sequential work
for value in items:
inspect(value)
for value in items:
record(value)
If each call has constant cost, this code makes 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 items. The total is 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 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
| Case | Cost at a fixed size |
|---|---|
| Best | Smallest cost among inputs of that size |
| Worst | Largest cost among inputs of that size |
| Average | Expected 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 , the best case takes one comparison because the target is first. The worst takes 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 have equal probability. Add and divide by the number of positions:
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 and the present ones average :
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 item comparisons. On reverse-sorted data, the new item is compared with all earlier items, giving 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 time and best-case 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.
2Describe 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, is when positive constants and exist such that
The multiplier absorbs fixed factors. The threshold allows a finite set of small sizes to behave differently. Both are fixed independently of . 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 means that belongs to a set of bounded functions. Its equals sign is one-way shorthand. The statement is true, but swapping its sides does not make true.
Build a proof
Let . For , both and . Bound each term using the same square:
Thus and prove . The constants need not be the smallest possible. Another valid choice is and : the needed inequality becomes , which holds for every integer . 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 were . Its required inequality would be beyond a fixed threshold. Dividing by positive gives . But an integer larger than both and violates it. No fixed multiplier can cover the growing ratio, so the proposed linear upper bound fails.
Understand what simplification removes
At , the leading term 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 ; it does not become numerically unimportant.
Upper bounds can be loose. The function is , and . The linear bound communicates more. A tight bound will need a lower bound too.
Finally, 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
| Notation | Required inequality beyond a fixed threshold | Meaning |
|---|---|---|
| Upper bound | ||
| Lower bound | ||
| 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 is and as well as . Only matching upper and lower rates establish Theta.
Prove a tight polynomial bound
For ,
The first inequality follows because the added terms are nonnegative. The second follows by bounding each term with a multiple of . Choose , and . The function is . More generally, a polynomial with positive leading coefficient and degree has growth .
For a pair-counting loop, the cost needs slightly more care because of the subtraction. The upper inequality is . For , use to get
This proves 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 , so it is . The best-case function equals 1 for nonempty lists, so it is . Across all inputs its cost is bounded above by and below by . Calling every execution would overlook a first-position match at any large size.
Insertion sort has best-case and worst-case comparison counts. Saying its worst case is 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 , and are all . 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:
Thus the sum has the tight growth rate of the maximum. In , the square eventually dominates, so the result is . This is the rule for sequential blocks.
Products keep their growing factors. An outer loop with iterations and an inner body of cost has total . 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 is 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:
Consequently and have the same asymptotic rate. The identity also gives . Keep separate: the factor multiplies the logarithm and grows with the input.
Exponentials follow a different rule
The expression differs from by a constant factor. But has ratio to . That ratio is unbounded, so is not . A fixed base in an exponential cannot be ignored the way a fixed logarithm base can.
Bounds are transitive. If and , then . For example, and imply . Such a statement is correct even when loose.
Preserve independent sizes
Scanning lists of lengths and takes work. There is no single dominant variable unless a relationship is known. If , the sum is bounded by and becomes . With no such restriction, may grow while stays small.
For , the expression is between and , so it is . The condition on justifies absorbing the extra . Write a simplified bound such as once the reasoning is complete, instead of leaving 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.
3Compare 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 , the usual rates increase in this order:
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 with fixed is polynomial. In a polynomial the input is the base; in the input is the exponent.
| Pattern | Typical cost |
|---|---|
| Read a list entry by index | Constant |
| Repeatedly halve a search range | Logarithmic |
| Sum a list | Linear |
| Efficient comparison sort | Linearithmic worst-case upper bound |
| Examine every pair | Quadratic |
| Examine every triple | Cubic |
| Consider every subset | Exponentially many subsets |
| Consider every ordering | Factorially 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.
| ! | ||||||
|---|---|---|---|---|---|---|
| 10 | 3.3 | 33 | 100 | 1,000 | 1,024 | 3,628,800 |
| 100 | 6.6 | 664 | 10,000 | 1,000,000 | About | About |
| 1,000 | 10.0 | 9,966 | About | Beyond 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, exceeds for integer sizes 2 through 9. From size 10 onward, exceeds . Every fixed polynomial is eventually outgrown by .
Estimate feasibility
Assume a rate of simple steps per second. For a million items, about linearithmic steps take 0.02 seconds, while quadratic steps take 1,000 seconds, nearly 17 minutes. These are model-based estimates; different operations have different real costs.
With that same rate, steps take about one second and take about 13 days. Performing 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 , 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 , inspect sees 16, 8, 4, 2 and 1. The next division produces 0 and the loop stops. The exact count for positive integer is . 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 . The count is , so reaching 16 takes four updates. Both loops are even though their endpoint counts differ.
Dividing by 3 each time gives about visits. The change of base only changes a constant factor. Subtracting 2 each time gives about 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 after four iterations. After iterations, has been removed. Reaching a value proportional to 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 reductions, the remaining range has roughly items. That becomes about one item when reaches .
For a nonempty sorted list, the worst case checks at most 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 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 items gives , 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 . 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 , increasing size by a factor increases time by approximately . A quadratic program taking 0.5 seconds at 1,000 items is predicted to take seconds at 4,000 items. A linear program starting at the same time would take about 2 seconds.
| Cost model | Effect of doubling input |
|---|---|
| Constant | No growth |
| Add 1 to the cost expression | |
| Multiply by 2 | |
| Slightly more than multiply by 2 | |
| Multiply by 4 | |
| Multiply by 8 | |
| Square the cost expression |
For linearithmic work from 1,000 to 2,000, the ratio is about 2.2. For exponential work, the exact identity explains why a fixed doubling ratio is inappropriate.
Run a doubling experiment
Use time.perf_counter() to measure elapsed time at sizes , , and . 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 steps and B takes . For positive sizes, equality occurs when , or . 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 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 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.
4Analyze 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
- Name each independent input size.
- Find the cost of the innermost operation, including calls.
- Count its repetitions in each enclosing loop.
- Add the costs of blocks that run one after another.
- 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 items, each outer visit starts a fresh inner scan of all items. The comparison runs times. Its truth value changes how often count increases, but not how often the comparison runs. Both best- and worst-case time are under constant-time comparisons. At 1,000 items the code makes a million comparisons.
Three independent loops over range(n) give body executions. At that is a million. If two nested loops visit separate lists of lengths and , their product is , not . 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 calls, hence . The inner loop adds a fixed factor. Replacing its bound with a doubling loop up to instead gives logarithmic inner work and 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 , so the tight growth rate remains . A second independent scan adds work; it does not multiply the first block by .
For two consecutive loops over different lists, the cost is . For nested full scans of those same lists, it is . 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 later indices. For the next there are , and the final index has none. The total is
This visits every pair of distinct positions once, with . At five items there are ten visits. At 1,000 there are 499,500. Halving a quadratic count leaves its rate .
The general arithmetic sum is . Three loops constrained by visit each triple once, giving , or 120 visits at ten items. That count has cubic growth.
Distinguish two logarithmic outer patterns
For each of items, a fresh inner counter starting at 1 and doubling until it reaches makes updates. This count is the same on every outer visit, so multiplication is exact: . 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 . This is a geometric pattern. Its sum is less than and at least because the first scan alone has length . Therefore the total is . At 16 it makes visits; at 1,000 it makes 1,994.
Multiplying the logarithmic number of outer iterations by the largest scan length produces . 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 . There are such values. A million permits 1,000 visits, so the loop is under fixed-size arithmetic.
Check whether a nested counter resets. A counter that keeps advancing through the input can advance at most 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 | Time cost |
|---|---|
len(items), items[i], indexed assignment | |
append(x), pop() at the end | Amortized |
Membership, index, count, min, max, sum, copying | worst case |
insert(0, x), pop(0) | |
| Slice of items | |
sorted(items), items.sort() | 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 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 items are distinct, the membership scans have lengths 0, 1, 2, through . They total 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 on average and uses linear extra storage. The set needs hashable items.
Include copying and shifting
Repeatedly replacing items with items[1:] copies 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 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 and give worst-case time with lists. Converting b to a set once costs average , after which the checks cost average . Include preparation to report average overall.
For duplicate detection, all-pairs comparison is quadratic in the worst case; sorting a copy and checking neighbors has an 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.
5Analyze 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 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 entries uses space. A set of distinct values seen so far can hold up to entries. A stored square grid with rows and cells per row needs 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 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 references, using 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 pairs if it builds them all in memory. That output alone takes space and at least 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 calls are active together at maximum depth, constant-sized frames use 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
| Method | Time | Extra space |
|---|---|---|
| Compare every pair | Worst-case | |
| Sort a copy and check neighbors | Worst-case | |
| Store seen items in a set | Average |
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 through , subtract prefix[i] from prefix[j]. The latter includes all items before ; subtraction removes exactly those before . For indices 1 through 3, prefix[4] - prefix[1] is , matching .
Building the table takes time and stored numbers. Each query then takes constant time. For queries, the total is , compared with worst-case 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 words with distinct values, a frequency dictionary updates one count per word. This gives average time and extra space under constant-cost hashing and comparison of the words. Rescanning the input for each distinct word can take 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.
6Explain 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:
Add sixteen writes to get 31 units. The seventeenth append needs another resize and copies sixteen entries. Its sequence total becomes units. That individual call is expensive even though most calls perform only a write.
Bound the geometric total
For any positive number of appends from empty, copied capacities form a doubling series. The last copied capacity is less than , and the sum of all copied capacities is less than twice that last capacity, hence less than . Adding writes gives fewer than 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 to and from to , another items arrive and save credits, enough for the next copy. Equivalently, when capacity has just filled, its newest items supply the 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 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 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 operations, there are at most pushes and therefore at most successful pops. Include constant overhead per operation and the total remains . The amortized cost is , despite a possible linear-cost multipop. Starting empty matters: items already present would add to the available pop work.
A moving boundary advances only 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 times. The right loop also advances times. Including tests gives linear total time, . 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 enqueues and dequeues from an empty queue costs 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 and . Each step writes an item and advances one of two indices. Neither index retreats, so producing the merged list takes 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
1From Python code to a cost function
12 steps
- 1IntroductionAsk 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.
- 2ExplanationName the size and the operation
Let 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.
- 3ExampleLook inside one line
The expression
sum(readings)is one line, but it processes all 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. - 4ChallengeChoose 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, and . The full comparison count is . 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.
- 5ExampleCount the summing loop
For this function, count initialization, additions and return:
def total(readings): result = 0 for value in readings: result += value return resultInitialization runs once. The addition runs once per entry, or times. The return runs once. Under this model, the total is . Counting item fetches too would alter the coefficient, not the linear growth.
- 6Key InsightA second scan adds work
Suppose a separate loop checks all readings after the total has been computed. It adds another visits. It does not repeat the summing function for every reading.
The combined count is proportional to . Sequential blocks add. Multiplication becomes appropriate when one block's work restarts inside every iteration of another loop.
- 7ChallengeCount 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.
- 8ExplanationKeep the size fixed
A linear search checks list entries from the front until a match occurs. For a nonempty -item list, a first-entry match needs one comparison; a last-entry match or absent target needs . 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.
- 9ExampleCalculate 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.
The expectation can be fractional although each individual search uses a whole number of comparisons. This calculation depends on the stated position probabilities.
- 10ChallengeChange 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:
Using 4.5 alone would ignore the extra probability assigned to searches that inspect the whole list.
- 11ConnectionChoose 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 comparisons. When you report a bound, keep the case visible: worst-case and best-case describe different cost functions.
- 12RecapA 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.
2Build and test asymptotic bounds
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn a count into a growth statement
- 2ExplanationRead an upper-bound inequality
- 3ExampleBound each polynomial term
- 4ExampleChoose valid proof constants
- 5ChallengeReject a linear upper bound
- 6ExplanationAdd the matching lower bound
- 7ChallengeDoes a loose lower bound suffice?
- 8TipKeep notation separate from cases
- 9ExampleSimplify a sum and a logarithm
- 10Key InsightExponential bases behave differently
- 11ChallengeKeep both list lengths
- 12ChallengeCombine a proof and a simplification
- 13RecapState only the bound you have proved
3Predict which algorithms scale
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionUse growth to plan for larger inputs
- 2ExplanationRead the eventual growth order
- 3ExampleTranslate steps into seconds
- 4ChallengeCompare complete candidate searches
- 5ExampleTrace a halving process
- 6ConnectionHalve a sorted search range
- 7ChallengeRepeat a logarithmic loop
- 8ExampleScale a quadratic timing
- 9TipMake a timing comparison meaningful
- 10ChallengeRead measured ratios
- 11Key InsightSmall constants can decide the winner
- 12RecapCombine a model with evidence
4Analyze a function from its inner work outward
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart where the work happens
- 2ExampleMultiply independent scans
- 3ExplanationAdd a later pass
- 4ChallengeTest the nesting shortcut
- 5ExampleList changing inner lengths
- 6ExampleSum the triangular count
- 7Key InsightShrinking scans form a different sum
- 8ChallengeCount a fresh doubling inner loop
- 9ExampleFind a scan inside membership
- 10ExampleAdd the hidden comparison counts
- 11ConnectionRemember seen values in a set
- 12ChallengeDetect repeated copying
- 13TipCheck an operation and its item requirements
- 14ChallengeAnalyze a whole function
- 15RecapMatch the count to the code structure
5Compare memory use and stored results
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAdd memory to the performance claim
- 2ExplanationChoose auxiliary or total space
- 3ExampleCompare reversal with a reversed copy
- 4Key InsightSpace measures simultaneous storage
- 5ChallengeCount an explicitly built output
- 6ExampleBuild the prefix table
- 7ExampleSubtract off the unwanted prefix
- 8ChallengeInclude preparation and repeated queries
- 9ConnectionKnow what a summary retains
- 10ChallengeChoose under a memory limit
- 11RecapCompare the resources that matter
6Spread expensive operations across a sequence
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow the work across operations
- 2ExplanationSeparate length from reserved capacity
- 3ExampleTrace the doubling resizes
- 4ExampleBound the whole copy series
- 5AnalogySave credits before the copy
- 6ChallengeCompare growth policies
- 7TipUse the right guarantee for a deadline
- 8ExplanationCount successful stack removals
- 9ChallengeTrack what a batch removal can consume
- 10ConnectionCharge work to forward movement
- 11ExampleTransfer a queue item only once
- 12ChallengeConnect the sequence arguments
- 13RecapFind the limited source of repeated work
Big-O Notation practice questions
Set 1: Count work and describe its growth10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
for i in range(0, 17, 3)?Show answerHide answer
range stopping bound.Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
How many body executions occur for the code below?
i = 48
while i > 0:
i //= 2
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
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
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)
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What tight time bound holds for positive integer if visit is constant time?
k = n
while k > 0:
for j in range(k):
visit(j)
k //= 2
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
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
items[1:] until empty. What is the tight total copying time?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
a and b contain and fixed-size integers. What average time bound includes building seen = set(b) once and then testing every item of a in seen?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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)
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
data = [6, 2, 5, 3, 8, 4], what subtraction answers the sum of indices 2 through 4?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
multipop(7), 4 pushes, and multipop(20). How many successful pops occur in total?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
What tight time bound holds for positive and constant-time visit?
j = 0
for i in range(n):
while j < n and j * j <= i:
visit(j)
j += 1
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
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
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
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Aggregate counting
Amortized cost
Arithmetic series
Asymptotic analysis
Auxiliary space
Average case
B
Best case
Big-O
Big-Omega
Big-Theta
Binary search
C
Call stack
Capacity
Case witness
Change of base
Conditional branch
Constant factor
Cost model
Credit argument
Crossover point
D
Dependent loop
Dominant term
Doubling experiment
Dynamic array
E
Early exit
Exponential growth
F
Factorial growth
Feasibility estimate
Fixed overhead
G
Geometric series
H
Halving loop
Hash collision
Hashability
Hidden scan
I
In-place algorithm
Independent sizes
Input distribution
Input size
Iteration
L
Linearithmic growth
Logarithmic growth
Loop body cost
Loop bookkeeping
Loose bound
M
Monotone counter
Multipop
N
Nested loops
O
Orderability
P
Peak live memory
Polynomial growth
Prefix sum
Preprocessing
Primitive operation
sum(items) includes a scan, so its whole body is not one primitive operation.Product rule
Proportional growth
R
RAM model
S
Sequential blocks
Slice copy
Sliding window
Space complexity
Streaming
Sum rule
T
Threshold
Tight bound
Time complexity
Time–space trade-off
Total space
Two-stack queue
W
Worst case
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.