02 EKH Algorithm Complexity Lecture
02 EKH Algorithm Complexity Lecture
What is an Algorithm?
Simple Example
Algorithm:
1. Start
2. Read number A
3. Read number B
4. Add A and B, store in SUM
5. Print SUM
6. End
Types of Algorithms
Complexity of Algorithms
• Time Complexity: How the running time grows with input size (Big O notation)
2. Time Complexity
It describes how the runtime of an algorithm increases with the size of the input, usually
represented by n.
O(1) Constant Accessing array element Same time regardless of input size
O(n) Linear Linear Search Time grows directly with input size
O(2ⁿ) Exponential Recursive Fibonacci Time doubles with each additional input
Examples
def get_first_element(arr):
return arr[0]
def find_max(arr):
max_val = arr[0]
max_val = val
return max_val
def bubble_sort(arr):
for i in range(len(arr)):
2. Focus on the most dominant term (ignore constants and low-order terms).
3. Space Complexity
It measures how much additional memory an algorithm needs as the input size increases.
Example
def sum_array(arr):
total = 0
return total
def fib(n):
memo = [0, 1]
for i in range(2, n+1):
memo.append(memo[i-1] + memo[i-2])
return memo[n]
• Best Case: Minimum time (e.g., searching and finding on the first try)
Best O(1)
Worst O(log n)
Average O(log n)
5. Tradeoffs
Sometimes:
7. Summary
Aspect Description