Advance Algorithm
Advance Algorithm
No on of an Algorithm
An algorithm is a finite, well-defined sequence of steps designed to solve a par cular problem or
perform a specific task.
Key Characteris cs
Effec veness: Each opera on must be basic enough to be carried out using known
techniques.
Simple Example
Keep in mind whether it’s suitable for parallel processing, embedded devices, etc.
Some problems are too complex for exact solu ons within me limits.
Opt for:
o Flowcharts
o Structured English
8. Proving Correctness
o Loop invariants
o Space complexity?
1. Analysis Framework
o Time Complexity: How many basic steps does it take to solve a problem of size
n?
6. Asympto c Nota on
Θ(f(n))\Theta(f(n)) Tight bound (sandwiched upper & lower) When bounds are exact
Using Limits:
Transi vity:
o If an algorithm does two things sequen ally (e.g., searching and sor ng), total
me = sum of their individual complexi es.
Upper Bound
Ensures an algorithm never takes more me than this (up to constant factors).
Example: If an algorithm has me complexity O(n2)O(n^2), it means it won't take more than
c⋅n2c \c.n^2 me for large enough n.
Lower Bound
Example: Ω(n)\Omega(n) implies that for large n, the algorithm cannot do be er than linear
me.
Tight Bound
Example: Θ(nlogn)\Theta(n \log n) means the me taken is always propor onal to nlognn
\log n, regardless of input varia ons.
= 0 → f(n)=o(g(n))f(n) = o(g(n))
= ∞ → f(n)=ω(g(n))f(n) = \omega(g(n))
Summary Table
O-nota on
What is O-Nota on (Big O)?
Big O nota on describes the upper bound of an algorithm’s running me. It expresses the
worst-case scenario growth rate of opera ons in rela on to input size nn.
It answers: "How badly can the algorithm perform as the input grows?"
Formal Defini on
f(n)=O(g(n))if∃ c>0,n0>0 such that ∀n≥n0,f(n)≤c⋅g(n)f(n) = O(g(n)) \quad \text{if} \quad \exists\
c > 0, n_0 > 0 \ \text{such that} \ \forall n \geq n_0, f(n) \leq c \cdot g(n)
Examples
Key Proper es
Ω -nota on
Ω-Nota on Explained
Ω-nota on provides a lower bound for the growth rate of an algorithm's running me. It tells
us the minimum me an algorithm must take, regardless of op miza ons or best-case inputs.
f(n)=Ω(g(n))if∃ c>0, n0>0 such that ∀n≥n0, f(n)≥c⋅g(n)f(n) = \Omega(g(n)) \quad \text{if} \quad
\exists\ c > 0,\ n_0 > 0\ \text{such that} \ \forall n \geq n_0,\ f(n) \geq c \cdot g(n)
Intui on
While Big-O is like saying "this car won't go faster than 100 km/h", Ω says "this car can't
go slower than 40 km/h" under op mal condi ons.
It gives us insight into best-case scenarios—how good the algorithm can possibly
perform.
Examples
Note: If the best and worst cases are the same, you might have
O(g(n))=Ω(g(n))=Θ(g(n))O(g(n)) = \Omega(g(n)) = \Theta(g(n))
Θ -nota on
Θ-nota on describes the exact asympto c behavior of an algorithm. It captures both the upper
and lower bounds, showing how the algorithm truly scales as input size nn grows large.
Formal Defini on
Interpreta on
It gives a sandwich bound: the algorithm's performance is both no worse than and no
be er than g(n)g(n), asympto cally.
So, if:
Examples
Why It Ma ers
O gives you a ceiling, Ω a floor, but Θ defines the true growth rate.
It’s the most informa ve, but it requires matching both bounds—which isn't always
possible.
Selec on Sort works by repeatedly selec ng the minimum (or maximum) element from the
unsorted part and placing it in the correct sorted posi on.
2. Find the minimum element in the remaining unsorted array from index i to n-1.
Pseudocode
cpp
for i = 0 to n - 2
min_index = i
for j = i+1 to n - 1
min_index = j
Example
Pass-by-pass Breakdown:
1. First Pass (i = 0): Minimum = 10 → swap with 29 → [10, 29, 14, 37, 13]
2. Second Pass (i = 1): Minimum = 13 → swap with 29 → [10, 13, 14, 37, 29]
3. Third Pass (i = 2): Minimum = 14 → already in place → [10, 13, 14, 37, 29]
4. Fourth Pass (i = 3): Minimum = 29 → swap with 37 → [10, 13, 14, 29, 37]
Time Complexity
Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order. It
“bubbles” the largest unsorted element to its correct posi on in each pass.
3. Repeat this process for all elements, reducing the range of comparison each me.
cpp
for i = 0 to n - 2:
for j = 0 to n - 2 - i:
Example
Pass-by-Pass Breakdown:
1. First Pass:
o 5 & 8 → OK
2. Second Pass:
o 1 & 4 → OK
o 4 & 5 → OK
3. Third Pass:
o 1 & 2 → OK
o 2 & 4 → OK
4. Fourth Pass:
o Sorted already
This algorithm checks each element one by one in a list un l it finds the target value or reaches
the end.
Algorithm Steps
5. If you reach the end and haven’t found it, return "Not Found".
cpp
if (arr[i] == key)
Example
Compare 12 → no
Compare 7 → no
Average O(n)O(n)
Space O(1)O(1)
Use Cases
Small datasets
Unsorted arrays
This algorithm checks for a given pa ern in a text by sliding the pa ern over the text one
character at a me and checking for a match at each posi on.
1. Let:
o T = Text of length n
o P = Pa ern of length m
cpp
int n = text.length();
int m = pa ern.length();
int j;
if (text[i + j] != pa ern[j])
break;
if (j == m) {
cout << "Pa ern found at index " << i << endl;
Example
Time Complexity
Case Complexity
Core Idea
Quick Sort picks a pivot element and par ons the array into two parts:
Elements greater than the pivot Then, it recursively applies the same logic to each part.
Algorithm Steps
cpp
int i = low - 1;
i++;
swap(arr[i], arr[j]);
Example
Input: [10, 80, 30, 90, 40, 50, 70] Let’s say the pivot is 70
Final Sorted Output: [10, 30, 40, 50, 70, 80, 90]
Worst Case O(n2)O(n^2) Unbalanced (e.g., sorted input with bad pivot)
Binary Search repeatedly divides the search interval in half to locate a target value.
cpp
return mid;
low = mid + 1;
else
high = mid - 1;
Example
Input Array: [5, 10, 15, 20, 25, 30, 35] Target (key): 25
Steps:
1. Dividing the array into halves recursively un l each sub-array has one element.
2. Merging the sorted sub-arrays to produce new sorted arrays, un l the whole array is
sorted.
cpp
if (l < r) {
int m = l + (r - l) / 2;
Example
Step-by-step Breakdown:
Divide:
Now:
Final merge:
[3, 27, 38, 43] + [9, 10, 82] → [3, 9, 10, 27, 38, 43, 82]
Core Idea
Inser on Sort works the way you might sort playing cards:
Start with an empty le hand and cards face down on the table.
Take cards one at a me and insert them into the correct posi on in the sorted part.
1. Start from the second element (i = 1), trea ng the first as sorted.
C++ Pseudocode
cpp
int j = i - 1;
j--;
Topological Sort is a linear ordering of ver ces in a Directed Acyclic Graph (DAG) such that for
every directed edge u → v, vertex u appears before v in the ordering.
Only works on DAGs—if the graph has a cycle, topological sor ng is not possible.
Applica ons
Data serializa on
Steps:
o Remove a node from the queue and add it to the topological order.
4. If the topological order contains all nodes → success. Otherwise, a cycle exists.
cpp
indegree[v]++;
queue<int> q;
if (indegree[i] == 0)
q.push(i);
vector<int> topo;
while (!q.empty()) {
topo.push_back(u);
if (--indegree[v] == 0)
q.push(v);
Example
5→4→2→3→1→0
Time Complexity
Time: O(V+E)O(V + E)
Space: O(V)O(V)
Core Idea
DFS starts at a source node and explores as far down a path as possible before backing up to try
other paths.
3. Repeat un l all ver ces reachable from the star ng point are visited.
cpp
visited[node] = true;
Example
Graph:
Ver ces: 0, 1, 2, 3, 4
Adjacency List:
0: [1, 2]
1: [3, 4]
2: []
3: []
4: []
Output: 0 1 3 4 2
Aspect Complexity
Time O(V+E)O(V + E)
Where:
E is number of edges
Core Idea
BFS starts from a source vertex and explores all its immediate neighbors before going deeper—
unlike DFS, which dives deep first.
It uses a queue to track the next vertex to explore and a visited array to avoid revisi ng nodes.
Algorithm Steps
Mark v as visited
Enqueue v
cpp
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
q.pop();
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
Example
Graph:
Ver ces: 0, 1, 2, 3, 4
Edges: 0 → 1, 0 → 2, 1 → 3, 1 → 4
Adjacency List:
0: [1, 2]
1: [3, 4]
2: []
3: []
4: []
Visit 0 → Enqueue 1, 2
Visit 1 → Enqueue 3, 4
Visit 2
Visit 3
Visit 4
Output: 0 1 2 3 4
Time and Space Complexity
Metric Complexity
Time O(V+E)O(V + E)
Space O(V)O(V)
Where:
E = number of edges