Advanced Data Structures Overview
Advanced Data Structures Overview
Data Structure
The data structure can be defined as the collection of elements and all the possible operations
which are required for those set of elements.
Data Structure and Algorithm
Data structures manage how data is stored and accessed, while Algorithms focus on processing
this data. Examples of data structures are Array, Linked List, Tree and Heap, and examples of
algorithms are Binary Search, Quick Sort and Merge Sort.
UNIT -1
Linear Data Structures and Memory Optimization
Array
An array is a linear data structure and it is a collection of element of same data type stored
at contiguous memory locations.
Key Features
Types of Arrays
1
Sparse arrays
A sparse array or sparse matrix is an array in which most of the elements are zero.
A Sparse Array is an optimized way of storing large arrays with many zero values by
saving only non-zero values and their positions.
Characteristics of Sparse array
Sparse matrices are those array that has the majority of their elements equal to zero.
A sparse array is an array in which elements do not have contiguous indexes starting
at zero.
Sparse arrays are used over arrays when there are lesser non-zero elements
Representation of Sparse Array
Sparse arrays can be represented in two ways:
a) Array Representation
b) Linked List Representation
1. Array Representation
To represent a sparse array 2-D array is used with three rows namely: Row, Column, and
Value.
Row: Index of the row where non-zero elements are present.
Column: Index of the column where the non-zero element is present.
Value: The non-zero value which is present in (Row, Column) index.
Advantages
1. Memory Efficient
2. Faster Access for Non-Zero Elements
2
3. Useful in matrices with lots of zeros
Disadvantages
Applications
Graph Representations
Image Compression
Machine Learning
Scientific Computation
Dynamic arrays
A Dynamic Array is a resizable array that can grow or shrink in size during runtime, unlike
a static array (fixed size). Dynamic Arrays = Resizable arrays that maintain random access
while supporting automatic expansion/shrinking.
Operation Complexity
Access (indexing) O(1)
Insertion (end) Amortized O(1)
Insertion (middle) O(n)
Deletion (end) O(1)
Deletion (middle) O(n)
Key Characteristics
Resizable Capacity
Random Access
3
Contiguous Memory Management
Memory Management
Advantages
Disadvantages
Example
Java
C++
Python
Java Script
Cache-aware structures
Modern CPUs have cache memory (L1, L2, and L3) between the processor and
main memory (RAM).
A Cache-Aware data structure is designed to take advantage of cache locality
(how data is laid out in memory) to reduce cache misses and improve performance.
Cache memory is small, high-speed memory that stores frequently used data and
instructions for quick retrieval by the CPU, significantly improving system
performance by reducing the need to access slower RAM.
Key Concepts
1. Spatial Locality
2. Temporal Locality
3. Cache Line
L1 Cache: The smallest and fastest cache, located directly on the CPU core.
L2 Cache: Larger and slightly slower than L1, it can be integrated into the
CPU or sit close to it.
L3 Cache: The largest and slowest of the CPU caches, shared across multiple
4
processor cores.
Key Characteristics
Volatility: Like RAM, cache memory is volatile, meaning it loses its contents
when the power is turned off.
Advantages
Disadvantages
5
Implementation can be complex (requires tuning to cache line size).
May be architecture-dependent (different CPUs have different cache sizes).
Applications
Databases
Operating Systems
Scientific Computing
Big Data / Machine Learning
Linked lists
A linked list is a linear data structure where elements, called nodes, are connected
using pointers. Each node contains:
Unlike arrays, linked lists do not store elements in contiguous memory, which
allows dynamic memory allocation and easy insertion/deletion.
5. Skip List
6. Unrolled List
6
Operation Description
Traversal Visit each node from head to tail.
Insertion Add a node at the beginning, end, or a specific position.
Deletion Remove a node from the beginning, end, or a specific position.
Search Find a node with a specific value.
Update Modify the value of a node.
Advantages
Disadvantages
Polynomial ADT
Radix Sort
Multilist
Skip lists
A skip list is a probabilistic data structure that allows fast search, insertion, and
deletion operations, similar to a balanced binary search tree (BST), but easier to
implement.
It is essentially a layered linked list where higher layers act as "express lanes" to skip
multiple elements, improving search efficiency.
Structure
Operations
Average Case
Search-Insert-Delete – O(log n)
Worst Case
7
Search-Insert-Delete – O(n)
Advantages
Disadvantages
Applications
Databases (Redis)
Concurrent data structure
Memory Key Value Store
Indexing system
An Unrolled Linked List (ULL) is a variation of a linked list where each node
stores an array of elements instead of a single element.
This reduces pointer overhead and improves cache performance, making it more
efficient for large datasets.
Structure
Key Characteristics
Node Structure
8
Cache Performance
Memory Overhead
Operations
Insertion/Deletion
Traversal
Searching
Advantages
Disadvantages
In an XOR linked list, each node stores only one pointer (npx) which is the
XOR (exclusive OR) of the addresses of the previous and next nodes.
This saves memory since only one pointer is stored instead of two.
9
Types of XOR Linked List
There are two main types of XOR Linked List:
Singly Linked XOR List: A singly XOR linked list is a variation of the XOR linked
list that uses the XOR operation to store the memory address of the next node in a
singly linked list.
Doubly Linked XOR List: A doubly XOR linked list is a variation of the XOR linked
list that uses the XOR operation to store the memory addresses of
the next and previous nodes in a doubly linked list.
Traversal in XOR linked list
Two types of traversal are possible in XOR linked list.
Forward Traversal
Backward Traversal:
Forward Traversal in XOR linked list
address of next Node = (address of prev Node) ^ (both)
Operations
Insertion
Deletion
Traversal
Traversal: O(n)
Insertion/Deletion: O(1)
10
Advantages
Memory-efficient
Saves space in memory-constrained environments.
Disadvantages
Stacks
A stack in data structure is a linear data structure that follows the LIFO (Last In,
First Out) principle.
This means the last element inserted (pushed) into the stack is the first one to be
removed (popped).
In which both insertion and deletion occur at only one end of the list called the Top.
Key Features
IMPLEMENTATION OF STACK
Array implementation of Stack
Linked list implementation of Stack
Array implementation of Stack
Push Operation
It adds a new element to the stack.
When implementing the push operation, overflow condition of a stack is to be
checked.
E.g.
11
Routine to check stack is FULL
int isFull(stack s)
{
if(Top>=Arraysize-1)
return(1);
}
Routine to Push an element on to stack
Void push(int x, stack s)
{
if(isFull((s))
Error(“Full Stack”);
else{
top=top+1;
s[top]=x;
}
}
ROUTINE TO DISPLAY THE ELEMENT OF THE STACK
void display(int s[])
{
printf("Display the elements in the stack");
for(i=top;i>=0;i--)
{
printf(" \n %d",s[i]);
}}
Pop Operation
A Pop operation deletes the topmost elements from the stack.
Underflow condition of a stack is to be checked.
Example
12
{
If(top==-1)
Return(1);
}
Routine to return top element of the stack (Peek)
Int topelement (stack s)
{
If(!IsEmpty(s))
Return s[top];
Else
Error(“Empty stack”);
Return 0;
}
Linked list implementation of Stack
Dynamically created
The list is a collection of nodes. Each node consists of two fields, data and next
pointer.
DECLARATION FOR LINKED LIST IMPLEMENTATION
struct node
{
int data;
struct node *link;
}
13
top= top->next;
free(temp)
}
}
Routine to test whether a stack is empty
Int IsEmpty(stack s)
{
If(s->next== NULL);
Return(1);
}
Application of Stack
Balancing Symbol
Function call
Postfix Expression evaluation
Infix to Postfix Conversion
INFIX NOTATION
For example: A+B
POSTFIX NOTATION
For example: AB +
PREFIX NOTATION
For example: +AB
14
15
Postfix Expression Evaluation
16
Queue
A Queue in data structure is a linear data structure that follows the FIFO (First In,
First Out) principle.
This means the first element inserted (enqueued) is the first one to be removed
(dequeued).
Key Features
Representation
Array-based Queue
Linked List-based Queue
Circular Queue
17
Variants of Queue
1. Linear Queue
2. Circular Queue
3. Deque (Double-Ended Queue)
4. Priority Queue
Applications of Queue
1. CPU Scheduling
2. I/O Buffers
3. Breadth-First Search (BFS)
4. Resource management
5. Simulation systems
Enqueue operation
18
Linked List Implementation of Queue
Struct node
{
Int data;
Struct node*next;
}
Else{
rear→next= temp;
rear= rear→next; }
Insertion
Q getnode(Q*temp)
{
Temp= malloc(Size of(Q));
Temp→ next= NULL:
Return temp;
}
Void insert()
{
Q*temp;
temp= getnode(temp);
if(front == NULL;)
{
Front= temp;
Rear= temp;
}}
Deletion
19
Priority queues
20
Operations
Key Characteristics
Priority Assignment
FIFO for identical Priorities
Priority based Deletion
Implementation Methods
1. CPU Scheduling
2. Dijkstra’s Algorithm / A Search* (shortest path in graphs).
3. Huffman Coding
4. Network Routers
5. Event-Driven Simulations
Types of Deque
1. Input-Restricted Deque
2. Output-Restricted Deque
Example
Operations in Deque
1. InsertFront(x)
2. InsertRear(x)
21
3. DeleteFront()
4. DeleteRear()
5. PeekFront() / PeekRear()
6. isEmpty(), isFull()
22
Applications of Deque
1. Palindrome checking
2. Sliding Window problems
3. Job/Task scheduling
4. Undo/Redo operations
5. Deque-based Queue/Stack implementations
23
Circular buffers
Key Features
1. Fixed Size
2. Wrap-around
3. Efficient Memory Use
Operations
Example
1. CPU Scheduling
2. Streaming Data
3. I/O Buffers in Operating Systems.
4. Embedded Systems
24
Advantages of circular queue
Hashing
Applications of Hashing
1. Databases
2. Symbol Tables
3. Cryptography
4. Caching
5. Hash Tables
6. Data Integrity
7. Data Structure
8. File Systems
25
26
27
28
29
30
Perfect hashing
Key Features
Example
h(10) = 1
h(22) = 1 ❌ Collision
So this is not perfect hashing.
h(10) = 3
h(22) = 1
h(37) = 2
No collisions → Perfect Hashing.
Implementation Approaches
31
Here, R = 7 and N = 5. The universal hash has unused buckets and collisions. The perfect
hash has no collisions, and the MPH has neither collisions nor unused buckets.
1. Compilers
2. Databases
3. Networking
4. Embedded Systems
Advantage
No collisions
Disadvantage
Complex to construct.
Cuckoo hashing
Cuckoo Hashing is a collision resolution technique in hashing that uses two (or more)
hash functions and ensures O(1) lookup time in the worst case.
It is named after the cuckoo bird, which lays its eggs in another bird’s nest, often
displacing the existing eggs. Similarly, in Cuckoo Hashing, when a collision occurs, the
existing key is kicked out and reinserted into another position using a different hash
function.
Key Idea
Operations
1. Insertion
2. Search
32
3. Deletion
Example
h1(x) = x % 7
h2(x) = (x / 7) % 7
Properties
Applications
1. Networking
2. Databases
3. Memory Systems
4. Real-time Systems
Extendible hashing
Extendible Hashing is a dynamic hashing technique used in databases and file systems.
It solves the problem of bucket overflows in static hashing by allowing the hash table to grow
or shrink dynamically.
Key Concepts
Main Features
33
Directories: The directories store addresses of the buckets in pointers.
Buckets: The buckets are used to hash the actual data.
34
Limitations
Size of every bucket is fixed.
Memory is wasted in pointers when the global depth and local depth difference
becomes drastic.
This method is complicated to code.
Advantages
Disadvantages
UNIT- 2
Advanced Tree Data Structures
Balanced Trees
A balanced tree is a binary tree where the height difference between the left and right sub
trees of any node is kept within certain limits. This ensures the tree remains shallow, so
operations are efficient.
1. Height-balanced: Difference between left and right sub tree heights is minimized.
2. Efficient operations:
o Searching: O(log n)
o Insertion: O(log n)
o Deletion: O(log n)
3. Avoids skewed trees (like linked lists).
10 20
\ / \
35
20 10 30
\ \
30 40
AVL
An AVL Tree (named after inventors Adelson-Velsky and Landis, 1962) is a self-
balancing Binary Search Tree (BST) where the height difference (balance factor)
between the left and right subtrees of any node is at most
BalanceFactor(node)=height(leftSubtree)−height(rightSubtree)BalanceFactor(node) =
height(leftSubtree) -
height(rightSubtree)BalanceFactor(node)=height(leftSubtree)−height(rightSubtree)
36
37
38
39
40
Applications of AVL Trees
Red-Black Trees
Operations
When inserting or deleting, violations of RBT properties can occur. They are fixed by:
Applications
Splay Trees
A Splay Tree is a type of self-adjusting binary search tree (BST) in which recently
accessed elements are moved closer to the root by a process called splaying.
Key Idea
41
After search, insertion, or deletion, the accessed node is splayed (rotated) to the
root.
This makes future access to that node faster.
Over time, frequently used elements stay near the top.
1. Search(x)
o Search like BST.
o If found (or last accessed node if not found), splay it to the root.
2. Insert(x)
o Insert as in BST.
o Then splay the inserted node to the root.
3. Delete(x)
o Search & splay x to the root.
o Remove root.
o Join left and right subtrees by splaying the largest node of the left subtree and
attaching the right subtree.
Applications
Treaps
42
Each node stores:
Properties
Operations in Treap
1. Insertion(key, priority)
o Insert node as in BST (by key).
o Assign a random priority.
o If heap property is violated, rotate to fix.
2. Deletion(key)
o Search key like BST.
o Rotate down the node until it becomes a leaf (maintaining heap property).
o Delete it.
3. Search(key)
o Same as BST search.
Rotations in Treap
Applications
Multi-way Trees
Multi-way Tree (also called an m-ary tree) is a tree in which each node can have more
than two children (unlike a binary tree).
43
B-Trees
Properties of B-Trees
Operations
Complexity
Applications
Advantages of B-Trees
B-Trees are self-balancing.
High-concurrency and high-throughput.
Efficient storage utilization.
44
Disadvantages of B-Trees
B-Trees are based on disk-based data structures and can have a high disk usage.
Not the best for all cases.
B+ Trees
B+ Tree is an advanced data structure used in database systems and file systems to
maintain sorted data for fast retrieval, especially from disk. It is an extended version of the B
Tree, where all actual data is stored only in the leaf nodes, while internal nodes contain only
keys for navigation.
Components of B+ Tree
Leaf nodes store all the key values and pointers to the actual data.
Internal nodes store only the keys that guide searches.
All leaf nodes are linked together, supporting efficient sequential and range queries.
Features of B+ Trees
Balanced
Multi-level
Ordered
High Fan-out
Cache-friendly
Disk-efficient
Difference between B+ Tree and B Tree
Parameters B+ Tree B Tree
Leaf nodes form a linked list for Leaf nodes do not form a linked
Leaf Nodes
efficient range-based queries list
Key Typically allows key duplication Usually does not allow key
Duplication in leaf nodes duplication
45
Parameters B+ Tree B Tree
Memory Requires more memory for Requires less memory as keys and
Usage internal nodes values are stored in the same node
Advantages of B+Trees
Data stored in a B+ tree can be accessed both sequentially and directly.
It takes an equal number of disk accesses to fetch records.
B+trees have redundant search keys, and storing search keys repeatedly is not
possible.
Disadvantages of B+ Trees
Slower exact match
More disk access
Complex updates
Extra space
R-Trees
R-tree is a tree data structure used for storing spatial data indexes in an efficient
manner. R-trees are highly useful for spatial data queries and storage.
An R-Tree (Rectangle Tree) is a balanced multi-way search tree designed for
indexing multi-dimensional data like:
Key Idea
Properties of R-Trees
Variants of R-Tree
Applications of R-Trees
46
Geographic Information Systems (GIS) 🌍 (maps, GPS, spatial queries).
Databases (spatial indexes in PostgreSQL, Oracle Spatial).
Computer Graphics & CAD (collision detection, object representation).
Networking (location-based services, nearest server lookup).
Segment Trees
A Segment Tree is a binary tree data structure used for storing information about
intervals (segments) or ranges.
It allows efficient range queries and range updates (like sum, minimum, maximum,
gcd, etc.) in O(log n) time.
Example
Array = [2, 5, 1, 4, 9, 3]
[24]
/ \
[8] [16]
/ \ / \
[7] [1] [13] [3]
/ \ /\ / \ / \
[2] [5] [1] [4] [9] [4] [9] [3]
Operations
Variants
47
Lazy Propagation → Handles range updates efficiently.
Dynamic Segment Tree → For large/unbounded ranges.
2D Segment Trees → For queries on 2D grids (matrices).
Applications
Advantages
Efficient querying
Efficient updates
Flexibility
Disadvantages
Complexity
Time complexity
Fenwick Trees
A Fenwick Tree, also called a Binary Indexed Tree (BIT), is a data structure that
provides:
It is an alternative to Segment Trees but is often simpler and uses less memory (O(n)).
Key Idea
Operations
Example
Array: [2, 1, 3, 2, 1, 4, 5]
48
Fenwick Tree Representation (BIT):
Index: 1 2 3 4 5 6 7
BIT[]: 2 3 3 8 1 5 5
BIT[1] = arr[1] = 2
BIT[2] = arr[1] + arr[2] = 3
BIT[4] = arr[1] + arr[2] + arr[3] + arr[4] = 8
And so on...
Complexity
Applications
Structure
49
Operations
Insert(word)
Search (word)
Prefix search
Applications
Autocomplete systems.
Spell checking.
Prefix-based searching.
IP routing (longest prefix match).
Efficient dictionary representation.
Complexity
Suffix Trees
Structure
Applications
Complexity
50
Space: O(n)O(n)O(n), but large constant factors (often 10–20× input size).
Space Higher (but per inserted word) Higher (proportional to input string length)
Applications in indexing
Indexing with Tries
A Trie is essentially a natural indexing structure for strings because it organizes data based
on prefixes.
Applications in Indexing
A Suffix Tree indexes all suffixes of a string, making it a powerful indexing tool for
substring problems.
Applications in Indexing
1. Full-text Indexing
o Allows substring queries in O(m)O(m)O(m) time (where mmm is query
length).
o Used in search engines and text editors.
2. Pattern Matching Index
o Efficiently checks if a pattern exists in the text.
51
o Example: Find if "ana" occurs in "banana".
3. Substring Frequency Index
o Can count occurrences of a substring quickly.
o Useful in analytics (e.g., keyword frequency).
4. Bioinformatics Indexing
o DNA/protein sequences are long strings.
o Suffix trees help index them for fast pattern matching (e.g., finding gene
sequences).
5. Plagiarism Detection Index
o Detects longest common substrings across documents.
Text retrieval
Text retrieval is the process of storing, indexing, and searching text efficiently.
It’s a core area of Information Retrieval (IR) – finding relevant documents/strings
based on queries.
2. Suffix Trees
3. Suffix Arrays
4. Inverted Index
52
Fundamental structure in search engines.
Maps each word → list of documents containing it.
Example:
"banana" → [Doc1, Doc5]
"apple" → [Doc2, Doc3, Doc4]
Applications:
o Google search
o Document retrieval
o Keyword queries
5. B-Trees / B+ Trees
6. Hashing
Computational geometry
Computational Geometry is the study of algorithms and data structures for solving
geometric problems involving points, lines, polygons, and shapes.
It’s widely used in graphics, robotics, GIS, CAD, gaming, and computer vision.
1. Point Location
2. Convex Hull
3. Range Searching
4. Nearest Neighbor Search
5. Intersection Problems
6. Triangulation
53
1. Segment Tree
Stores intervals/segments.
Used for:
o Line segment intersection detection.
o Range queries (e.g., how many lines overlap at a point).
2. Interval Tree
3. Range Trees
5. Quad Trees
6. R-Trees
54
Applications of Computational Geometry
UNIT – 3
Graph Data Structures and Algorithms
Representation: Adjacency list/matrix
Adjacency Matrix
An Adjacency Matrix is a 2D array (matrix) used to represent a graph.
A B C D
A[0 1 1 0]
B[1 0 0 1]
C[1 0 0 0]
D[0 1 0 0]
Best for
Adjacency List
A → [B, C]
55
B → [A, D]
C → [A]
D → [B]
Best for
In Algorithms
Incidence matrix
An Incidence Matrix is a way of representing a graph using a matrix of size V×EV \times
EV×E, where:
Rules
1. Undirected Graph:
o If edge eje_jej connects vertex viv_ivi, then:
M[i][j]=1M[i][j] = 1M[i][j]=1 if viv_ivi is incident to eje_jej.
Otherwise, M[i][j]=0M[i][j] = 0M[i][j]=0.
o Each column has exactly two 1’s (since each edge connects two vertices).
2. Directed Graph:
o If edge eje_jej goes from vertex viv_ivi: M[i][j]=−1M[i][j] = -1M[i][j]=−1.
o If edge eje_jej goes to vertex vkv_kvk: M[k][j]=+1M[k][j] = +1M[k][j]=+1.
o Otherwise: 000.
o Each column has one -1 and one +1.
Vertices: A, B, C
Edges: e1 = (A, B), e2 = (B, C), e3 = (A, C)
Incidence Matrix:
e1 e2 e3
A →[1 0 1]
56
B →[1 1 0]
C →[0 1 1]
Example 2: Directed Graph
Vertices: A, B, C
Edges: e1 = A → B, e2 = B → C, e3 = C → A
Incidence Matrix:
e1 e2 e3
A → [ -1 0 1 ]
B → [ 1 -1 0 ]
C → [ 0 1 -1 ]
Properties
Applications in Algorithms
Compressed storage
Arrays:
o val[] → stores nonzero values
o col[] → stores column indices
o row_ptr[] → marks starting index of each row
57
✅ Applications: Graph algorithms (adjacency matrix compression), scientific computing.
Summary
Technique Where Used
CSR / CSC Sparse matrices, graph algorithms
Compressed Tries String dictionaries, IP routing
RLE Text/images with repetition
Huffman Coding File formats, multimedia compression
Dictionary-based (LZW) ZIP, PNG, GIF
Compressed Suffix Arrays Text indexing, DNA sequences
Graph compression Social networks, web graphs
Graphs (or trees as a special case) can be explored systematically using traversal algorithms.
The two fundamental ones are:
DFS(node):
mark node as visited
for each neighbor of node:
if neighbor not visited:
DFS(neighbor)
Applications of DFS
59
o Generate a DFS Tree.
Pseudocode (BFS)
BFS(start):
create a queue Q
mark start as visited
enqueue start
while Q not empty:
node = dequeue(Q)
for each neighbor of node:
if neighbor not visited:
mark visited
enqueue(neighbor)
Applications of BFS
60
Given a graph G(V, E) with edge weights w(u, v) ≥ 0:
1. Initialization
o Distance of source s = 0
o Distance of all other vertices = ∞
o Mark all vertices unvisited
2. Processing
o While there are unvisited vertices:
Select vertex u with the minimum distance
Mark u as visited
For each neighbor v of u:
If dist[u] + w(u, v) < dist[v]
→ Update dist[v] = dist[u] + w(u, v)
3. End
o Distances now represent shortest paths from s
Pseudocode
Dijkstra(Graph, source):
for each vertex v in Graph:
dist[v] = ∞
prev[v] = NIL
dist[source] = 0
create a priority queue Q
[Link](source, 0)
while Q is not empty:
u = Q.extract_min()
for each neighbor v of u:
alt = dist[u] + weight(u, v)
if alt < dist[v]:
dist[v] = alt
prev[v] = u
Q.decrease_key(v, alt)
return dist[], prev[]
Limitations
Does not work with negative weight edges (Bellman-Ford is needed instead).
61
Bellman-Ford
Algorithm (Steps)
1. Initialization
o Distance to source = 0
o Distance to all other vertices = ∞
2. Relaxation (Repeat V – 1 times)
o For each edge (u, v) with weight w:
If dist[u] + w < dist[v] → update dist[v] = dist[u] + w
3. Negative Cycle Check
o Run one more relaxation:
If any distance is updated → Negative cycle exists.
Pseudocode
BellmanFord(Graph, source):
for each vertex v in Graph:
dist[v] = ∞
dist[source] = 0
for i = 1 to V-1:
for each edge (u, v) with weight w in Graph:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for each edge (u, v) with weight w in Graph:
if dist[u] + w < dist[v]:
return "Negative weight cycle detected"
return dist[]
Applications of Bellman–Ford
Floyd-Warshall
Algorithm (Steps)
1. Initialization
o Construct a distance matrix dist[][] from the adjacency matrix.
o If no edge exists → ∞ (infinity).
o Distance of vertex to itself = 0.
2. Dynamic Programming Update
o For each vertex k (as intermediate):
For each pair (i, j):
62
Update:
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
3. Result
o Matrix dist[][] gives shortest distances between all vertex pairs.
o If dist[i][i] < 0 → Negative cycle exists.
Pseudocode
FloydWarshall(Graph):
let dist = adjacency matrix of Graph
for k = 1 to V:
for i = 1 to V:
for j = 1 to V:
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist
Applications of Floyd–Warshall
Johnson’s algorithm
It finds the shortest paths between all pairs of vertices in a weighted directed graph. It
allows some of the edge weights to be negative numbers, but no negative-weight
cycles may exist.
Use Floyd–Warshall for dense graphs.
Use Johnson’s Algorithm for sparse graphs with possible negative weights.
63
Steps of Johnson’s Algorithm
A spanning tree of a graph is a subset of edges that connects all vertices with no
cycles.
64
A minimum spanning tree is a spanning tree with the minimum total edge weight.
MST exists only for connected, undirected, weighted graphs.
1. Prim’s Algorithm
Start from a node, grow the MST one edge at a time by always picking the
minimum edge that connects a vertex inside the tree to one outside.
Steps
Pseudocode
Prim(Graph, start):
Initialize MST = {}
dist[v] = ∞ for all vertices
dist[start] = 0
Q = priority queue of all vertices
while Q is not empty:
u = extract_min(Q)
for each neighbor v of u:
if v in Q and weight(u,v) < dist[v]:
dist[v] = weight(u,v)
parent[v] = u
return parent[]
2. Kruskal’s Algorithm
Start with all vertices as separate components, then add edges in increasing weight
order, avoiding cycles.
Uses Disjoint Set Union (DSU) / Union-Find to check cycles.
Steps
Pseudocode
Kruskal(Graph):
MST = {}
sort edges by weight
for each edge (u, v) in sorted order:
if Find(u) != Find(v):
65
[Link]((u, v))
Union(u, v)
return MST
Comparison: Prim’s vs Kruskal’s
Feature Prim’s Algorithm Kruskal’s Algorithm
Approach Grow MST from a start node Add edges by global min wt
Data Structure Priority Queue (Heap) Union-Find (Disjoint Set)
Best For Dense graphs (many edges) Sparse graphs (few edges)
Complexity O(E log V) O(E log E)
Cycle Check Implicit (via tree growth) Explicit (Union-Find)
Applications of MST
1. Network Design
o Laying cables, pipelines, roads (minimum cost).
2. Clustering in Machine Learning
o Single-link hierarchical clustering.
3. Approximation Algorithms
o Basis for TSP approximation.
4. Image Segmentation
o Region-based grouping in computer vision.
Borůvka’s algorithm
Algorithm (Steps)
Pseudocode
Boruvka(Graph):
MST = {}
Components = {each vertex is a separate set}
while number_of_components > 1:
for each component C:
find the cheapest edge (u, v) leaving C
for each chosen edge (u, v):
if u and v are in different components:
66
[Link]((u, v))
Union(u, v)
return MST
Applications
1. Network Design
o Constructing low-cost power or telecommunication networks.
2. Parallel & Distributed Computing
o Each component can independently find its cheapest edge (parallel-friendly).
3. Sparse Graph Optimization
o Especially useful in early MST computations before Kruskal/Prim
optimizations.
Ford–Fulkerson Method
Algorithm (Steps)
Pseudocode
FordFulkerson(Graph, s, t):
for each edge (u, v):
f[u][v] = 0
while there exists augmenting path P from s to t:
bottleneck = min(residual_capacity(u, v) for (u, v) in P)
for each edge (u, v) in P:
f[u][v] += bottleneck
f[v][u] -= bottleneck // reverse edge
return total flow from s
Applications of Ford–Fulkerson
1. Network Routing
2. Bipartite Matching
3. Circulation Problems
4. Image Segmentation
5. Project Scheduling
Edmonds-Karp
67
It is Ford–Fulkerson + BFS.
Instead of choosing any augmenting path arbitrarily, Edmonds–Karp always chooses
the shortest augmenting path (in terms of number of edges) using Breadth-First
Search (BFS) in the residual graph.
Algorithm (Steps)
1. Initialize flow:
Set all edge flows f(u, v) = 0.
2. Build residual graph:
For each edge (u, v) with capacity c(u, v), maintain residual capacity:
o Forward: c(u, v) – f(u, v)
o Backward: f(u, v)
3. Find augmenting path (BFS):
o Run BFS from source s to sink t in residual graph.
o If no path exists → stop.
4. Augment flow:
o Find bottleneck capacity = min residual capacity along the BFS path.
o Increase flow along forward edges, decrease along reverse edges.
5. Repeat until no augmenting path exists.
Pseudocode
EdmondsKarp(Graph, s, t):
for each edge (u, v):
f[u][v] = 0
max_flow = 0
while BFS(s, t) finds augmenting path P:
bottleneck = min(residual_capacity(u, v) for (u, v) in P)
for each edge (u, v) in P:
f[u][v] += bottleneck
f[v][u] -= bottleneck
max_flow += bottleneck
return max_flow
Applications
Push-Relabel
It maintains a preflow: flow that may temporarily violate the conservation property (a
vertex can have more incoming flow than outgoing).
Excess flow is gradually pushed "downhill" from source s toward sink t.
68
A height function (label) guides flow direction: flow is only pushed from higher to
lower height nodes.
Algorithm (Steps)
1. Initialization
o Set flow f(u, v) = 0.
o Set h(s) = |V|, h(v) = 0 for others.
o Push maximum possible flow from source s to its neighbors.
2. While some vertex u (≠ s, t) has excess flow:
o If u can push flow to neighbor v: Push.
o Else: Relabel (increase h(u)).
3. Continue until no vertex (except sink) has excess flow.
Pseudocode
PushRelabel(Graph, s, t):
initialize preflow: f(u, v) = 0
h[s] = |V|, h[v] = 0 for all v ≠ s
for each neighbor v of s:
f(s, v) = c(s, v)
e(v) = c(s, v)
while there exists a vertex u ≠ s, t with e(u) > 0:
if exists v such that (u, v) has residual capacity and h(u) = h(v) + 1:
Push(u, v)
else:
Relabel(u)
return total flow out of s
Applications
UNIT -4
Algorithm Design and Paradigms
Divide and Conquer: Karatsuba’s multiplication
69
The Karatsuba multiplication algorithm is a fast multiplication algorithm based on the
divide and conquer technique. It improves the multiplication of two nnn-digit numbers from
the classical complexity of
O(n2) to
Karatsuba’s Trick
Strassen’s algorithm
O(n3)O(n^3)O(n3)
operations.
Strassen’s idea (1969): Use Divide and Conquer to reduce the number of
multiplications.
→ Achieves time complexity:
Applications
70
Useful in large matrix multiplications.
Forms the basis of faster algorithms like Coppersmith-Winograd.
Applied in computer graphics, scientific computing, and big data problems.
Greedy Strategy
1. Build the Huffman tree by repeatedly merging the two least-frequent nodes.
2. Assign 0 to one branch and 1 to the other.
3. Codes are obtained by traversing from the root to each leaf.
Algorithm Steps
Example
A(5) + B(9) = 14
Insert back → {C:12, D:13, (AB):14, E:16, F:45}
71
C(12) + D(13) = 25
(AB)(14) + E(16) = 30
(CD)(25) + (AB,E)(30) = 55
(55) + F(45) = 100
F=0
C = 100
D = 101
A = 1100
B = 1101
E = 111
Result
Applications
Interval scheduling
Problem Definition
You are given n intervals/jobs, each with a start time and finish time.
Goal: Select the maximum number of non-overlapping intervals.
Greedy Algorithm
72
Algorithm Steps
Example
(1,3),(2,5),(4,6),(6,7),(5,9),(8,10)(1, 3), (2, 5), (4, 6), (6, 7), (5, 9), (8,
10)(1,3),(2,5),(4,6),(6,7),(5,9),(8,10)
(1,3),(4,6),(6,7),(2,5),(5,9),(8,10)(1, 3), (4, 6), (6, 7), (2, 5), (5, 9), (8,
10)(1,3),(4,6),(6,7),(2,5),(5,9),(8,10)
(1,3),(2,5),(4,6),(6,7),(5,9),(8,10)(1, 3), (2, 5), (4, 6), (6, 7), (5, 9), (8,
10)(1,3),(2,5),(4,6),(6,7),(5,9),(8,10)
Applications
Definition
We are given:
73
o A universe of elements U={1,2,...,n}U = \{1,2,...,n\}U={1,2,...,n}
o A collection of subsets S={S1,S2,...,Sm}S = \{S_1, S_2, ..., S_m\}S={S1,S2
,...,Sm}, each Si⊆US_i \subseteq USi⊆U.
Goal: Select the minimum number of subsets from SSS whose union covers UUU.
Algorithm Steps
Example
Universe:
U={1,2,3,4,5,6,7}U = \{1,2,3,4,5,6,7\}U={1,2,3,4,5,6,7}
Subsets:
S1={1,2,3}S_1 = \{1,2,3\}S1={1,2,3}
S2={2,4,5}S_2 = \{2,4,5\}S2={2,4,5}
S3={3,6}S_3 = \{3,6\}S3={3,6}
S4={4,5,6,7}S_4 = \{4,5,6,7\}S4={4,5,6,7}
Applications
74
Test case reduction (cover all conditions with fewer test cases)
Example:
Example
Given dimensions:
Matrices:
75
o (A1A2)(A3A4)(A_1A_2)(A_3A_4)(A1A2)(A3A4) = 30000 multiplications
(optimal)
Applications
Floyd Warshall
Problem Definition
Algorithm
for k = 1 to n:
for i = 1 to n:
for j = 1 to n:
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
Example
Edge weights:
o 1→2=41 \to 2 = 41→2=4
o 2→3=52 \to 3 = 52→3=5
o 1→3=101 \to 3 = 101→3=10
76
Applications
Knapsack variants
We are given:
o A set of nnn items, each with:
weight wiw_iwi
value viv_ivi
o A knapsack of capacity WWW.
Goal: Maximize the total value without exceeding the capacity.
Knapsack Variants
0/1 Knapsack
Fractional Knapsack
Unbounded Knapsack
Complexity: O(nW)O(nW)O(nW).
77
Bounded Knapsack
Each item can be taken a limited number of times (given count cic_ici).
Reduction to 0/1 knapsack using binary representation trick (e.g., item count 13 →
items of 1, 2, 4, 6).
Complexity: O(nWlogci)O(nW \log c_i)O(nWlogci).
Applications
Backtracking
Steps
78
Branch and Bound
Steps
79
A randomized algorithm is an algorithm that uses random numbers during its execution to
make decisions. This introduces probabilistic behavior in the outcome, performance, or
both.
Probabilistic Analysis
Key Concepts
Example
80
o
Expected chain length is small (O(1)O(1)O(1)) under random uniform
hashing.
Randomized QuickSort:
o Expected runtime is O(nlogn)O(n \log n)O(nlogn) even though worst case is
O(n2)O(n^2)O(n2).
Applications
UNIT -5
Computational Complexity and Approximation Algorithms
Complexity Classes: P
Definition
P (Polynomial time) is the class of decision problems (yes/no problems) that can be
solved by a deterministic Turing machine in polynomial time.
Key Features
Examples of Problems in P
Important
81
Applications
NP
Example
Problem: Given a set of integers, is there a subset whose sum equals a target value?
Hard to compute directly (may take exponential time).
But if someone gives you a subset, you can quickly add the numbers and check if it
equals the target → verification is polynomial time.
Thus, it belongs to NP.
Relation with P
P ⊆ NP
o Every problem in P (solvable in polynomial time) is also in NP (since we can
verify solutions easily).
Open question:
Is P = NP? → Still unsolved in Computer Science.
NP-Complete (NPC):
o Problems that are both in NP and as hard as any other problem in NP.
o If you solve one NP-Complete problem in polynomial time → all NP
problems can be solved in polynomial time.
o Examples: Traveling Salesman Problem (decision version), 3-SAT, Clique
problem.
82
NP-Hard:
o At least as hard as NP problems but not necessarily in NP (may not even be
decision problems).
o Example: Optimization version of TSP.
Diagram (Hierarchy)
P ⊆ NP ⊆ NP-Complete ⊆ NP-Hard
NP-Complete
Important in DSA
83
o Does a cycle exist that visits every vertex exactly once?
NP-Hard
Important in DSA
84
o Approximation algorithms (e.g., for TSP, Vertex Cover)
o Heuristics & Metaheuristics (e.g., Genetic algorithms, Simulated annealing)
o Branch-and-Bound / Backtracking
Relation (Hierarchy)
P ⊆ NP
⊆ NP-Complete
⊆ NP-Hard
Polynomial-Time Reduction
Notation: A ≤p B
Why Important
Example
Subset Sum Problem: Does there exist a subset of numbers that adds to K?
Knapsack Problem: Can items be chosen such that weight ≤ W and value ≥ V?
We can convert Subset Sum into a special case of Knapsack in polynomial time →
proving that if Knapsack can be solved efficiently, so can Subset Sum.
85
1. 3-SAT ≤p Clique
o SAT formulas can be reduced to graphs (clique problem).
2. Clique ≤p Vertex Cover
o Graph transformations map one to another.
3. Hamiltonian Cycle ≤p Traveling Salesman Problem (TSP)
o Special weights enforce equivalence.
Key Concepts
SAT ∈ NP (trivial).
Every NP problem can be reduced to SAT in polynomial time.
This means SAT was the first problem proven NP-Complete.
After this, to prove other problems NP-Complete, researchers reduce SAT to them.
Importance in DSA
86
2. The machine’s computation steps can be encoded into a Boolean formula.
3. The formula is satisfiable if and only if the machine accepts the input.
4. Thus, solving SAT is as powerful as solving any NP problem.
Approximation Algorithms
Since exact solutions are hard, we use approximation algorithms that guarantee a solution
close to optimal.
Guarantee:
This algorithm gives a solution of size at most 2 × OPT (where OPT = size of
minimum vertex cover).
Hence, it’s a 2-approximation.
Example
Graph edges:
Set cover
Definition
We are given:
o A universe U={e1,e2,…,en}U = \{e_1, e_2, …, e_n\}U={e1,e2,…,en} (a set
of elements).
o A collection of subsets S={S1,S2,…,Sm}S = \{S_1, S_2, …, S_m\}S={S1,S2
,…,Sm}, where each Si⊆US_i \subseteq USi⊆U.
Goal: Find the smallest number of subsets from SSS whose union equals UUU.
Example
Universe:
U = {1, 2, 3, 4, 5}
Subsets:
S1 = {1, 2, 3}
S2 = {2, 4}
S3 = {3, 4, 5}
Complexity
88
3. Stop when all elements are covered.
Performance
Applications in DSA
TSP
Problem Statement
A salesman wants to visit a set of cities exactly once and return to the starting city, traveling
the minimum possible cost (distance/time).
Formally:
Given a complete weighted graph G=(V,E)G = (V, E)G=(V,E), where VVV is the
set of cities and EEE is the set of edges with weights (distances),
Find the shortest Hamiltonian Cycle that visits each vertex once and returns to the
start.
Key Characteristics
1. Input:
o
Number of cities nnn
o
Cost matrix (distance between each pair of cities)
2. Output:
o The order of visiting cities that minimizes the total cost
o The minimum tour cost
3. Type:
o Combinatorial optimization
o NP-hard problem
Example
89
Suppose we have 4 cities and the cost matrix:
From/To A B C D
A 0 10 15 20
B 10 0 35 25
C 15 35 0 30
D 20 25 30 0
But the optimal tour may differ (we compute using algorithms).
Since TSP is NP-hard, exact algorithms are expensive for large nnn.
1. Brute Force
Use bitmasking + DP
Recurrence:
Applications of TSP
k center problem
Problem Statement
Given:
A set of n points (usually in a metric space with distances defined between every pair
of points).
An integer k (the number of centers).
Goal:
Choose k centers such that the maximum distance of any point to its nearest center
is minimized.
Example
Complexity
This guarantees that the maximum distance is at most 2 × OPT (where OPT is the optimal
solution).
Applications
Related Problems
91
k-means (minimizes average squared distance, not max distance).
k-median (minimizes sum of distances, not max distance).
Dominating set problem (special case of k-center).
Key Features
1. Initialization
2. Neighborhood Generation
3. Evaluation
4. Move/Update
5. Termination
1. Hill Climbing
2. Simulated Annealing
3. Tabu Search
4. Genetic Algorithms (GA)
Advantages
Disadvantages
92
Can get stuck in local optima.
Performance depends on the initial solution.
No guarantee of global optimum.
Simulated annealing
Key Idea
As T → 0, the algorithm behaves like hill climbing (accepting only better moves).
Algorithm Steps
93
Advantages
Disadvantages
Genetic algorithms
Key Concepts in GA
1. Population
2. Chromosome
3. Fitness Function
4. Selection
5. Crossover (Recombination)
6. Mutation
7. Generations
1. Initialize Population
2. Evaluate Fitness
3. Selection
4. Crossover
5. Mutation
6. Replacement
7. Termination
94
Advantages
Disadvantages
UNIT -6
Advanced Topics and Emerging Trends
Randomized Algorithms
A randomized algorithm uses random numbers (coin flips, random choices) during
execution to make decisions.
Unlike deterministic algorithms, which always give the same result for the same
input, randomized algorithms may behave differently on different runs.
Common Applications in DS
1. Randomized QuickSort
o Pivot chosen randomly to avoid worst-case (O(n^2)).
o Expected time: O(n log n).
2. Randomized Selection (QuickSelect)
o Finds k-th smallest element in expected O(n) time.
3. Randomized Hashing
o Hash functions with randomness reduce collision chances.
o Example: Universal hashing, Cuckoo hashing.
4. Randomized Primality Testing
95
Miller-Rabin, Fermat’s test used in cryptography.
o
5. Randomized Graph Algorithms
o Minimum cut (Karger’s Algorithm).
o Randomized algorithms for matching, spanning trees, etc.
6. Approximation Algorithms
o Use randomness to find near-optimal solutions in NP-hard problems.
o Example: Randomized rounding.
Advantages
Disadvantages
Real-World Examples
Monte Carlo algorithms sacrifice certainty for speed — they always run fast, but may
be wrong with low probability. Repetition makes them highly reliable.
Characteristics
1. Primality Testing
o Miller-Rabin test → checks if a number is prime.
96
o Runs in polynomial time, may wrongly classify a composite as prime with tiny
probability.
o Widely used in cryptography.
2. Minimum Cut Problem (Karger’s Algorithm)
o Uses random edge contractions to find graph minimum cut.
o Result may be wrong, but repeating increases correctness probability.
3. Polynomial Identity Testing
o Checks if two polynomials are identical by evaluating them at random points.
o Fast but has a chance of error.
4. Monte Carlo Integration (approximation)
o Used in approximation algorithms (e.g., estimating area, volume, or
probabilities).
5. Randomized Approximation Algorithms
o Many NP-hard problems (e.g., MAX-SAT, Vertex Cover) use Monte Carlo
approximation.
Complexity
Advantages
Disadvantages
Real-World Usage
Parallel Algorithm
97
Distributed Algorithms
1. Leader Election
o Nodes elect a coordinator in distributed systems (e.g., Bully Algorithm, Ring
Algorithm).
2. Consensus Algorithms
o Ensures all nodes agree on a value.
o Examples: Paxos, Raft, Byzantine Agreement.
3. Distributed Mutual Exclusion
o Algorithms to avoid race conditions (Ricart–Agrawala, Token-based
methods).
4. Spanning Tree Construction
o Distributed Minimum Spanning Tree (Gallager-Humblet-Spira algorithm).
5. Distributed Shortest Paths
o Bellman-Ford and Dijkstra adapted for networks.
Advantages
Parallel Algorithms
Faster execution.
Efficient use of multi-core systems.
98
Distributed Algorithms
High scalability.
Fault tolerance (system continues despite failures).
Essential for cloud computing, blockchain, and distributed databases.
Challenges
Parallel Algorithms
Synchronization overhead.
Load balancing across processors.
Distributed Algorithms
Real-World Application
PRAM Model
Components of PRAM
99
1. EREW PRAM (Exclusive Read, Exclusive Write)
o No two processors can read or write the same memory location
simultaneously.
o Most restrictive, easiest to implement.
2. CREW PRAM (Concurrent Read, Exclusive Write)
o Multiple processors can read the same memory cell at the same time.
o Only one processor can write at a time.
3. CRCW PRAM (Concurrent Read, Concurrent Write)
o Multiple processors can read and write the same memory cell simultaneously.
o Variants:
Common CRCW: All processors writing must write the same value.
Arbitrary CRCW: One arbitrary processor’s value is written.
Priority CRCW: The processor with highest priority writes.
Applications of PAM
Advantage
Limitations
100
Many subproblems are independent → can be solved simultaneously by different
processors.
Parallelization reduces execution time by distributing work.
Works well with PRAM model or multi-core processors.
1. Divide step:
o Assign different subproblems to different processors.
o Example: Splitting an array into two halves → each processor handles one
half.
2. Conquer step:
o Each processor solves its subproblem in parallel.
o If still large, subproblem is again split among processors (recursive
parallelism).
3. Combine step:
o Merge results (may need synchronization).
o Example: Merging sorted subarrays in Parallel Merge Sort.
Examples in DSA
Complexity
Advantages
Challenges
Load Balancing
101
Load Balancing is the process of distributing tasks/workload evenly across
processors or resources so that no single processor is overloaded while others
remain idle.
It is crucial in parallel and distributed algorithms, where multiple
processors/cores/computers cooperate to solve a problem.
Goal: maximize throughput, minimize execution time, and improve resource utilization.
Many DSA algorithms (sorting, searching, graph processing, matrix operations) are
implemented in parallel/distributed systems.
Unequal task distribution → idle processors → reduced efficiency.
Example: In Parallel Merge Sort, if one processor handles a huge subarray and others
get small chunks, performance suffers.
Applications in DSA
Parallel Sorting
Matrix Multiplication
Graph Algorithms
Hashing & Data Structures
102
Distributed Systems
Challenges
Streaming Algorithms
Streaming algorithms are designed to process large data streams where the input
is:
o Too large to store entirely in memory.
o Arrives sequentially and must be processed in one pass (or few passes).
They use small memory (sublinear in input size) and often produce approximate
answers instead of exact results.
Key Characteristics
1. Sampling
o Keep a random subset of data to approximate results.
o Example: Reservoir Sampling.
2. Sketching
o Maintain a compact summary (sketch) of data.
o Example: Count-Min Sketch for frequency estimation.
3. Sliding Window Models
o Process only the most recent data.
o Example: Network traffic monitoring over the last 10 minutes.
4. Hashing & Randomization
o Use hash functions for approximate counting.
o Example: Flajolet-Martin algorithm for distinct elements.
1. Reservoir Sampling
o Selects a random sample of k items from a stream of unknown length.
2. Morris Algorithm
o Probabilistic counting algorithm (logarithmic space for counters).
3. Flajolet-Martin Algorithm
103
oEstimates the number of distinct elements in a stream.
4. Count-Min Sketch
o Estimates the frequency of elements with limited memory.
5. Bloom Filters
o Probabilistic data structure to test set membership with false positives allowed.
Applications
Advantages
Limitations
This model is widely used in streaming algorithms for handling Big Data, IoT, and network
analytics.
104
1. Insertion-only Model
o Stream contains only insertions (new data items).
o Example: Counting website visitors, accumulating transaction records.
2. Cash Register Model
o Generalization of insertion-only.
o Each item has an associated positive weight.
o Example: Monitoring sales revenue, packet sizes in a network.
3. Turnstile Model
o Stream allows both insertions and deletions.
o Each update modifies the frequency of an item (can increase or decrease).
o Example: Tracking active users (login = +1, logout = –1).
4. Sliding Window Model
o Only the most recent W elements of the stream are considered.
o Useful when recent data is more relevant than old data.
o Example: Monitoring website hits in the last 10 minutes.
Search Engines
Network Security
Social Media Analytics
Financial Systems
IoT & Sensors
Advantages
Limitations
105
Both are key techniques in streaming algorithms for handling massive, real-time data
efficiently.w
When dealing with large data streams (Big Data, real-time analytics), storing and
processing the entire dataset is impossible.
Both are widely used in streaming algorithms for approximation with limited memory.
Sampling in DSA
Definition: Sampling selects a small subset of items from a stream or dataset while
preserving statistical properties.
Techniques
1. Reservoir Sampling
o Randomly selects kkk items from a stream of unknown length.
o Guarantees uniform probability for each item.
2. Random Sampling with Replacement
o Each item has equal chance of being chosen, independent of previous
selections.
3. Priority Sampling / Weighted Sampling
o Items with higher weights are more likely to be chosen.
Applications
Sketching in DSA
1. Count-Min Sketch
o Approximates frequency of items in a stream.
o Uses hash functions + counters.
o Example: Finding most frequent queries in Google search logs.
2. Bloom Filters
o Probabilistic data structure to test set membership.
o May give false positives but never false negatives.
o Example: Checking if an element has appeared before in a stream.
3. Flajolet-Martin Algorithm (FM Sketch)
o Estimates number of distinct elements.
106
o
Uses hashing and position of least significant 1-bit.
4. HyperLogLog
o Improved distinct element counting.
o Used in databases and analytics engines.
Applications
Network monitoring
Search engines
Big data analytics
Distributed systems
Advantages
Limitations
Frequency Moments
107
(Here, we count each element that appears at least once.)
Applications
Exact computation: Use a hash table to store frequencies → O(n) time, O(m) space.
But this is impractical for large streams (big data) due to memory limits.
Approximate computation (popular in streaming algorithms):
o F₀: HyperLogLog algorithm, Flajolet-Martin algorithm
o F₂: Alon-Matias-Szegedy (AMS) algorithm
o Heavy hitters / F∞: Count-Min Sketch
These algorithms use sublinear space and probabilistic guarantees to estimate frequency
moments.
Summary Table
Moment Formula Meaning Example
∑i=1m[fi>0]\sum_{i=1}^{m} [f_i > Distinct Stream: [a, b, a, c] → F₀ =
F₀
0]∑i=1m[fi>0] elements 3
Total Stream: [a, b, a, c] → F₁ =
F₁ ∑i=1mfi\sum_{i=1}^{m} f_i∑i=1mfi
elements 4
F₂ ∑i=1mfi2\sum_{i=1}^{m} f_i^2∑i=1m Measure of Stream: [a, b, a, c] → F₂ =
108
Moment Formula Meaning Example
fi2 skew 2² + 1² + 1² = 6
Most Stream: [a, b, a, c] → F∞
F∞ max(f_i)
frequent =2
Boyer-Moore Algorithm
Idea: Compare from right to left and skip sections of text intelligently.
Heuristics:
1. Bad Character Rule: Shift pattern past the mismatched character.
2. Good Suffix Rule: Shift pattern based on matched suffix.
Time Complexity: O(n) on average; O(n × m) worst case.
Use Case: Fast searching in English text, DNA sequences.
Rabin-Karp Algorithm
Aho-Corasick Algorithm
109
Builds an automaton for all patterns → scans text in O(n + total pattern length +
output size)
Use Case: Spam filtering, DNA motif search, dictionary matching.
Knuth-Morris-Pratt Variants
Applications
Suffix Trees
A suffix tree is a compressed trie of all suffixes of a string SSS of length nnn.
Example:
Let S="banana$"S = "banana\$"S="banana$" (we append $ to mark the end).
Suffixes of SSS:
banana$
anana$
nana$
ana$
na$
a$
$
A suffix tree organizes all these suffixes in a trie, compressing common prefixes.
Key Features
110
Search for a pattern PPP: O(m), where m = length of P
Longest repeated substring: O(n)
Longest common substring between two strings: O(n + m) with generalized suffix
tree
Space: O(n) with Ukkonen’s online construction algorithm
1. Nodes:
o Internal nodes: represent branching points of common prefixes.
o Leaf nodes: represent suffix indices.
2. Edges:
oLabeled with substrings of S.
oCompressed: instead of one character per edge, edges can represent multiple
characters.
3. Suffix Links (used in construction):
o Link from a node representing string xαx\alphaxα to a node representing
α\alphaα
o Crucial for Ukkonen’s linear-time construction.
Naive Approach: Insert all suffixes into a trie → O(n²) time, O(n²) space.
Ukkonen’s Algorithm (online construction):
o Builds suffix tree in O(n) time and O(n) space.
o Uses suffix links and implicit suffix trees.
Applications
Application How Suffix Tree Helps
Substring search Check if P exists in T in O(m)
Longest repeated substring Find the deepest internal node
Longest common substring Build generalized suffix tree for two strings
String compression Detect repeated patterns
DNA sequence analysis Search patterns in genomes efficiently
Example
Text: banana$
Suffixes:
Suffix Arrays
Example:
Let S = "banana$". Suffixes:
0: banana$
1: anana$
2: nana$
3: ana$
4: na$
5: a$
6: $
Suffix Index
$ 6
a$ 5
ana$ 3
anana$ 1
banana$ 0
na$ 4
nana$ 2
Key Properties
112
Construction of Suffix Arrays
A. Naive Approach
Generate all suffixes, sort them → O(n² log n) (because comparing strings is O(n)).
B. Efficient Algorithms
To find a pattern PPP of length mmm in text TTT using a suffix array:
Time Complexity:
O(m log n) for each search (O(m) to compare + O(log n) for binary search)
Definition: LCP[i] = length of longest common prefix between suffixes SA[i] and
SA[i-1].
Use: Helps in finding repeated substrings, longest common substring, etc.
Construction: Kasai’s algorithm → O(n) time.
Applications
Application How Suffix Array Helps
Pattern search Binary search in O(m log n)
Longest repeated substring Use LCP array
Longest common substring Compare LCPs in generalized SA for two strings
Data compression Detect repeated substrings
Genome analysis Efficient substring queries in DNA sequences
Idea
1. Preprocess Pattern:
o LPS[i] = length of the longest proper prefix which is also a suffix for
pattern[0..i].
2. Search in Text:
o Compare pattern and text character by character.
o If mismatch occurs, use LPS to skip ahead in pattern.
Time Complexity
O(n + m)
O(m) to build LPS, O(n) to search.
Z-Algorithm
Idea
Steps
Time Complexity
O(n + m)
Idea
Steps
Time Complexity
Average: O(n + m)
Worst case: O(n × m) (rare, depends on collisions)
114
Suffix Tree / Suffix Array Based Matching
Applications
115