Skip to content

Commit 96df5ad

Browse files
committed
feat(algorithms): add big o notation
1 parent 9aee598 commit 96df5ad

File tree

8 files changed

+169
-1
lines changed

8 files changed

+169
-1
lines changed
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
# Algorthm Analysis
2+
3+
Before starting, lets thin about 3 problems:
4+
5+
For an array of size N, dont overthink. think and answer:
6+
7+
1. How many iterations a loop run to find a specific number inside an array? (naively)
8+
2. How many comparisons should I make to find two numbers in an array that sum a specific target? (naively)
9+
3. List all different shuffled arrays we can make? (naively) ex for n==3 123, 132, 213, 231, 312, 321
10+
11+
## How to measure an algorithm mathematically?
12+
13+
???+ example "find a number in a vector"
14+
15+
```c++
16+
int find(vector<int> v, int target) {
17+
// how many iterations?
18+
for (int i = 0; i < v.size(); i++) {
19+
// how many comparisons?
20+
if (v[i] == target) {
21+
return i;
22+
}
23+
}
24+
return -1;
25+
}
26+
```
27+
28+
???+ example "find two numbers sum in an array"
29+
30+
```c++
31+
vector<int> findsum2(vector<int> v, int target) {
32+
// how many outer loop iterations?
33+
for (int i = 0; i < v.size(); i++) {
34+
// how many inner loop iterations?
35+
for (int j = i+1; j < v.size(); j++) {
36+
// how many comparisons?
37+
if (v[i] + v[j] == target) {
38+
return {i, j};
39+
}
40+
}
41+
}
42+
return {-1, -1};
43+
}
44+
```
45+
Check it out on [leetcode](https://leetcode.com/problems/two-sum/description/). Can you solve it better?
46+
47+
???+ example "Print all pormutations of an array"
48+
49+
```c++
50+
void generatePermutations(std::vector<int>& vec, int index) {
51+
if (index == vec.size() - 1) {
52+
// Print the current permutation
53+
for (int num : vec) {
54+
std::cout << num << " ";
55+
}
56+
std::cout << std::endl;
57+
return;
58+
}
59+
60+
// how many swaps for every recursive call?
61+
for (int i = index; i < vec.size(); ++i) {
62+
// Swap the elements at indices index and i
63+
std::swap(vec[index], vec[i]);
64+
65+
// Recursively generate permutations for the rest of the vector
66+
// How deep this can go?
67+
generatePermutations(vec, index + 1);
68+
69+
// Backtrack: undo the swap to explore other possibilities
70+
std::swap(vec[index], vec[i]);
71+
}
72+
}
73+
```
74+
75+
Trying to be mathematicaly correct, the number of instructions the first one should be a function similar to this:
76+
77+
1. $f(n) = a*n + b$ : Where $b$ is the cost of what runs before and after the main loop and $a$ is the cost of the loop.
78+
2. $f(n) = a*n^2 + b*n + c$ : Where $c$ is the cost of what runs before and after the oter loop; $b$ is the cost of the outer loop; and $a$ is the cost of the inner loop;
79+
3. $f(n) = a*n!$ : Where $a$ is the cost of what runs before and after the outer loop;
80+
81+
To simplify, we remove the constants and the lower order terms:
82+
83+
1. $$ f(n) = n $$
84+
2. $$ f(n) = n^2 $$
85+
3. $$ f(n) = n! $$
86+
87+
## Difference between Big O vs Big Theta Θ vs Big Omega Ω Notations
88+
89+
<figure markdown>
90+
![img.png](img.png)
91+
<figcaption>Source: bigocheatsheet.com</figcaption>
92+
</figure>
93+
94+
### Big O
95+
96+
- Most used notation;
97+
- Upper bound;
98+
- "never worse than";
99+
- A real case cannot be faster than it;
100+
- $ 0 <= func <= O $
101+
102+
### Big Theta Θ
103+
104+
- Wrongly stated as average;
105+
- Theta is two-sided;
106+
- Tight bound between 2 constants of the same function
107+
- $ k1*Θ <= func <= k2*Θ $
108+
- When $N$ goes to infinite, it cannot be faster or slower than it;
109+
110+
### Honorable mentions
111+
112+
- **Big Omega Ω**: roughly the oposite of Big O;
113+
- **Little o** and **Little Omega (ω)**. The same concept from the big, but exclude the exact bound;
114+
115+
<figure markdown>
116+
![img_1.png](img_1.png)
117+
<figcaption>Source: freecodecamp.com</figcaption>
118+
</figure>
119+
120+
## Common Big Os
121+
122+
!!! note inline end "Log"
123+
124+
In computer science, when we say log, assume base 2, unless expressely stated;
125+
126+
| Big O | Name | Example |
127+
| --- | --- | --- |
128+
| O(1) | Constant | sum two numbers |
129+
| O(lg(n)) | Logarithmic | binary search |
130+
| O(n) | Linear | search in an array |
131+
| O(n*lg(n)) | Linearithmic | Merge Sort |
132+
| O(n^c) | Polinomial | match 2 sum |
133+
| O(c^n) | Exponential | brute force password of size n |
134+
| O(n!) | factorial | list all combinations |
135+
136+
### What is log?
137+
138+
Log is the inverse of exponentiation. It is the number of times you have to multiply a number by itself to get another number.
139+
140+
$$ log_b(b^x) = x $$
141+
142+
### What is binary search?
143+
144+
In a binary search, we commonly divide the array in half (base 2), and check if the target is in the left or right half. Then we repeat the process until we find the target or we run out of elements.
145+
146+
<figure markdown>
147+
![linear-vs-binary-search-worst-case.gif](linear-vs-binary-search-worst-case.gif)
148+
<figcaption>Source: mathwarehouse.com</figcaption>
149+
</figure>
150+
151+
## Common data structures and algorithms
152+
153+
<figure markdown>
154+
![img_2.png](img_2.png)
155+
<figcaption>Source: bigocheatsheet.com</figcaption>
156+
</figure>
157+
158+
<figure markdown>
159+
![img_3.png](img_3.png)
160+
<figcaption>Source: bigocheatsheet.com</figcaption>
161+
</figure>
162+
163+
## Common Issues and misconceptions
164+
165+
- Big O and Theta are commonly mixed;
166+
- Hashtables: it is commonly assumed that queries on <map> or <set> being O(1); std:: `<map>` and `<set>` are not the ideal implementation! [Watch this CppCon video](https://www.youtube.com/watch?v=ncHmEUmJZf4) for some deep level insights;
71.1 KB
Loading
14.2 KB
Loading
220 KB
Loading
125 KB
Loading
Loading

courses/algorithms/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ College dates for the Spring 2024 semester:
7777
---
7878

7979
- Week 2. 2024/01/22
80-
- Topic: Algorithm Analysis
80+
- Topic: [Algorithm Analysis](02-analysis/README.md)
8181

8282
- ### :material-code-array:{ .lg .middle } __Dynamic Data__
8383

mkdocs.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,8 @@ plugins:
259259
minify_html: true
260260
- exclude:
261261
glob:
262+
- .git/*
263+
- .github/*
262264
- node_modules/*
263265
- buildDocs/*
264266
- cmake-build-debug/*

0 commit comments

Comments
 (0)