Retranslate the complete English edition from Simplified Chinese (#2010)

* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
This commit is contained in:
Yudong Jin
2026-10-31 03:35:51 +08:00
committed by GitHub
parent ef46e2ed95
commit 14c314c08c
1502 changed files with 29459 additions and 23517 deletions

View File

@@ -1,11 +1,11 @@
# Exercises
## Concept Review
## Check your understanding
### Time and Space Complexity of Iteration and Recursion
### Time and space in iteration and recursion
The two functions below both calculate $1 + 2 + \dots + n$ (assume $n \ge 1$). Set `n` to 4,
answer the questions by following the program's actual execution order, and then compare the efficiency of the two approaches.
Both functions below compute $1 + 2 + \dots + n$ (assume $n \ge 1$). Set `n` to 4,
follow the program's execution order to answer the questions, and then compare the efficiency of the two approaches.
```src
[file]{complexity_exercises}-[class]{}-[func]{sum_iter}
@@ -13,75 +13,75 @@ answer the questions by following the program's actual execution order, and then
<!-- numbered-subquestions -->
1. When the iterative function runs with `n = 4`, what is the value of the accumulator `res` after each loop iteration?
2. When the recursive function runs with `n = 4`, which values does the argument `n` take in order? As the calls return from the deepest level, how is the result obtained?
3. What are the time and space complexities of the two approaches? Explain your reasoning using the execution processes from Questions 1 and 2.
1. When the iterative function runs with `n = 4`, what is the value of the accumulator `res` at the end of each iteration?
2. When the recursive function runs with `n = 4`, what values does the parameter `n` take, in order? How is the result computed as the calls return, starting from the deepest call?
3. What are the time and space complexities of each approach? Explain using the execution steps from questions 1 and 2.
??? success "Answer"
??? success "Reference answer"
1. The loop variable `i` takes the values `1, 2, 3, 4`. After each iteration, `res` becomes
1. The loop variable `i` takes the values `1, 2, 3, 4` in order. At the end of each iteration, `res` becomes
`1, 3, 6, 10`, respectively, so the iterative function returns 10.
2. The argument `n` takes the values `4 → 3 → 2 → 1`.
The deepest call returns 1. The remaining calls then obtain `2 + 1 = 3`, `3 + 3 = 6`, and `4 + 6 = 10`, in that order.
At the deepest point, all four function calls are still unfinished.
2. The parameter `n` follows the sequence `4 → 3 → 2 → 1`.
The deepest call returns 1. The remaining calls then compute `2 + 1 = 3`, `3 + 3 = 6`, and `4 + 6 = 10`, in order.
At the deepest point, all four function calls are still active.
3. Both functions perform a number of loop iterations or calls proportional to $n$, so both have a time complexity of $O(n)$.
Their space complexities differ. The iterative version uses only a constant number of variables, so its space complexity is $O(1)$.
In the recursive version, earlier calls must wait for a result before returning, so the call stack holds up to $n$ calls at the same time.
Its space complexity is $O(n)$.
3. Both functions perform a number of iterations or calls proportional to $n$, so both have time complexity $O(n)$.
Their space complexities differ: the iterative version uses only a constant number of variables, giving $O(1)$.
In the recursive version, earlier calls must wait for their results until the base case is reached. The call stack therefore holds up to $n$ calls at once,
giving space complexity $O(n)$.
When analyzing space complexity, remember to include the space used by recursive calls as well as the variables written in the code.
When analyzing space complexity, consider the space used by recursive calls as well as the variables in the code.
### Time Complexity of Three Code Fragments
### Time complexity of three code snippets
Each of the following code fragments takes a positive integer $n$ as input. Order them from lowest to highest time complexity, and give the complexity of each one.
Each of the following three code snippets takes a positive integer $n$ as input. Rank them from lowest to highest time complexity, and state each complexity.
```src
[file]{complexity_exercises}-[class]{}-[func]{linear_loop}
```
??? success "Answer"
??? success "Reference answer"
From lowest to highest, the order is Fragment 3 with $O(\log n)$, Fragment 1 with $O(n)$, and Fragment 2 with $O(n^2)$.
Fragment 3 halves $n$ in each iteration, so it runs about $\log_2 n$ times.
The loop in Fragment 1 runs exactly $n$ times. The inner loop in Fragment 2 runs
$n,n-1,\dots,1$ times, for a total of $n(n+1)/2$, so its time complexity is quadratic.
From lowest to highest: snippet 3, $O(\log n)$; snippet 1, $O(n)$; snippet 2, $O(n^2)$.
Snippet 3 halves $n$ at each iteration, so it runs approximately $\log_2 n$ times.
Snippet 1 runs its loop exactly $n$ times. In snippet 2, the inner loop runs
$n,n-1,\dots,1$ times in successive iterations, for a total of $n(n+1)/2$, giving quadratic time complexity.
### Which Reversal Uses Less Space?
### Which reversal method uses less space?
There are two ways to reverse all the elements in the array `nums`:
There are two ways to reverse all the elements in an array `nums`:
<!-- numbered-subquestions -->
1. Create a new array `res` of the same length, copy the elements into it in reverse order, and return it.
2. Move two indices `i` and `j` inward from the beginning and end, swapping `nums[i]` and `nums[j]` at each step.
1. Create an array `res` of the same length, copy the elements into it in reverse order, and return it.
2. Move two indices, `i` and `j`, inward from the beginning and end, swapping `nums[i]` with `nums[j]` in pairs.
What is the space complexity of each approach? Which one is an "in-place" operation?
What is the space complexity of each approach? Which operation is in-place?
??? success "Answer"
??? success "Reference answer"
1. This approach needs an auxiliary array with the same length as the input, so its space complexity is $O(n)$.
1. An auxiliary array as long as the input is needed, giving space complexity $O(n)$.
2. This approach uses only two index variables,
so its space complexity is $O(1)$. It is an in-place operation.
2. Only two index variables are used,
giving space complexity $O(1)$. This is an in-place operation.
Note that an in-place reversal changes the input array,
so it should be preferred only when modifying the input is allowed. If the original array must be kept, the copying cost of the first approach is unavoidable.
Keep in mind that in-place reversal modifies the input array.
Prefer it only when modifying the input is allowed. If the original array must be preserved, the copying cost of approach 1 is unavoidable.
## Programming Exercises
## Programming exercises
### Fibonacci Number
### Fibonacci number
The Fibonacci sequence is defined by $F(0)=0$, $F(1)=1$, and, for $n\ge2$,
The Fibonacci sequence satisfies $F(0)=0$, $F(1)=1$, and, for $n\ge2$,
$F(n)=F(n-1)+F(n-2)$.
Given a non-negative integer `n`, use a loop to calculate and return $F(n)$. Do not use recursion.
Given a nonnegative integer `n`, use a loop to compute and return $F(n)$ without recursion.
??? tip "Hints"
1. Handle the cases where n is 0 or 1 separately
2. Only the previous two terms are needed to calculate the next term; there is no need to store the entire sequence
3. When updating the two variables, take care not to overwrite an old value before it is used
1. Handle n equal to 0 or 1 separately first.
2. Computing the next term requires only the previous two terms; there is no need to store the entire sequence.
3. When updating the two variables, take care not to overwrite an old value before you have finished using it.
[LeetCode](https://leetcode.com/problems/fibonacci-number/){ .rounded-button .exercise-button target="_blank" rel="noopener noreferrer" }

View File

@@ -1,9 +1,9 @@
# Complexity Analysis
# Complexity analysis
![Complexity analysis](../assets/covers/chapter_complexity_analysis.jpg)
!!! abstract
Complexity analysis is like a space-time guide in the vast universe of algorithms.
It leads us to explore deeply within the two dimensions of time and space, seeking more elegant solutions.
Complexity analysis is our guide to time and space in the vast universe of algorithms.
It leads us to explore these two dimensions in depth as we search for more elegant solutions.

View File

@@ -1,194 +1,194 @@
# Iteration and Recursion
# Iteration and recursion
In algorithms, repeatedly executing a task is very common and closely related to complexity analysis. Therefore, before introducing time complexity and space complexity, let's first understand how to implement repeated task execution in programs, namely the two basic program control structures: iteration and recursion.
Algorithms often repeat tasks, and repetition is closely tied to complexity analysis. Before introducing time and space complexity, let's examine two basic ways to repeat work in a program: iteration and recursion.
## Iteration
<u>Iteration</u> is a control structure for repeatedly executing a task. In iteration, a program repeatedly executes a segment of code under certain conditions until those conditions are no longer satisfied.
<u>Iteration</u> is a control structure for repeating a task. A program repeatedly executes a block of code while a condition holds, stopping when it no longer does.
### For Loop
### For loops
The `for` loop is one of the most common forms of iteration, **suitable for use when the number of iterations is known in advance**.
A `for` loop is one of the most common forms of iteration, **especially when the number of iterations is known in advance**.
The following function implements the summation $1 + 2 + \dots + n$ using a `for` loop, with the result stored in the variable `res`. Note that in Python, `range(a, b)` corresponds to a "left-closed, right-open" interval, with the traversal range being $a, a + 1, \dots, b-1$:
The following function uses a `for` loop to compute $1 + 2 + \dots + n$, storing the result in `res`. In Python, `range(a, b)` includes the left endpoint but excludes the right, so it visits $a, a + 1, \dots, b-1$:
```src
[file]{iteration}-[class]{}-[func]{for_loop}
```
The figure below shows the flowchart of this summation function.
The figure below is a flowchart of this summation function.
![Flowchart of the summation function](iteration_and_recursion.assets/iteration.png)
The number of operations in this summation function is proportional to the input data size $n$, or has a "linear relationship". In fact, **time complexity describes precisely this "linear relationship"**. Related content will be introduced in detail in the next section.
Its operation count is proportional to the input size $n$: the relationship is linear. **Time complexity describes this relationship**, as the next section will explain.
### While Loop
### While loops
Similar to the `for` loop, the `while` loop is also a method for implementing iteration. In a `while` loop, the program first checks the condition in each round; if the condition is true, it continues execution, otherwise it ends the loop.
Like `for`, a `while` loop implements iteration. Before each iteration, it checks a condition: if true, execution continues; otherwise, the loop ends.
Below we use a `while` loop to implement the summation $1 + 2 + \dots + n$:
Here is a `while` loop computing $1 + 2 + \dots + n$:
```src
[file]{iteration}-[class]{}-[func]{while_loop}
```
**The `while` loop has greater flexibility than the `for` loop**. In a `while` loop, we can freely design the initialization and update steps of the condition variable.
**A `while` loop offers more flexibility than a `for` loop** in how its condition variables are initialized and updated.
For example, in the following code, the condition variable $i$ is updated twice per round, which is not convenient to implement using a `for` loop:
For example, the following code updates the condition variable $i$ twice per iteration, which is less convenient to express with a `for` loop:
```src
[file]{iteration}-[class]{}-[func]{while_loop_ii}
```
Overall, **`for` loops have more compact code, while `while` loops are more flexible**; both can implement iterative structures. The choice of which to use should be determined based on the requirements of the specific problem.
In general, **`for` loops are more compact, while `while` loops are more flexible**. Both implement iteration; choose according to the problem's needs.
### Nested Loops
### Nested loops
We can nest one loop structure inside another. Below is an example using `for` loops:
We can place one loop inside another, as in the following `for`-loop example:
```src
[file]{iteration}-[class]{}-[func]{nested_for_loop}
```
The figure below shows the flowchart of this nested loop.
The figure below shows the nested loop's flowchart.
![Flowchart of nested loops](iteration_and_recursion.assets/nested_iteration.png)
In this case, the number of operations of the function is proportional to $n^2$, or the algorithm's running time has a "quadratic relationship" with the input data size $n$.
Here, the operation count is proportional to $n^2$: runtime has a quadratic relationship with input size $n$.
We can continue adding nested loops, where each additional level of nesting can be viewed as an increase in dimensionality, raising the time complexity to a "cubic relationship", a "quartic relationship", and so on.
Adding further nesting increases the dimension each time, producing cubic, fourth-power, and higher-order time complexity.
## Recursion
<u>Recursion</u> is an algorithmic strategy that solves problems by having a function call itself. It mainly consists of two phases.
<u>Recursion</u> is an algorithmic strategy in which a function calls itself to solve a problem. It has two main phases.
1. **Descend**: The program continuously calls itself deeper, usually passing in smaller or more simplified parameters, until reaching a "termination condition".
2. **Ascend**: After triggering the "termination condition", the program returns layer by layer from the deepest recursive function, aggregating the result of each layer.
1. **Descent**: The function calls itself more deeply, usually with smaller or simpler arguments, until a base case is reached.
2. **Return**: Once the base case is reached, calls return from the deepest level upward, combining results along the way.
From an implementation perspective, recursive code mainly consists of three elements.
In implementation, recursive code has three main elements.
1. **Termination condition**: Used to determine when to switch from "descending" to "ascending".
2. **Recursive call**: Corresponds to "descending", where the function calls itself, usually with smaller or more simplified parameters.
3. **Return result**: Corresponds to "ascending", returning the result of the current recursion level to the previous layer.
1. **Base case**: Determines when descent stops and returning begins.
2. **Recursive call**: The function calls itself, usually with smaller or simpler arguments.
3. **Returned result**: The current level returns its result to the previous level.
Observe the following code. We only need to call the function `recur(n)` to complete the calculation of $1 + 2 + \dots + n$:
In the following code, calling `recur(n)` computes $1 + 2 + \dots + n$:
```src
[file]{recursion}-[class]{}-[func]{recur}
```
The figure below shows the recursive process of this function.
The figure below illustrates the recursive process.
![Recursive process of the summation function](iteration_and_recursion.assets/recursion_sum.png)
Although from a computational perspective, iteration and recursion can achieve the same results, **they represent two completely different paradigms for thinking about and solving problems**.
Iteration and recursion can produce the same answer, **but represent two different ways of thinking about and solving a problem**.
- **Iteration**: Solves problems "bottom-up". Starting from the most basic steps, these steps are then repeatedly executed or accumulated until the task is complete.
- **Recursion**: Solves problems "top-down". The original problem is decomposed into smaller subproblems that have the same form as the original problem. These subproblems continue to be decomposed into even smaller subproblems until reaching the base case (where the solution is known).
- **Iteration** works bottom up, starting with basic steps and repeatedly performing or accumulating them until the task is complete.
- **Recursion** works top down, dividing the original problem into smaller subproblems of the same form, then repeating the division until reaching base cases with known solutions.
Taking the above summation function as an example, let the problem be $f(n) = 1 + 2 + \dots + n$.
For the summation example, let $f(n) = 1 + 2 + \dots + n$.
- **Iteration**: Simulates the summation process in a loop, traversing from $1$ to $n$, performing the summation operation in each round to obtain $f(n)$.
- **Recursion**: Decomposes the problem into the subproblem $f(n) = n + f(n-1)$, continuously decomposing (recursively) until terminating at the base case $f(1) = 1$.
- **Iteration**: Loop from $1$ to $n$, accumulating the sum at each step to obtain $f(n)$.
- **Recursion**: Decompose the problem as $f(n) = n + f(n-1)$ and keep doing so recursively until the base case $f(1) = 1$.
### Call Stack
### The call stack
Each time a recursive function calls itself, the system allocates memory for the newly invoked function to store local variables, call addresses, and other information. This leads to two consequences.
Each time a recursive function calls itself, the system allocates memory for the new call's local variables, return address, and other information. This has two consequences.
- The function's context data is stored in a memory area called "stack frame space", which is not released until the function returns. Therefore, **recursion usually consumes more memory space than iteration**.
- Recursive function calls incur additional overhead. **Therefore, recursion is usually less time-efficient than loops**.
- The call's context is stored in a stack frame until it returns. **Recursion therefore usually uses more memory than iteration**.
- Each recursive call adds overhead. **Recursion is therefore usually slower than a loop**.
As shown in the figure below, before the termination condition is triggered, there are $n$ unreturned recursive functions existing simultaneously, with a **recursion depth of $n$**.
As shown in the figure below, before the base case is reached, $n$ recursive calls remain active at once: **the recursion depth is $n$**.
![Recursion call depth](iteration_and_recursion.assets/recursion_sum_depth.png)
![Depth of recursive calls](iteration_and_recursion.assets/recursion_sum_depth.png)
In practice, the recursion depth allowed by programming languages is usually limited, and excessively deep recursion may lead to stack overflow errors.
Programming languages usually limit recursion depth, and excessively deep recursion may cause a stack overflow.
### Tail Recursion
### Tail recursion
Interestingly, **if a function makes the recursive call as the very last step before returning**, the compiler or interpreter may optimize it so that its space efficiency is comparable to iteration. This case is called <u>tail recursion</u>.
Interestingly, **if the recursive call is the last operation before a function returns**, a compiler or interpreter can optimize it to use as little space as iteration. This is called <u>tail recursion</u>.
- **Regular recursion**: When a function returns to the previous level, it needs to continue executing code, so the system needs to save the context of the previous layer's call.
- **Tail recursion**: The recursive call is the last operation before the function returns, meaning that after returning to the previous level, there is no need to continue executing other operations, so the system does not need to save the context of the previous layer's function.
- **Ordinary recursion**: After a call returns, its caller must continue executing code, so the caller's context must be preserved.
- **Tail recursion**: Nothing remains to be done after the recursive call returns, so the caller's context need not be retained.
Taking the calculation of $1 + 2 + \dots + n$ as an example, we can set the result variable `res` as a function parameter to implement tail recursion:
For $1 + 2 + \dots + n$, passing the accumulated result `res` as a parameter gives a tail-recursive solution:
```src
[file]{recursion}-[class]{}-[func]{tail_recur}
```
The execution process of tail recursion is shown in the figure below. Comparing regular recursion and tail recursion, the summation operation is performed at different points.
The figure below illustrates tail recursion. Ordinary and tail recursion perform their additions at different points.
- **Regular recursion**: The summation operation is performed during the "ascending" process, requiring an additional summation operation after each layer returns.
- **Tail recursion**: The summation operation is performed during the "descending" process; the "ascending" process only needs to return layer by layer.
- **Ordinary recursion**: Addition occurs during the return phase, after each deeper call returns.
- **Tail recursion**: Addition occurs during descent; the return phase simply returns through the levels.
![Tail recursion process](iteration_and_recursion.assets/tail_recursion_sum.png)
![Tail-recursive summation](iteration_and_recursion.assets/tail_recursion_sum.png)
!!! tip
Please note that many compilers or interpreters do not support tail recursion optimization. For example, Python does not support tail recursion optimization by default, so even if a function is in tail recursive form, it may still encounter stack overflow issues.
Many compilers and interpreters do not support tail-recursion optimization. Python, for example, does not optimize it by default, so even a tail-recursive function can run into a stack overflow.
### Recursion Tree
### Recursion trees
When dealing with algorithmic problems related to "divide and conquer", recursion often provides a more intuitive approach and more readable code than iteration. Taking the "Fibonacci sequence" as an example.
For divide-and-conquer problems, recursion often provides a more intuitive approach and more readable code than iteration. Consider the Fibonacci sequence.
!!! question
Given a Fibonacci sequence $0, 1, 1, 2, 3, 5, 8, 13, \dots$, find the $n$-th number in the sequence.
Given the Fibonacci sequence $0, 1, 1, 2, 3, 5, 8, 13, \dots$, find its $n$-th number.
Let the $n$-th number of the Fibonacci sequence be $f(n)$. Two conclusions can be easily obtained.
Let $f(n)$ be its $n$-th number. Two facts follow.
- The first two numbers of the sequence are $f(1) = 0$ and $f(2) = 1$.
- Each number in the sequence is the sum of the previous two numbers, i.e., $f(n) = f(n - 1) + f(n - 2)$.
- The first two numbers are $f(1) = 0$ and $f(2) = 1$.
- Every later number is the sum of the two preceding numbers: $f(n) = f(n - 1) + f(n - 2)$.
Following the recurrence relation to make recursive calls, with the first two numbers as termination conditions, we can write the recursive code. Calling `fib(n)` will give us the $n$-th number of the Fibonacci sequence:
Use the recurrence for recursive calls and the first two numbers as base cases. Calling `fib(n)` then returns the $n$-th Fibonacci number:
```src
[file]{recursion}-[class]{}-[func]{fib}
```
Observing the above code, we make two recursive calls within the function, **meaning that one call produces two call branches**. As shown in the figure below, this repeated recursive calling eventually produces a <u>recursion tree</u> with $n$ levels.
The function makes two recursive calls, **so each call creates two branches**. Continuing this process produces a <u>recursion tree</u> with $n$ levels, as shown in the figure below.
![Recursion tree of the Fibonacci sequence](iteration_and_recursion.assets/recursion_tree.png)
![Recursion tree for the Fibonacci sequence](iteration_and_recursion.assets/recursion_tree.png)
Fundamentally, recursion embodies the paradigm of "decomposing a problem into smaller subproblems", and this divide-and-conquer strategy is crucial.
Recursion embodies the idea of breaking a problem into smaller subproblems, a crucial divide-and-conquer strategy.
- From an algorithmic perspective, many important algorithmic strategies such as searching, sorting, backtracking, divide and conquer, and dynamic programming directly or indirectly apply this way of thinking.
- From a data structure perspective, recursion is naturally suited for handling problems related to linked lists, trees, and graphs, because they are well-suited for analysis using divide-and-conquer thinking.
- In algorithms, searching, sorting, backtracking, divide and conquer, dynamic programming, and many other techniques use this idea directly or indirectly.
- In data structures, recursion naturally handles linked lists, trees, and graphs because divide-and-conquer reasoning suits them well.
## Comparison of the Two
## Comparing iteration and recursion
Summarizing the above content, as shown in the table below, iteration and recursion differ in implementation, performance, and applicability.
The table below summarizes their differences in implementation, performance, and suitability.
<p align="center"> Table <id> &nbsp; Comparison of iteration and recursion characteristics </p>
<p align="center"> Table <id> &nbsp; Comparing iteration and recursion </p>
| | Iteration | Recursion |
| -------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| Implementation | Loop structure | Function calls itself |
| Time efficiency | Generally more efficient, no function call overhead | Each function call incurs overhead |
| Memory usage | Usually uses a fixed amount of memory space | Accumulated function calls may use a large amount of stack frame space |
| Suitable problems | Suitable for simple loop tasks, with intuitive and readable code | Suitable for subproblem decomposition, such as trees, graphs, divide and conquer, backtracking, etc., with concise and clear code structure |
| | Iteration | Recursion |
| -------- | -------------------------------------- | ------------------------------------------------------------ |
| Implementation | Loops | A function calls itself |
| Time efficiency | Usually high, with no function-call overhead | Each call adds overhead |
| Memory use | Usually a fixed amount of memory | Accumulated calls may require many stack frames |
| Suitable problems | Simple repetitive tasks, with straightforward, readable code | Subproblem decomposition, including trees, graphs, divide and conquer, and backtracking; concise, clear structure |
!!! tip
If you find the following content difficult to understand, you can review it after reading the "Stack" chapter.
If the following discussion feels difficult, return to it after reading the section on stacks.
What is the intrinsic relationship between iteration and recursion? Taking the above recursive function as an example, the summation operation is performed during the "ascending" phase of recursion. This means that the function called first actually completes its summation operation last, **and this working mechanism is similar to the "last-in, first-out" principle of stacks**.
How are iteration and recursion connected? In the summation example, additions occur during the return phase. The first function called is the last to finish its addition, **matching a stack's last-in, first-out behavior**.
In fact, recursive terminology such as "call stack" and "stack frame space" already hints at the close relationship between recursion and stacks.
The terms call stack and stack frame already suggest this close relationship.
1. **Descend**: When a function is called, the system allocates a new stack frame on the "call stack" for that function to store the function's local variables, parameters, return address, and other data.
2. **Ascend**: When the function completes execution and returns, the corresponding stack frame is removed from the "call stack", restoring the execution environment of the previous function.
1. **Descent**: A function call adds a new stack frame to the call stack, holding local variables, parameters, the return address, and other data.
2. **Return**: When the function finishes, its frame is removed, restoring the caller's execution context.
Therefore, **we can use an explicit stack to simulate the behavior of the call stack**, thus transforming recursion into iterative form:
Thus, **an explicit stack can simulate the call stack**, converting recursion into iteration:
```src
[file]{recursion}-[class]{}-[func]{for_loop_recur}
```
Observing the above code, when recursion is transformed into iteration, the code becomes more complex. Although iteration and recursion can be converted into each other in many cases, it may not be worthwhile to do so for the following two reasons.
The resulting iterative code is more complicated. Although iteration and recursion can often be converted into each other, doing so is not always worthwhile.
- The transformed code may be more difficult to understand and less readable.
- For some complex problems, simulating the behavior of the system call stack can be very difficult.
- The converted code may be harder to understand and less readable.
- Simulating the call stack can be very difficult for complex problems.
In summary, **choosing between iteration and recursion depends on the nature of the specific problem**. In programming practice, it is crucial to weigh the pros and cons of both and choose the appropriate method based on the context.
**The choice between iteration and recursion depends on the problem**. In practice, weigh their strengths and weaknesses and choose the approach that fits the situation.

View File

@@ -1,49 +1,49 @@
# Algorithm Efficiency Evaluation
# Evaluating algorithm efficiency
In algorithm design, we pursue the following two levels of objectives sequentially.
Algorithm design pursues two goals in sequence.
1. **Finding a solution to the problem**: The algorithm must reliably obtain the correct solution within the specified input range.
2. **Seeking the optimal solution**: Multiple solutions may exist for the same problem, and we hope to find an algorithm that is as efficient as possible.
1. **Find a solution**: The algorithm must reliably produce correct results across the specified input range.
2. **Find the best solution**: When several approaches exist, we want the most efficient algorithm possible.
In other words, under the premise of being able to solve the problem, algorithm efficiency has become the primary evaluation criterion for measuring the quality of algorithms. It includes the following two dimensions.
Once correctness is established, efficiency becomes a primary measure of an algorithm's quality. It has two dimensions.
- **Time efficiency**: The length of time the algorithm runs.
- **Space efficiency**: The size of memory space the algorithm occupies.
- **Time efficiency**: How long the algorithm takes to run.
- **Space efficiency**: How much memory it uses.
In short, **our goal is to design data structures and algorithms that are "both fast and memory-efficient"**. Effectively evaluating algorithm efficiency is crucial, because only in this way can we compare various algorithms and guide the algorithm design and optimization process.
**Our goal is to design data structures and algorithms that are both fast and economical with memory**. Evaluating efficiency effectively lets us compare algorithms and guide their design and optimization.
Efficiency evaluation methods are mainly divided into two types: actual testing and theoretical estimation.
There are two main evaluation methods: practical testing and theoretical estimation.
## Actual Testing
## Practical testing
Suppose we now have algorithm `A` and algorithm `B`, both of which can solve the same problem, and we need to compare their efficiency. The most direct method is to run them on a computer and measure their running time and memory usage. This evaluation approach can reflect real-world behavior, but it also has considerable limitations.
Suppose algorithms `A` and `B` solve the same problem. The most direct comparison is to run both on a computer and measure runtime and memory use. This reflects actual behavior, but has substantial limitations.
On one hand, **it is difficult to eliminate interference factors from the testing environment**. Hardware configuration affects algorithmic performance. For example, if an algorithm has a high degree of parallelism, it is more suitable for running on multi-core CPUs; if an algorithm performs memory-intensive operations, it will benefit more from high-performance memory. In other words, the test results of an algorithm on different machines may be inconsistent. This means we need to test on various machines and calculate average efficiency, which is impractical.
First, **it is difficult to remove the influence of the test environment**. Hardware affects performance: a highly parallel algorithm benefits from a multicore CPU, while a memory-intensive algorithm benefits from faster RAM. Results may differ across machines, so a fair average would require testing on many kinds of hardware, which is impractical.
On the other hand, **conducting complete testing is very resource-intensive**. As the input data volume changes, the algorithm will exhibit different efficiencies. For example, when the input data volume is small, the running time of algorithm `A` is shorter than algorithm `B`; but when the input data volume is large, the test results may be exactly the opposite. Therefore, to obtain convincing conclusions, we need to test input data of various scales, which requires a large amount of computational resources.
Second, **comprehensive testing consumes substantial resources**. Efficiency changes with input size. Algorithm `A` may be faster than `B` for small inputs, while the reverse holds for large inputs. A convincing conclusion requires testing many input sizes, consuming considerable computing resources.
## Theoretical Estimation
## Theoretical estimation
Since actual testing has considerable limitations, we can consider evaluating algorithm efficiency through theoretical calculation. This estimation method is called <u>asymptotic complexity analysis</u>, or <u>complexity analysis</u> for short.
Given these limitations, we can estimate efficiency through calculation alone. This is called <u>asymptotic complexity analysis</u>, or simply <u>complexity analysis</u>.
Complexity analysis can reflect the relationship between the time and space resources required for algorithm execution and the input data scale. **It describes the growth trend of the time and space required for algorithm execution as the input data scale increases**. This definition is a bit cumbersome, so we can break it down into three key points to understand.
Complexity analysis relates an algorithm's time and space requirements to its input size. **It describes how runtime and memory use grow as the input gets larger**. We can unpack this definition into three points.
- "Time and space resources" correspond to <u>time complexity</u> and <u>space complexity</u>, respectively.
- "As the input data scale increases" means that complexity reflects the relationship between algorithm running efficiency and input data scale.
- "Growth trend of time and space" indicates that complexity analysis focuses not on the specific values of running time or occupied space, but on how "fast" time or space grows.
- Time and space resources correspond to <u>time complexity</u> and <u>space complexity</u>.
- Growth in input size means complexity relates efficiency to the amount of input data.
- Growth trends mean we study how quickly time or space increases, rather than its exact value.
**Complexity analysis overcomes the drawbacks of the actual testing method**, reflected in the following aspects.
**Complexity analysis overcomes limitations of practical testing** in several ways.
- It does not need to actually run the code, making it more environmentally friendly and energy-efficient.
- It is independent of the testing environment, and the analysis results are applicable to all running platforms.
- It can reflect algorithm efficiency at different data volumes, especially algorithm performance at large data volumes.
- It does not require running code, saving energy and computing resources.
- It is independent of the test environment, so its conclusions apply across platforms.
- It reveals efficiency at different input sizes, especially for large inputs.
!!! tip
If you are still confused about the concept of complexity, don't worry—we will introduce it in detail in subsequent chapters.
If complexity still feels unclear, do not worry. The following sections will explain it in detail.
Complexity analysis provides us with a "ruler" for evaluating algorithm efficiency, allowing us to measure the time and space resources required to execute a certain algorithm and compare the efficiency between different algorithms.
Complexity analysis gives us a yardstick for evaluating the time and space an algorithm needs and comparing different algorithms.
Complexity is a mathematical concept that may feel abstract and challenging for beginners. From this perspective, complexity analysis may not be the most suitable topic to introduce first. However, when we discuss the characteristics of a certain data structure or algorithm, it is difficult to avoid analyzing its running speed and space usage.
As a mathematical concept, complexity can be abstract and challenging for beginners. This makes it a difficult topic to introduce first. Yet discussing a data structure or algorithm's properties inevitably involves runtime and memory use.
In summary, it is recommended that before diving deep into data structures and algorithms, **you first establish a preliminary understanding of complexity analysis so that you can analyze the complexity of simple algorithms**.
Before studying data structures and algorithms in depth, **build an initial understanding of complexity analysis so that you can analyze simple algorithms**.

View File

@@ -1,28 +1,28 @@
# Space Complexity
# Space complexity
<u>Space complexity</u> measures the growth trend of memory space occupied by an algorithm as the data size increases. This concept is very similar to time complexity, except that "running time" is replaced with "occupied memory space".
<u>Space complexity</u> measures how an algorithm's memory use grows as the input gets larger. It is much like time complexity, with memory usage replacing runtime.
## Algorithm-Related Space
## Space used by an algorithm
The memory space used by an algorithm during execution mainly includes the following types.
The memory an algorithm uses during execution falls into these main categories.
- **Input space**: Used to store the input data of the algorithm.
- **Temporary space**: Used to store variables, objects, function contexts, and other data during the algorithm's execution.
- **Output space**: Used to store the output data of the algorithm.
- **Input space**: Stores the input data.
- **Temporary space**: Stores variables, objects, function contexts, and other working data.
- **Output space**: Stores the output data.
In general, the scope of space complexity statistics is "temporary space" plus "output space".
Space complexity generally counts temporary space plus output space.
Temporary space can be further divided into three parts.
Temporary space can be divided further into three parts.
- **Temporary data**: Used to save various constants, variables, objects, etc., during the algorithm's execution.
- **Stack frame space**: Used to save the context data of called functions. The system creates a stack frame at the top of the stack each time a function is called, and the stack frame space is released after the function returns.
- **Instruction space**: Used to save compiled program instructions, which are usually ignored in actual statistics.
- **Temporary data**: Constants, variables, objects, and other data used during execution.
- **Stack frames**: Context data for function calls. Each call creates a frame at the top of the stack, which is released when the function returns.
- **Instruction space**: Compiled program instructions, usually ignored in the analysis.
When analyzing the space complexity of a program, **we usually consider three parts: temporary data, stack frame space, and output data**, as shown in the following figure.
**We usually count temporary data, stack frames, and output data** when analyzing space complexity, as shown in the figure below.
![Algorithm-related space](space_complexity.assets/space_types.png)
![Space used by an algorithm](space_complexity.assets/space_types.png)
The related code is as follows:
The corresponding code is:
=== "Python"
@@ -39,10 +39,10 @@ The related code is as follows:
return 0
def algorithm(n) -> int: # Input data
A = 0 # Temporary data (constant, usually represented by uppercase letters)
A = 0 # Temporary data (constant, conventionally named in uppercase)
b = 0 # Temporary data (variable)
node = Node(0) # Temporary data (object)
c = function() # Stack frame space (function call)
c = function() # Stack frame (function call)
return A + b + c # Output data
```
@@ -66,7 +66,7 @@ The related code is as follows:
const int a = 0; // Temporary data (constant)
int b = 0; // Temporary data (variable)
Node* node = new Node(0); // Temporary data (object)
int c = func(); // Stack frame space (function call)
int c = func(); // Stack frame (function call)
return a + b + c; // Output data
}
```
@@ -80,18 +80,18 @@ The related code is as follows:
Node next;
Node(int x) { val = x; }
}
/* Function */
int function() {
// Perform some operations...
return 0;
}
int algorithm(int n) { // Input data
final int a = 0; // Temporary data (constant)
int b = 0; // Temporary data (variable)
Node node = new Node(0); // Temporary data (object)
int c = function(); // Stack frame space (function call)
int c = function(); // Stack frame (function call)
return a + b + c; // Output data
}
```
@@ -115,7 +115,7 @@ The related code is as follows:
const int a = 0; // Temporary data (constant)
int b = 0; // Temporary data (variable)
Node node = new(0); // Temporary data (object)
int c = Function(); // Stack frame space (function call)
int c = Function(); // Stack frame (function call)
return a + b + c; // Output data
}
```
@@ -129,11 +129,11 @@ The related code is as follows:
next *node
}
/* Create node structure */
/* Create a node structure */
func newNode(val int) *node {
return &node{val: val}
}
/* Function */
func function() int {
// Perform some operations...
@@ -144,7 +144,7 @@ The related code is as follows:
const a = 0 // Temporary data (constant)
b := 0 // Temporary data (variable)
newNode(0) // Temporary data (object)
c := function() // Stack frame space (function call)
c := function() // Stack frame (function call)
return a + b + c // Output data
}
```
@@ -172,7 +172,7 @@ The related code is as follows:
let a = 0 // Temporary data (constant)
var b = 0 // Temporary data (variable)
let node = Node(x: 0) // Temporary data (object)
let c = function() // Stack frame space (function call)
let c = function() // Stack frame (function call)
return a + b + c // Output data
}
```
@@ -200,7 +200,7 @@ The related code is as follows:
const a = 0; // Temporary data (constant)
let b = 0; // Temporary data (variable)
const node = new Node(0); // Temporary data (object)
const c = constFunc(); // Stack frame space (function call)
const c = constFunc(); // Stack frame (function call)
return a + b + c; // Output data
}
```
@@ -228,7 +228,7 @@ The related code is as follows:
const a = 0; // Temporary data (constant)
let b = 0; // Temporary data (variable)
const node = new Node(0); // Temporary data (object)
const c = constFunc(); // Stack frame space (function call)
const c = constFunc(); // Stack frame (function call)
return a + b + c; // Output data
}
```
@@ -253,7 +253,7 @@ The related code is as follows:
const int a = 0; // Temporary data (constant)
int b = 0; // Temporary data (variable)
Node node = Node(0); // Temporary data (object)
int c = function(); // Stack frame space (function call)
int c = function(); // Stack frame (function call)
return a + b + c; // Output data
}
```
@@ -263,14 +263,14 @@ The related code is as follows:
```rust title=""
use std::rc::Rc;
use std::cell::RefCell;
/* Structure */
struct Node {
val: i32,
next: Option<Rc<RefCell<Node>>>,
}
/* Create Node structure */
/* Create a Node structure */
impl Node {
fn new(val: i32) -> Self {
Self { val: val, next: None }
@@ -278,7 +278,7 @@ The related code is as follows:
}
/* Function */
fn function() -> i32 {
fn function() -> i32 {
// Perform some operations...
return 0;
}
@@ -287,7 +287,7 @@ The related code is as follows:
const a: i32 = 0; // Temporary data (constant)
let mut b = 0; // Temporary data (variable)
let node = Node::new(0); // Temporary data (object)
let c = function(); // Stack frame space (function call)
let c = function(); // Stack frame (function call)
return a + b + c; // Output data
}
```
@@ -304,7 +304,7 @@ The related code is as follows:
int algorithm(int n) { // Input data
const int a = 0; // Temporary data (constant)
int b = 0; // Temporary data (variable)
int c = func(); // Stack frame space (function call)
int c = func(); // Stack frame (function call)
return a + b + c; // Output data
}
```
@@ -327,7 +327,7 @@ The related code is as follows:
val a = 0 // Temporary data (constant)
var b = 0 // Temporary data (variable)
val node = Node(0) // Temporary data (object)
val c = function() // Stack frame space (function call)
val c = function() // Stack frame (function call)
return a + b + c // Output data
}
```
@@ -356,21 +356,21 @@ The related code is as follows:
a = 0 # Temporary data (constant)
b = 0 # Temporary data (variable)
node = Node.new(0) # Temporary data (object)
c = function # Stack frame space (function call)
c = function # Stack frame (function call)
a + b + c # Output data
end
```
## Calculation Method
## Deriving space complexity
The calculation method for space complexity is roughly the same as for time complexity, except that what we measure changes from the "number of operations" to the "amount of space used".
The approach is much like time complexity analysis, except that we count memory used rather than operations performed.
Unlike time complexity, **we usually only focus on the worst-case space complexity**. This is because memory space is a hard requirement, and we must ensure that sufficient memory space is reserved for all input data.
Unlike time complexity, **we usually focus only on worst-case space complexity**. Memory is a hard requirement: enough must be available for every valid input.
Observe the following code. Here, "worst case" in worst-case space complexity has two meanings.
In the following code, "worst case" has two meanings.
1. **Based on the worst input data**: When $n < 10$, the space complexity is $O(1)$; but when $n > 10$, the initialized array `nums` occupies $O(n)$ space, so the worst-case space complexity is $O(n)$.
2. **Based on the peak memory during algorithm execution**: For example, before executing the last line, the program occupies $O(1)$ space; when initializing the array `nums`, the program occupies $O(n)$ space, so the worst-case space complexity is $O(n)$.
1. **The worst input**: When $n < 10$, space complexity is $O(1)$. When $n > 10$, initializing `nums` requires $O(n)$ space, so worst-case space complexity is $O(n)$.
2. **Peak memory during execution**: Before the final line, the program uses $O(1)$ space. Initializing `nums` raises usage to $O(n)$, so worst-case space complexity is $O(n)$.
=== "Python"
@@ -523,7 +523,7 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
end
```
**In recursive functions, it is necessary to count the stack frame space**. Observe the following code:
**For recursive functions, remember to count stack frames**. Consider the following code:
=== "Python"
@@ -533,12 +533,12 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
return 0
def loop(n: int):
"""Loop has space complexity of O(1)"""
"""The loop uses O(1) space"""
for _ in range(n):
function()
def recur(n: int):
"""Recursion has space complexity of O(n)"""
"""The recursion uses O(n) space"""
if n == 1:
return
return recur(n - 1)
@@ -551,13 +551,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0;
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
void loop(int n) {
for (int i = 0; i < n; i++) {
func();
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
void recur(int n) {
if (n == 1) return;
recur(n - 1);
@@ -571,13 +571,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0;
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
void loop(int n) {
for (int i = 0; i < n; i++) {
function();
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
void recur(int n) {
if (n == 1) return;
recur(n - 1);
@@ -591,13 +591,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0;
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
void Loop(int n) {
for (int i = 0; i < n; i++) {
Function();
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
int Recur(int n) {
if (n == 1) return 1;
return Recur(n - 1);
@@ -611,15 +611,15 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
func loop(n int) {
for i := 0; i < n; i++ {
function()
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
func recur(n int) {
if n == 1 {
return
@@ -637,14 +637,14 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
return 0
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
func loop(n: Int) {
for _ in 0 ..< n {
function()
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
func recur(n: Int) {
if n == 1 {
return
@@ -660,13 +660,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0;
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
function loop(n) {
for (let i = 0; i < n; i++) {
constFunc();
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
function recur(n) {
if (n === 1) return;
return recur(n - 1);
@@ -680,13 +680,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0;
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
function loop(n: number): void {
for (let i = 0; i < n; i++) {
constFunc();
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
function recur(n: number): void {
if (n === 1) return;
return recur(n - 1);
@@ -700,13 +700,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0;
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
void loop(int n) {
for (int i = 0; i < n; i++) {
function();
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
void recur(int n) {
if (n == 1) return;
recur(n - 1);
@@ -720,13 +720,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0;
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
fn loop(n: i32) {
for i in 0..n {
function();
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
fn recur(n: i32) {
if n == 1 {
return;
@@ -742,13 +742,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0;
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
void loop(int n) {
for (int i = 0; i < n; i++) {
func();
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
void recur(int n) {
if (n == 1) return;
recur(n - 1);
@@ -762,13 +762,13 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
// Perform some operations
return 0
}
/* Loop has space complexity of O(1) */
/* The loop uses O(1) space */
fun loop(n: Int) {
for (i in 0..<n) {
function()
}
}
/* Recursion has space complexity of O(n) */
/* The recursion uses O(n) space */
fun recur(n: Int) {
if (n == 1) return
return recur(n - 1)
@@ -783,26 +783,26 @@ Observe the following code. Here, "worst case" in worst-case space complexity ha
0
end
### Loop has space complexity of O(1) ###
### The loop uses O(1) space ###
def loop(n)
(0...n).each { function }
end
### Recursion has space complexity of O(n) ###
### The recursion uses O(n) space ###
def recur(n)
return if n == 1
recur(n - 1)
end
```
The time complexity of both functions `loop()` and `recur()` is $O(n)$, but their space complexities are different.
Both `loop()` and `recur()` take $O(n)$ time, but their space complexities differ.
- The function `loop()` calls `function()` $n$ times in a loop. In each iteration, `function()` returns and releases its stack frame space, so the space complexity remains $O(1)$.
- The recursive function `recur()` has $n$ unreturned `recur()` instances existing simultaneously during execution, thus occupying $O(n)$ stack frame space.
- `loop()` calls `function()` $n$ times. Each call returns and releases its stack frame before the next iteration, so space complexity remains $O(1)$.
- During `recur()`, $n$ calls can remain active at once, using $O(n)$ space for stack frames.
## Common Types
## Common complexity classes
Let the input data size be $n$. The following figure shows common types of space complexity (arranged from low to high).
For input size $n$, the figure below shows common space complexities in increasing order of growth.
$$
\begin{aligned}
@@ -811,70 +811,70 @@ $$
\end{aligned}
$$
![Common types of space complexity](space_complexity.assets/space_complexity_common_types.png)
![Common space complexity classes](space_complexity.assets/space_complexity_common_types.png)
### Constant Order $O(1)$
### Constant space $O(1)$
Constant order is common for constants, variables, and objects whose number is independent of the input data size $n$.
Constant space commonly occurs when the number of constants, variables, and objects is independent of input size $n$.
It should be noted that memory occupied by initializing variables or calling functions in a loop is released when entering the next iteration, so it does not accumulate space, and the space complexity remains $O(1)$:
Memory for variables initialized or functions called within a loop is released by the next iteration, so it does not accumulate. Space complexity remains $O(1)$:
```src
[file]{space_complexity}-[class]{}-[func]{constant}
```
### Linear Order $O(n)$
### Linear space $O(n)$
Linear order is common in arrays, linked lists, stacks, queues, etc., where the number of elements is proportional to $n$:
Linear space commonly occurs in arrays, linked lists, stacks, and queues whose element counts are proportional to $n$:
```src
[file]{space_complexity}-[class]{}-[func]{linear}
```
As shown in the following figure, the recursion depth of this function is $n$, meaning that there are $n$ unreturned `linear_recur()` functions existing simultaneously, using $O(n)$ stack frame space:
As shown in the figure below, this function has recursion depth $n$, with $n$ active calls to `linear_recur()` at once, using $O(n)$ space for stack frames:
```src
[file]{space_complexity}-[class]{}-[func]{linear_recur}
```
![Linear order space complexity generated by recursive function](space_complexity.assets/space_complexity_recursive_linear.png)
![Linear space complexity from recursion](space_complexity.assets/space_complexity_recursive_linear.png)
### Quadratic Order $O(n^2)$
### Quadratic space $O(n^2)$
Quadratic order is common in matrices and graphs, where the number of elements is quadratically related to $n$:
Quadratic space commonly occurs in matrices and graphs whose element counts grow with the square of $n$:
```src
[file]{space_complexity}-[class]{}-[func]{quadratic}
```
As shown in the following figure, the recursion depth of this function is $n$, and an array is initialized in each recursive function with lengths of $n$, $n-1$, $\dots$, $2$, $1$, with an average length of $n / 2$, thus occupying $O(n^2)$ space overall:
As shown in the figure below, the recursion depth is $n$, and each call initializes an array. Their lengths are $n$, $n-1$, $\dots$, $2$, and $1$, averaging $n / 2$, so total space is $O(n^2)$:
```src
[file]{space_complexity}-[class]{}-[func]{quadratic_recur}
```
![Quadratic order space complexity generated by recursive function](space_complexity.assets/space_complexity_recursive_quadratic.png)
![Quadratic space complexity from recursion](space_complexity.assets/space_complexity_recursive_quadratic.png)
### Exponential Order $O(2^n)$
### Exponential space $O(2^n)$
Exponential order is common in binary trees. Observe the following figure: a "full binary tree" with $n$ levels has $2^n - 1$ nodes, occupying $O(2^n)$ space:
Exponential space commonly occurs in binary trees. In the figure below, a perfect binary tree with $n$ levels contains $2^n - 1$ nodes and uses $O(2^n)$ space:
```src
[file]{space_complexity}-[class]{}-[func]{build_tree}
```
![Exponential order space complexity generated by full binary tree](space_complexity.assets/space_complexity_exponential.png)
![Exponential space used by a perfect binary tree](space_complexity.assets/space_complexity_exponential.png)
### Logarithmic Order $O(\log n)$
### Logarithmic space $O(\log n)$
Logarithmic order is common in divide-and-conquer algorithms. For example, merge sort: given an input array of length $n$, each recursion divides the array in half from the midpoint, forming a recursion tree of height $\log n$, using $O(\log n)$ stack frame space.
Logarithmic space often appears in divide-and-conquer algorithms. For example, merge sort splits an array of length $n$ in half at each recursive step, producing a recursion tree of height $\log n$ and using $O(\log n)$ space for stack frames.
Another example is converting a number to a string. Given a positive integer $n$, it has $\lfloor \log_{10} n \rfloor + 1$ digits, i.e., the corresponding string length is $\lfloor \log_{10} n \rfloor + 1$, so the space complexity is $O(\log_{10} n + 1) = O(\log n)$.
Another example is converting a number to a string. A positive integer $n$ has $\lfloor \log_{10} n \rfloor + 1$ digits, giving a string of length $\lfloor \log_{10} n \rfloor + 1$. The space complexity is therefore $O(\log_{10} n + 1) = O(\log n)$.
## Trading Time for Space
## Balancing time and space
Ideally, we hope that both the time complexity and space complexity of an algorithm can reach optimal. However, in practice, optimizing both time complexity and space complexity simultaneously is usually very difficult.
Ideally, we would minimize both time and space complexity. In practice, optimizing both simultaneously is usually difficult.
**Reducing time complexity usually comes at the cost of increasing space complexity, and vice versa**. Sacrificing memory space to improve execution speed is called "trading space for time"; the reverse is called "trading time for space".
**Reducing time complexity often increases space complexity, and vice versa**. Using more memory to run faster is called trading space for time; accepting slower execution to use less memory is trading time for space.
The choice of which approach depends on which aspect we value more. In most cases, time is more precious than space, so "trading space for time" is usually the more common strategy. Of course, when the data volume is very large, controlling space complexity is also very important.
The choice depends on which resource matters more. Time is usually more valuable than space, so trading space for time is common. For very large datasets, however, keeping space complexity under control is also crucial.

View File

@@ -1,55 +1,55 @@
# Summary
### Key Review
### Key takeaways
**Algorithm Efficiency Assessment**
**Evaluating algorithm efficiency**
- Time efficiency and space efficiency are the two primary evaluation metrics for measuring algorithm performance.
- We can evaluate algorithm efficiency through actual testing, but it is difficult to eliminate the influence of the testing environment, and it consumes substantial computational resources.
- Complexity analysis can overcome the limitations of actual testing. Its results apply across running platforms, and it can reveal algorithm efficiency under different data scales.
- Time and space efficiency are the two main measures of algorithm quality.
- Practical testing measures efficiency, but cannot easily remove environmental effects and consumes substantial computing resources.
- Complexity analysis avoids those limitations, applies across platforms, and reveals efficiency at different input sizes.
**Time Complexity**
**Time complexity**
- Time complexity is used to measure the trend of algorithm runtime as data volume increases. It can effectively evaluate algorithm efficiency, but it may be less informative in certain situations, such as when the input data volume is small or when time complexities are identical, making it impossible to precisely compare algorithm efficiency.
- Worst-case time complexity is represented using Big $O$ notation, corresponding to the asymptotic upper bound of a function, reflecting the growth level of the number of operations $T(n)$ as $n$ approaches positive infinity.
- Deriving time complexity involves two steps: first, counting the number of operations, then determining the asymptotic upper bound.
- Common time complexities arranged from low to high include $O(1)$, $O(\log n)$, $O(n)$, $O(n \log n)$, $O(n^2)$, $O(2^n)$, and $O(n!)$.
- The time complexity of some algorithms is not fixed, but rather depends on the distribution of input data. Time complexity is divided into worst-case, best-case, and average-case time complexity. Best-case time complexity is rarely used because input data generally needs to satisfy strict conditions to achieve the best case.
- Average time complexity reflects the algorithm's runtime efficiency under random data input, and is closest to the algorithm's performance in practical applications. Calculating average time complexity requires analyzing the input data distribution and the resulting mathematical expectation.
- Time complexity describes how runtime grows with input size. It is useful for evaluating efficiency, but may not distinguish algorithms accurately for small inputs or equal complexity classes.
- Worst-case time complexity is expressed with big-$O$ notation, an asymptotic upper bound describing the growth of the operation count $T(n)$ as $n$ tends to positive infinity.
- Deriving time complexity takes two steps: count operations, then determine the asymptotic upper bound.
- Common complexities, from slower to faster growth, include $O(1)$, $O(\log n)$, $O(n)$, $O(n \log n)$, $O(n^2)$, $O(2^n)$, and $O(n!)$.
- Some algorithms' complexity depends on the input's arrangement. We distinguish worst-case, best-case, and average-case complexity. Best-case complexity is rarely used because reaching it generally requires strict input conditions.
- Average-case complexity describes performance on random inputs and is closest to typical practical behavior. Calculating it requires an input distribution and its mathematical expectation.
**Space Complexity**
**Space complexity**
- Space complexity serves a similar purpose to time complexity, used to measure the trend of algorithm memory usage as data volume increases.
- The memory space related to algorithm execution can be divided into input space, temporary space, and output space. Typically, input space is not included in space complexity calculations. Temporary space can be divided into temporary data, stack frame space, and instruction space, where stack frame space usually affects space complexity only in recursive functions.
- We typically only focus on worst-case space complexity, which is the space complexity of an algorithm under worst-case input data and worst-case runtime.
- Common space complexities arranged from low to high include $O(1)$, $O(\log n)$, $O(n)$, $O(n^2)$, and $O(2^n)$.
- Like time complexity, space complexity describes a growth trend: how memory usage increases with input size.
- Memory used during execution includes input, temporary, and output space. Input space is usually excluded from space complexity. Temporary space includes temporary data, stack frames, and instructions; stack frames usually affect complexity only in recursive functions.
- We usually consider worst-case space complexity, measuring memory under the worst input and at the moment of maximum usage.
- Common space complexities, from slower to faster growth, include $O(1)$, $O(\log n)$, $O(n)$, $O(n^2)$, and $O(2^n)$.
### Q & A
**Q**: Is the space complexity of tail recursion $O(1)$?
**Q**: Does tail recursion have $O(1)$ space complexity?
Theoretically, the space complexity of tail recursive functions can be optimized to $O(1)$. However, most programming languages (such as Java, Python, C++, Go, C#, etc.) do not support automatic tail recursion optimization, so the space complexity is generally considered to be $O(n)$.
In theory, tail recursion can be optimized to $O(1)$ space. However, most languages, including Java, Python, C++, Go, and C#, do not automatically optimize tail recursion, so its space complexity is usually treated as $O(n)$.
**Q**: What is the difference between the terms function and method?
**Q**: What is the difference between a function and a method?
A <u>function</u> can be executed independently, with all parameters passed explicitly. A <u>method</u> is associated with an object, is implicitly bound to the object that invokes it, and can operate on data contained in class instances.
A <u>function</u> can run independently, with all arguments passed explicitly. A <u>method</u> is associated with an object, receives that object implicitly when called, and can operate on the instance's data.
The following examples use several common programming languages for illustration.
Here are examples from several common languages.
- C is a procedural programming language without object-oriented concepts, so it only has functions. However, we can simulate object-oriented programming by creating structures (struct), and functions associated with structures are equivalent to methods in other programming languages.
- Java and C# are object-oriented programming languages where code blocks (methods) are typically part of a class. Static methods behave like functions because they are bound to the class and cannot access specific instance variables.
- C++ and Python support both procedural programming (functions) and object-oriented programming (methods).
- C is procedural and has no built-in object-oriented model, so it has functions only. We can simulate object-oriented programming with structures (`struct`); functions associated with a structure then act like methods in other languages.
- Java and C# are object-oriented, and executable blocks (methods) are usually part of a class. Static methods behave like functions: they belong to the class and cannot access a particular instance's variables directly.
- C++ and Python support both procedural programming with functions and object-oriented programming with methods.
**Q**: Does the diagram for "common space complexity types" reflect the absolute size of occupied space?
**Q**: Does the common space complexity chart show absolute memory usage?
No, the diagram shows space complexity, which reflects growth trends rather than the absolute size of occupied space.
No. It illustrates growth trends rather than absolute amounts of memory.
Assuming $n = 8$, you might find that the values of each curve do not correspond to the functions. This is because each curve contains a constant term used to compress the value range into a visually comfortable range.
For $n = 8$, the plotted values may not match the corresponding functions exactly. Each curve includes a constant term that adjusts it to a visually convenient range.
In practice, because we generally do not know the "constant-term" cost of each method, we usually cannot choose the optimal solution for cases like $n = 8$ based on complexity alone. But for $n = 8^5$, the choice is straightforward, because the growth trend already dominates.
In practice, these constant terms are usually unknown, so complexity alone cannot generally identify the best solution for $n = 8$. For $n = 8^5$, the choice is easier because growth rates dominate.
**Q**: Are there situations where algorithms are designed to sacrifice time (or space) based on actual use cases?
**Q**: Do algorithms sometimes trade time for space, or space for time, depending on the application?
In practical applications, most situations choose to sacrifice space for time. For example, with database indexes, we typically choose to build B+ trees or hash indexes, occupying substantial memory space in exchange for efficient queries of $O(\log n)$ or even $O(1)$.
Most practical applications trade space for time. Database indexes, for example, often use B+ trees or hash indexes, consuming substantial memory to achieve $O(\log n)$ or even $O(1)$ query time.
In scenarios where space resources are precious, time may be sacrificed for space. For example, in embedded development, device memory is precious, and engineers may forgo using hash tables and choose to use array sequential search to save memory usage, at the cost of slower searches.
When memory is scarce, the reverse tradeoff may be useful. In embedded development, an engineer might replace a hash table with sequential array search to save memory, accepting slower lookups.

File diff suppressed because it is too large Load Diff