π Day 1: Introduction to Algorithms & Big O Notation
π§ Concept
An algorithm is a step-by-step method to solve a problem β just like a cooking recipe. Computers follow these βrecipesβ to process data and make decisions.
Big O Notation is how we talk about how fast (or slow) an algorithm is. It tells us how the time or memory usage of your code grows with the input size n.
| Big O | Name | Example |
|---|---|---|
| O(1) | Constant Time | Access array element |
| O(n) | Linear Time | Loop through an array |
| O(nΒ²) | Quadratic Time | Nested loops |
| O(log n) | Logarithmic Time | Binary Search |
Think of O(n) as a chore that takes longer the more things you have β like checking every item in a list.
π¨βπ» Example
function findMax(arr: number[]): number {
let max = arr[0]; // O(1) - constant time
for (let i = 1; i < arr.length; i++) { // O(n) - linear time
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}Time Complexity: O(n)
We look at every element once.
π ASCII Trace
Input: [3, 8, 2, 9]
Start: max = 3
β 8 > 3 β max = 8
β 2 > 8 β β
β 9 > 8 β max = 9
Return 9π Homework
βοΈ Problem: Return the smallest element in an array.
function findMin(arr: number[]): number {
// your code here
}Example:
Input: [4, 2, 7, 1, 9]
Output: 1π Up Next:
Day 2: Big O Notation β O(1), O(n), O(nΒ²)