Discrete MathematicsAlgorithms and Growth of Functions2 of 4
Algorithms and Growth of Functions · 2
Counting Steps: Time Complexity of Loops and Recursive Algorithms
We already know how to simplify a step-count formula into Big O, Big Ω, and Big Θ, and now we need to count the steps directly from a piece of code.
1
Single Loops: Stepping vs. Doubling
To find the time complexity of a single loop that runs from start to finish, we count how many turns the loop takes as a function of the input size n and how much work happens inside each turn.
Single Loops: Stepping vs. Doubling
Text solution
Step by a constantWhen `for i = 1 to n` steps by +1 (or by +2, which visits every other number), the steps form a line (or half a line) whose length grows proportionally to n.
StepsandSteps=n=Θ(n)=2n=Θ(n)
Track i as a power of 2When a loop starts at i=1 and doubles the counter on each turn (`i = i * 2`), the value of i after k steps is 2k.
i=k doublings2×2×⋯×2=2k
Solve for the stopping step kThe loop stops as soon as i reaches n, so we set 2k=n and take the base-2 logarithm to find the total number of turns.
2k=n⟹k=log2(n)=Θ(logn)
2
Nested Loops: Grids, Rectangles, and Triangles
Now we want to find the total number of steps when one loop is nested inside another, so that the inner loop runs all over again on every turn of the outer loop. When the inner loop's upper limit changes with the outer counter i, counting the steps row by row uses the sum of the first n positive integers:
1+2+3+⋯+n=2n(n+1)
Nested Loops: Grids, Rectangles, and Triangles
Text solution
Multiply rows by columns when the bounds are independentWhen the outer loop runs n times and the inner loop runs the same number of turns every time (either n steps by adding 1, or log2(n) steps by doubling j), the steps form a full grid or rectangle.
n×nandn×log2(n)=n2=Θ(n2)=Θ(nlogn)
Add the rows when the inner bound depends on iIn `for i = 1 to n: for j = 1 to i`, row 1 has 1 dot, row 2 has 2 dots, and row n has n dots, forming a right-triangular staircase that fills half of the n by n square.
Steps=1+2+3+⋯+n=2n(n+1)
Drop the lower-order term and constant multiplierExpanding the triangle's area into half of the n2 square plus half of the n diagonal dots shows that half a square still grows like n2.
21n2+21n=Θ(n2)
In an n by n grid of steps, stopping the inner loop at i cuts the square in half along its diagonal to give 2n(n+1)=Θ(n2) dots, whereas doubling j shrinks the width to log2(n) columns and drops the total work to Θ(nlogn).
Stopping the inner loop at i cuts the square of steps in half, while doubling j on each turn shrinks it to a thin strip.
3
Loops That Stop Early: Best Case and Worst Case
Every loop so far ran all the way to its final limit, so the step count depended only on n. Now we want to count the array comparisons in Linear Search (`if A[i] == target: return true`), where the loop can stop early depending on what is inside the array A.
Loops That Stop Early: Best Case and Worst Case
Text solution
Find the best caseWhen `target` sits in the very first slot A[1], the first comparison succeeds and the function returns immediately.
Best case=1 comparison=Θ(1)
Find the worst caseWhen `target` sits in the last slot A[n] or is not in A at all, the loop checks every slot from A[1] through A[n] before finishing.
Worst case=n comparisons=Θ(n)
Bound the algorithm across all inputs of size nBecause any input takes at least 1 comparison and at most n comparisons, the best case sets the lower bound Ω and the worst case sets the upper bound O.
All inputs: at least 1Ω(1)andat most nO(n)
In Linear Search on A[1..n], the number of comparisons equals the slot position k where `target` first appears: from 1 comparison when `target` is in A[1] up to all n comparisons when `target` is in A[n] or missing from the array.
Even on the same array, Linear Search can stop after one check or check every slot, depending on where the item you want sits.
4
Recursive Chains: Subtracting vs. Halving
When a function calls itself instead of running a loop, we want to find the total steps T(n) by adding the local work inside one call to the work done by its smaller recursive calls, down to the base case at n=1.
Recursive Chains: Subtracting vs. Halving
Text solution
Set up the recurrence for a single callA function that does 1 step of local work and calls itself once has total steps equal to the smaller call's steps plus 1.
Count the chain when subtracting 1In T(n)=T(n−1)+1, the input size steps down through n,n−1,n−2,…,1, creating a single chain of n boxes doing 1 step each.
T(n)=n×1=n=Θ(n)
Count the chain when halving nIn T(n)=T(2n)+1, cutting n in half takes log2(n) steps to reach 1, creating a chain of log2(n)+1 boxes doing 1 step each.
T(n)=(log2(n)+1)×1=Θ(logn)
5
Divide-and-Conquer Recursion Trees
Next, we want to find the total steps T(n) when a function makes two recursive calls on half the input size (2n), which branches the calls into a binary recursion tree. When each call does 1 step of local work, the row totals double at each level and we use the geometric sum of powers of 2:
1+2+4+8+⋯+n=2n−1
Divide-and-Conquer Recursion Trees
Text solution
Add the local work across each row for Merge SortIn T(n)=2T(2n)+n, Row r has 2r calls that each do 2rn local merging work, so the doubling calls and halving sizes cancel on every row.
Row r work=2r×2rn=n
Multiply work per row by the number of rowsHalving n down to 1 produces log2(n)+1 rows of n work each.
T(n)=n(log2(n)+1)=Θ(nlogn)
Add the doubling rows when local work is 1In T(n)=2T(2n)+1, Row r does 2r×1=2r work down to 2log2(n)=n calls on the bottom row, so the whole tree adds up to roughly twice the bottom row.
T(n)=1+2+4+⋯+n=2n−1=Θ(n)
In a binary recursion tree that halves n at each level, doing local work equal to the subproblem size makes the bars on every row add up to the same width n, whereas doing 1 step of local work per call makes each row's total double from 1 at the top down to n on the bottom row.
When a recursion tree branches in two and halves the input at each level, doing work equal to each call's size makes every row add up to the full input size, while doing one step per call makes the row totals double until the bottom row holds roughly half the work.
6
Exponential Recursion Trees
Finally, we want to find the total moves T(n) when a function still makes two recursive calls per turn, as in the Towers of Hanoi puzzle, but only subtracts 1 from n at each level instead of dividing n by 2.
Exponential Recursion Trees and Shape Summary
Text solution
Write the recurrence for moving n disksMoving n disks requires moving the top n−1 disks twice and moving the largest disk once.
T(n)=2T(n−1)+1
Count the work on each row across n levelsBecause each call makes 2 calls of size n−1 doing 1 step each, the row totals double (1,2,4,8,…) across all n levels from size n down to size 1.
Row r workfor r=2r=0,1,…,n−1
Sum the doubling rows over all n levelsAdding the powers of 2 from Row 0 through Row n−1 gives an exponential step count.
T(n)=1+2+4+⋯+2n−1=2n−1=Θ(2n)
You can spot Θ(n2) for a triangular loop or Θ(nlogn) for T(n)=2T(2n)+n right away from its shape, but when a question asks for the exact number of steps, write out the row sum first before dropping constants and lower-order terms.
Key concepts
Before writing a complexity bound, check whether the code can stop early depending on the contents of the input (such as `if A[i] == target: return true`). When a loop can exit early, a single formula in n cannot describe every input: you bound the best case (Θ(1) when `target` is in A[1]) and the worst case (Θ(n) when `target` is in A[n] or missing) separately, which makes the algorithm Ω(1) and O(n) across all inputs of size n. Only when code always runs to its final limit do the minimum and maximum steps match, giving a single tight Θ bound for all inputs of size n.
For loops that run to completion, the shape of the dots gives the step count:
Key concept
In a single loop, adding or subtracting a constant (`for i = 1 to n (stepping by +2)`) steps through a line of 2n=Θ(n) dots, while multiplying or dividing by a constant (`i = i * 2` while `i < n`) reaches n in log2(n)=Θ(logn) steps.
Key concept
In nested loops, multiply the outer count by the inner count whenever every row has the same width: an n by n square (`j = 1 to n`) takes n2=Θ(n2) steps, and an n by log2(n) rectangle (`j = j * 2`) takes nlog2(n)=Θ(nlogn) steps. Do not multiply rows by columns when the inner bound depends on the outer counter (`for j = 1 to i`). Instead, sum the rows as a right triangle:
1+2+3+⋯+n=2n(n+1)=Θ(n2)
For recursive algorithms, the number of recursive calls per turn sets the branching and the input reduction sets the height:
Key concept
A single recursive call per turn forms a vertical chain: subtracting 1 (`T(n) = T(n - 1) + 1`) stacks n boxes for Θ(n), while halving (`T(n) = T(n/2) + 1`) stacks log2(n)+1 boxes for Θ(logn).
Key concept
Two recursive calls per turn form a binary tree, which we sum row by row. Halving the input (`2T(n/2)`) gives log2(n)+1 levels: when each call does local work equal to its subproblem size (`T(n) = 2T(n/2) + n`), doubling calls and halving sizes cancel so every row totals n, giving n(log2(n)+1)=Θ(nlogn); when each call does 1 step (`T(n) = 2T(n/2) + 1`), don't multiply by the height, because the rows double down to n on the bottom row:
1+2+4+⋯+n=2n−1=Θ(n)
Key concept
Subtracting 1 across two recursive calls (`T(n) = 2T(n - 1) + 1`) doubles the row work across all n levels, growing to 1+2+4+⋯+2n−1=2n−1=Θ(2n).
7
Practice
1
Suppose n=2k for a positive integer k. Find the exact number of steps performed by the following loop and give a tight Big Theta bound: ```text i = n while i > 1: do 1 step of work i = i / 2 ```
Watch out for the strict loop condition `i > 1`: the loop stops the moment i hits 1 rather than running one extra turn for i=1 (which is the slip that gives log2(n)+1).
Write the value of i in terms of k after 1,2,… turns. After how many halvings does i reach 1?
Starting at i=n=2k, each turn performs 1 step of work and cuts i in half: after 1 step i=2k−1, after 2 steps i=2k−2, and after k steps i=20=1. Watch out for the strict loop condition `i > 1`: the loop stops the moment i hits 1 rather than running one extra turn for i=1 (which is the slip that gives log2(n)+1). Thus the loop performs k=log2(n) steps, which is Θ(logn).
2
Suppose n=2k with k≥1. Find the exact number of steps performed by these nested loops and give a tight Big Theta bound: ```text i = 1 while i < n: for j = 1 to n (stepping by +2): do 1 step of work i = i * 2 ```
Be careful not to confuse `stepping by +2` with multiplying by 2 (which would wrongly give log2(n) inner steps and (log2n)2 overall) or forget that skipping every even number cuts the row width from n to 2n (which would give nlog2(n) as the exact count).Be careful not to confuse `stepping by +2` with multiplying by 2 (which would wrongly give log2(n) inner steps and (log2n)2 overall) or forget that skipping every even number cuts the row width from n to 2n (which would give nlog2(n) as the exact count).
Does the inner loop's limit depend on i, or does every turn of the outer loop perform the exact same number of inner steps?
The outer loop doubles i through 1,2,4,…,2k−1=2n, stopping as soon as i reaches 2k=n, so it runs k=log2(n) times. On each turn of the outer loop, the inner loop steps j by +2 through the odd numbers 1,3,5,…,n−1. Be careful not to confuse `stepping by +2` with multiplying by 2 (which would wrongly give log2(n) inner steps and (log2n)2 overall) or forget that skipping every even number cuts the row width from n to 2n (which would give nlog2(n) as the exact count). Multiplying the log2(n) rows by 2n dots per row gives 2nlog2(n) steps, which is Θ(nlogn).
3
Find the exact number of steps as a function of n and give a tight Big Theta bound for the following nested loop: ```text for i = 1 to n: for j = i to n: do 1 step of work ```
Don't subtract the endpoints as n−i without adding 1 for the starting value j=i, a slip that drops 1 dot from every row and gives 2n(n−1).
How many values of j run from i to n on row i=1, row i=2, and down to row i=n?
When i=1,j runs from 1 to n(n steps). When i=2,j runs from 2 to n(n−1 steps). This continues down to i=n, where j runs from n to n(1 step). Don't subtract the endpoints as n−i without adding 1 for the starting value j=i, a slip that drops 1 dot from every row and gives 2n(n−1). Adding the rows from n down to 1 gives
n+(n−1)+(n−2)+⋯+1=2n(n+1)=21n2+21n steps,
which is Θ(n2).
4
The following function checks whether an array A[1..n] (with n≥2) is sorted in non-decreasing order: ```text function isSorted(A, n): for i = 1 to n - 1: if A[i] > A[i + 1]: return false return true ``` Using the array comparison `A[i] > A[i + 1]` as the step count, describe a best-case input and a worst-case input, give the exact number of comparisons and tight Big Theta bound for each case, and give the Big Omega and Big O bounds that hold across all inputs of size n.
Don't assume a sorted array is the best case just because the function checks for sorting: a sorted array never triggers `return false`, so it forces the loop to run all the way through!
Which pair of elements makes `return false` trigger on i=1, and what kind of array forces the loop to check every adjacent pair?
Don't assume a sorted array is the best case just because the function checks for sorting: a sorted array never triggers `return false`, so it forces the loop to run all the way through! Instead, the best case occurs when the very first pair is out of order (A[1]>A[2]), where the loop returns `false` on i=1 after 1 comparison, which is Θ(1). The worst case occurs when the array is completely sorted in non-decreasing order (or only the final pair has A[n−1]>A[n]); watching the upper bound `n - 1` so you don't write n comparisons, the loop checks every adjacent pair from i=1 to n−1 for n−1 comparisons, which is Θ(n). Across all inputs of size n, the algorithm is Ω(1) and O(n).
5
Suppose n=2k for a non-negative integer k. Consider the following recursive function: ```text function process(n): if n == 1: do 1 step of work return process(n / 2) process(n / 2) for i = 1 to n / 2: do 1 step of work ``` Write a recurrence for the exact number of steps T(n), find the total work on each row of the recursion tree, and determine both the exact total step count and a tight Big Theta bound.
How many recursive calls and how many loop steps happen when n>1, and what happens at the bottom row when n=1?
For n>1, the function makes 2 recursive calls of size 2n and performs 2n steps in its loop, giving the recurrence
T(n)=2T(2n)+2nwith T(1)=1.
In the recursion tree, Row 0 has 1 call of size n doing 2n steps, Row 1 has 2 calls of size 2n each doing 4n steps for 2(4n)=2n steps, and each internal row r (for 0≤r<log2(n)) has 2r calls of size 2rn each doing 2r+1n steps, totaling 2n steps per row across the log2(n) internal rows. At the bottom row r=log2(n), don't apply the internal-row formula 2n (which would give 2n(log2(n)+1)): the 2log2(n)=n calls at the bottom have size 1 and hit the `if n == 1` base case, doing 1 step each for n steps. Summing all rows gives 2nlog2(n)+n steps, which is Θ(nlogn).
6
Compare two recursive functions that both return 2n−1 for an integer n≥1, where each function call counts as 1 step of local work: ```text function calcA(n): if n == 1: return 1 return calcA(n - 1) + calcA(n - 1)
function calcB(n): if n == 1: return 1 x = calcB(n - 1) return x + x ``` For each function, write the recurrence for the total steps, find the exact number of steps as a function of n, and give its tight Big Theta bound.
Its binary tree has n levels (from size n down to 1) whose row totals double each level (1,2,4,…,2n−1); be careful to include all n levels, because stopping one row early gives only 2n−1−1.
Count how many times each function actually calls itself on n−1 before returning.
In `calcA`, each call with n>1 makes two separate recursive calls of size n−1, giving TA(n)=2TA(n−1)+1 with TA(1)=1. Its binary tree has n levels (from size n down to 1) whose row totals double each level (1,2,4,…,2n−1); be careful to include all n levels, because stopping one row early gives only 2n−1−1. Adding all n rows gives 1+2+4+⋯+2n−1=2n−1 steps, which is Θ(2n). In `calcB`, don't write 2TB(n−1)+1 just because `x` appears twice in `x + x`. Storing `x = calcB(n - 1)` calls the function only once and reuses the number, giving TB(n)=TB(n−1)+1 with TB(1)=1, a single chain of n steps, which is Θ(n).