Comprehensive Data Structures and Algorithms Study Guide
vg Course Structure and Examination Scheme
Academic Context:
Institution: Savitribai Phule Pune University
Program: Second Year of Computer Engineering and Computer Science and Engineering (2024 Course)
Course Code & Title: PCC-201-COM: Data Structures
Teaching and Examination Scheme:
Teaching Scheme: Theory 03 Hours/Week
Credits: 03 Credits
Examination Scheme:
Continuous Comprehensive Evaluation (CCE): 30 Marks
End-Semester Examination: 70 Marks
Unit-Wise Syllabus Breakdown:
Unit I (09 Hours): Introduction to Data Structures and Algorithms
Abstract Data Types (ADT), Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures.
Space complexity, Time complexity, Asymptotic notations (Big-O, Theta, Omega), Step count method, Analysis of programming constructs (Linear, Quadratic, Cubic, Logarithmic).
Algorithm design strategies: Divide and Conquer, Greedy strategy.
Case studies: E-commerce Product Sorting using Divide and Conquer; Google Calendar event scheduling using Greedy strategy.
Unit II: Arrays, Searching, and Sorting
1D, 2D, and Multidimensional Arrays, Row-Major and Column-Major order storage representations.
Sparse Matrix representation (Triplet format) and operations.
Searching: Linear Search, Binary Search, Fibonacci Search, Indexed Sequential Search.
Sorting: Bubble Sort, Insertion Sort, Selection Sort, Quick Sort, Merge Sort.
Case study: Social Network Adjacency Matrix using sparse representations.
Unit III (09 Hours): Stacks, Queues, and Linked Lists
Stack operations, Multiple Stacks, Expression conversion (Infix, Prefix, Postfix) and Postfix evaluation.
Linear Queue, Circular Queue, Priority Queue (Ascending and Descending order) with Heap implementation.
Linked Lists: Singly Linked List, Doubly Linked List, Circular Singly Linked List, Circular Doubly Linked List.
Case studies: Stack and Queue implementation using Linked Lists.
Unit IV (09 Hours): Hashing
Hash tables, Hash functions (Division, Multiplication, Universal), Bucket, Collision, Probe, Synonym, Overflow.
Open Hashing (Separate Chaining) versus Closed Hashing (Open Addressing with Linear, Quadratic, and Double Hashing probing).
Load factor (), Load density, Rehashing, Perfect Hashing (Static and Minimal).
Extendible Hashing, Directory and Bucket splitting.
Case study: Dictionary Application using Hash Tables.
Unit V (09 Hours): Graphs and Trees
Graphs: Directed, Undirected, Weighted, Bipartite graphs; Adjacency Matrix and Adjacency List representations.
Traversals: Breadth-First Search (BFS) using Queue; Depth-First Search (DFS) using Stack.
Minimum Spanning Tree (MST): Kruskal's Algorithm and Prim's Algorithm.
Trees: General trees, Binary tree properties, Linked and Sequential array representations.
Binary Tree Traversals: Inorder, Preorder, Postorder; Binary Search Trees (BST) insertion, search, and deletion.
Expression Trees; Huffman Trees.
Case studies: GPS/Navigation System (weighted graph modeling); ZIP/GZIP File Compression using Huffman Trees.
Introduction to Data Structures and Algorithmic Analysis
Fundamental Concepts of Data Structures:
Data structures serve as the core foundation for computer science algorithms, enabling programmers to manipulate, store, and organize data efficiently.
Software performance relies heavily on selecting appropriate data structures to ensure rapid data storage and retrieval.
Selecting the optimal data structure is among the most critical architectural decisions in system design.
Abstract Data Types (ADT):
Definition: An Abstract Data Type is a conceptual mathematical model that specifies a set of data items and a collection of operations allowable on that data, without dictating how the operations are implemented or how the data is laid out in physical memory.
Abstraction Principle: ADTs separate the interface (what operations can be executed) from the underlying implementation (how algorithms and memory layouts accomplish those operations), thereby providing essential details while concealing low-level complexity.
Classification of Data Structures:
Primitive Data Structures: Basic building blocks defined natively by programming languages (e.g., integers, floats, characters, pointers).
Non-Primitive Data Structures: Complex structures derived from primitive types, subdivided into:
Linear Data Structures: Elements are arranged in sequential, adjacent order where every element has a unique predecessor and successor (except the first and last). Examples include Arrays, Stacks, Queues, and Linked Lists.
Non-Linear Data Structures: Elements form multi-level, hierarchical, or interconnected relationships. Examples include Trees and Graphs.

Static versus Dynamic Data Structures:
Static Data Structures: Memory allocation occurs at compile time with a fixed structural capacity. While the content within elements can be altered, the overall memory bounds cannot expand or contract dynamically (e.g., standard fixed arrays).
Dynamic Data Structures: Memory is allocated during execution time (runtime) from heap memory. The structure expands or contracts on demand via pointer manipulation (e.g., Linked Lists, dynamic trees).
Persistent versus Ephemeral Data Structures:
Ephemeral Data Structures: Ordinary, short-lived data structures where modifications occur in-place, overwriting prior states. Once modified, historic configurations are irrevocably lost.
Persistent Data Structures: Data structures that systematically preserve historic versions of themselves across state changes, functioning immutably without in-place destruction.
Partially Persistent: All historic versions remain accessible for read/query operations, but only the most recent version can be mutated.
Fully Persistent: Every historic version can be both queried and mutated, creating a branching history tree.
Confluently Persistent: Operations can merge two or more historic versions to synthesize a completely new version.
Linked List Concatenation Example: When concatenating list onto under persistence, a deep copy of list nodes can be duplicated to preserve the pristine state of and , or an optimized structural sharing method is employed where one list is traversed and its tail nodes point to the existing nodes of the other list without modifying the original references.

Algorithmic Complexity, Asymptotic Notations, and Design Strategies
Algorithms and Performance Analysis:
Algorithm: A finite, step-by-step sequence of unambiguous instructions designed to solve any valid instance of a computational problem and produce desired outputs from specified inputs.
Program: The concrete encoding of an abstract algorithm into an executable programming language.
Performance Metric: Algorithms solving identical problems are benchmarked based on computing resource utilization, measured via Time Complexity and Space Complexity as functions of input size .
Order of Growth Hierarchy:
The asymptotic growth rates of algorithmic runtimes scale according to the following mathematical order: where represents any positive constant.
Space Complexity Analysis:
Defined as the total memory space required by an algorithm to execute to completion.
Constant Space Complexity Example:
c int square(int a) { return a * a; } The parameter
aoccupies , and the return value consumes .Total memory required is , which remains fixed regardless of the magnitude of
a, yielding constant space complexity.
Linear Space Complexity Example:
c int sum(int A[], int n) { int sum = 0, i; for(i = 0; i < n; i++) sum = sum + A[i]; return sum; } Array parameter
A[]requires .Integer parameter
nrequires .Local integer variables
sumandirequire each ( total).The return value requires .
Total memory required evaluates to . As scales, space demand increases linearly, demonstrating linear space complexity.
Asymptotic Notations:
Big-O Notation () — Upper Bound:
Represents the formal worst-case time complexity, guaranteeing that the execution time will not exceed a defined threshold for large inputs.
Mathematical Definition: if and only if there exist positive constants and such that:
Big-Omega Notation () — Lower Bound:
Defines the best-case execution time, establishing the baseline minimum computational time required by an algorithm.
Mathematical Definition: if and only if there exist positive constants and such that:
Theta Notation () — Tight Bound (Average Bound):
Encapsulates the function within tight upper and lower bounds, characterizing the exact average growth rate.
Mathematical Definition: if and only if there exist positive constants , , and such that:
Step Count Method for Complexity Determination:
An analytical approach that tallies the frequency of elementary instructions (assignments, arithmetic operations, comparisons, function calls) executed during an algorithm's lifecycle.
Worked Step Count Table for Linear Array Summation:
c Algorithm Sum(a, n) { sum = 0; for i = 1 to n do { sum = sum + a[i]; } return sum; } Line
sum = 0;: Step count per execution = , Frequency = , Total steps = .Line
for i = 1 to n do: Step count per execution = , Frequency = , Total steps = .Line
sum = sum + a[i];: Step count per execution = , Frequency = , Total steps = .Line
return sum;: Step count per execution = , Frequency = , Total steps = .Total cumulative step count: .
Asymptotic complexity: .
Analysis of Programming Constructs:
Constant Time (): Independent of input size. Example:
A = A + B;.Linear Time (): Execution scales proportionally with .
c for (i = 1; i <= n; i++) a = a * b;
Quadratic Time (): Nested loops where execution scales with .
c for (i = 1; i <= n; ++i) for (j = 1; j <= n; j++) a = a * b; Cubic Time (): Triple-nested loops scaling with .
c for (i = 1; i <= n; ++i) for (j = 1; j <= n; j++) for (k = 1; k <= n; k++) a = a * b; Logarithmic Time (): Iteration variable increases or decreases exponentially by multiplication or division factors.
c for (i = 1; i <= n; i = i * 2) a = a * b; // or for (i = n; i >= 1; i = i / 2) a = a * b; Algorithm Design Strategies:
Divide and Conquer:
Divides a large problem into independent, smaller sub-problems recursively.
Conquers the sub-problems by solving them recursively (or directly at base cases).
Combines sub-problem solutions into an optimal global solution.
Canonical algorithms: Binary Search, Merge Sort, Quick Sort.
Greedy Strategy:
Constructs a solution piece by piece, always choosing the immediate, locally optimal step without backtracking.
Objective is to achieve a global optimum through locally optimal choices.
Canonical applications: Kruskal's Minimum Spanning Tree, Prim's Minimum Spanning Tree, Dijkstra's Shortest Path, Fractional Knapsack, Traveling Salesperson approximations.
Arrays, Storage Representations, and Matrix Operations
Array Fundamentals:
Definition: A linear, homogeneous data structure that allocates contiguous blocks of physical memory to store elements of identical data types, referenced through index offsets from to .
Key Characteristics: Fixed capacity determined at initialization (static memory allocation), direct random access in time complexity, high memory locality for hardware caching efficiency.

Array Operations and Complexities:
Traversal: Sequentially accessing each element from index to for evaluation, printing, or aggregation; Time Complexity: .
Insertion: Inserting a value at a designated index. Requires right-shifting elements from down to index .
Best Case (insertion at end):
Worst Case (insertion at index ):
Deletion: Removing an item at index , followed by left-shifting all subsequent elements from to to close the void; Time Complexity: .
Updating: Directly indexing and assigning a new value to
arr[k]; Time Complexity: .Searching: Scanning for a target value using Linear Search () or Binary Search ( for sorted data).
Memory Address Calculation for 1D Arrays:
In a one-dimensional array, the physical memory address for the element at index is computed via the formula:
Example: Given a base address of and an integer type size of :
Index :
Index :
Index :
Index :

Multidimensional Arrays and Storage Orders:
2D Arrays: Represent matrix structures configured in rows and columns (e.g.,
int arr[nrows][ncols]).Row-Major Order: Array elements are flattened sequentially across memory row by row. All elements of row are stored contiguously, followed by row , then row .
Column-Major Order: Elements are stored column by column. All elements of column are laid out in contiguous memory, followed by column , through column .

nD Arrays: Extended dimensions beyond matrices (e.g.,
int tensor[3][4][2]), used in tensor computations, deep learning feature spaces, 3D graphics rendering, and physics simulations.Sparse Matrix Representation:
Definition: A matrix in which the overwhelming majority of values are zeros. Allocating full 2D grids for sparse matrices causes substantial memory waste and unnecessary computations.
Triplet Representation: Stores only non-zero elements using a compact 2D array format with three explicit metadata columns:
[Row, Col, Value].Triplet Mapping Example: | Row Index | Column Index | Non-Zero Value | | :---: | :---: | :---: | | 0 | 2 | 5 | | 1 | 0 | 8 | | 3 | 1 | 6 |
Applications: Adjacency matrices of sparse graph networks, natural language processing feature vectors, image compression algorithms.
Searching and Sorting Algorithms
Searching Algorithms:
Linear (Sequential) Search:
Traverses an array element-by-element from the first to the final position.
Operates seamlessly on both unsorted and sorted datasets.
Time Complexity: Best case (target located at index ), Worst case (target located at index or entirely absent).
Binary Search:
Requires data to be pre-sorted.
Uses a divide-and-conquer strategy by comparing the search target against the median element (). If the target is smaller, the upper half is discarded; if larger, the lower half is eliminated.
Time Complexity: .

Fibonacci Search:
A divide-and-conquer searching method that uses Fibonacci numbers () to determine split points within a sorted array.
Relies on basic addition and subtraction rather than division operators, conferring performance advantages on architectures with slower hardware division.
Uses offset indexing: .
Time Complexity: .
Indexed Sequential Search:
Combines primary index tables with sequential file blocks.
An auxiliary index table stores sorted pointer markers into the primary records. Searches rapidly isolate the target cluster via index lookup before executing a localized linear search across the bounded block.
Core Sorting Principles:
Stability: A sorting algorithm is defined as stable if it preserves the relative order of duplicate elements possessing identical keys from input to output.
Efficiency: Evaluated based on comparative time complexity ( vs. ) and auxiliary space complexity (in-place vs. extra buffer allocation).
Elementary Sorting Algorithms:
Bubble Sort:
Iteratively compares adjacent pairs and swaps them if out of order, causing the largest unsorted value to bubble up to its final position with each pass.
Time Complexity: ; Auxiliary Space: ; Stability: Stable.
Insertion Sort:
Builds the sorted array incrementally by consuming one unsorted item at a time and shifting larger preceding values rightward to insert it into its correct position.
Exceptionally efficient for small datasets or nearly sorted arrays.
Time Complexity: ; Auxiliary Space: ; Stability: Stable.
Selection Sort:
Iterates through the unsorted array to locate the minimum element and swaps it with the element at the beginning of the unsorted segment.
Time Complexity: ; Auxiliary Space: ; Stability: Not Stable.
Advanced Sorting Algorithms:
Quick Sort:
Selects a pivot element and partitions the array into two sub-arrays: elements smaller than the pivot and elements greater than the pivot.
Recursively sorts the partitions.
Time Complexity: Average case , Worst case (occurring with highly unbalanced partitions); Stability: Not Stable.
Merge Sort:
Recursively splits the array into two halves until single-element sub-arrays are achieved, then merges sorted sub-arrays into a unified sequence.
Time Complexity: across all cases (best, average, worst); Auxiliary Space: ; Stability: Stable.

Stacks: Concept, Operations, and Multiple Stacks
Stack ADT Definition:
A linear data structure that operates under the Last In, First Out (LIFO) access paradigm.
Elements can only be inserted and removed from a single end called the
topof the stack.Components:
TOP: Pointer variable maintaining the current array index of the topmost item.Element: The data payload contained at a stack slot.MaxStack/MAX: The maximum capacity or total allocated size of the stack.
Stack Operations:
push(item): Inserts an element onto the top of the stack.pop(): Removes and returns the topmost element, provided the stack is not empty.peek(): Returns the topmost element without removing it.isEmpty(): Returns true ifTOP == -1, otherwise false.isFull(): Returns true ifTOP == MAX - 1, otherwise false.size(): Returns the total count of elements currently resident ().
Stack Primitive Algorithms:
Push Operation:
text if TOP == MAX - 1 then return "Overflow" endif TOP = TOP + 1 STACK[TOP] = item end
Pop Operation:
text if TOP == -1 then return "Underflow" endif item = STACK[TOP] TOP = TOP - 1 return item end

Multiple Stacks in a Single Array:
Solves fixed memory boundary limitations by partitioning a single unified array
STACK[n]between two separate stacks (Stack A and Stack B).Configuration:
Array size: (indices through ).
Stack A expands left-to-right starting from index , with
TOP_Ainitialized to .Stack B expands right-to-left starting from index , with
TOP_Binitialized to ().Condition for Stack Overflow:
TOP_A + 1 == TOP_B.Combined capacity remains bounded by , allowing flexible space sharing when stack growth rates are asymmetrical.

General Applications of Stacks:
Expression conversion (Infix to Postfix/Prefix) and Postfix evaluation.
Validating balanced nested parentheses and parsing source code syntax.
String reversal and decimal-to-binary number conversion.
Call stack tracking for subprogram/function execution and recursion simulation.
Backtracking algorithms (graph exploration, game states, maze solving).
Polish Notations, Expression Conversion, and Evaluation
Types of Arithmetic Notations:
Infix Notation: Operators are positioned between operands (e.g., ). While intuitive for humans, parsing requires parenthetical disambiguation and complex lookahead logic for machines.
Prefix Notation (Polish Notation): Operators precede their respective operands (e.g., ).
Postfix Notation (Reverse Polish Notation — RPN): Operators follow their respective operands (e.g., ). Completely eliminates the need for parentheses and precedence rules during machine evaluation.
Operator Precedence and Associativity Table: | Rank | Operator Type | Operators | Associativity | | :---: | :---: | :---: | :---: | | 1 | Postfix |
(),[],->,.,++,--| Left to Right | | 2 | Unary |+,-,!,~,++,--,(type)*,&,sizeof| Right to Left | | 3 | Multiplicative |*,/,%| Left to Right | | 4 | Additive |+,-| Left to Right | | 5 | Shift |<<,>>| Left to Right | | 6 | Relational |<,<=,>,>=| Left to Right | | 7 | Equality |==,!=| Left to Right | | 8 | Bitwise AND |&| Left to Right | | 9 | Bitwise XOR |^| Left to Right | | 10 | Bitwise OR ||| Left to Right | | 11 | Logical AND |&&| Left to Right | | 12 | Logical OR |||| Left to Right | | 13 | Conditional / Assignment |?:,=,+=,-=,*=,/=,%=,>>=| Right to Left |Algorithm for Infix to Postfix Conversion:
Scan tokens of the infix expression from left to right.
If the token is an operand, append it directly to the output postfix string.
If the token is an opening parenthesis
(, push it onto the operator stack.If the token is an operator:
If the stack is empty or contains an opening parenthesis on top, push the operator.
If the operator has higher precedence than the operator on top of the stack, push it.
Otherwise, pop operators with greater or equal precedence to the output, then push the current operator.
If the token is a closing parenthesis
): Pop operators from the stack to the output until an opening parenthesis(is encountered; discard both parentheses.Repeat until the input is exhausted, then pop all remaining operators from the stack to the output.
Worked Example — Infix to Postfix Conversion:
Expression:
Trace Steps:
Token
2: Stack[], Output:2Token
*: Stack[*], Output:2Token
3: Stack[*], Output:2 3Token
/: Stack[/](pops*), Output:2 3 *Token
(: Stack[/, (], Output:2 3 *Token
2: Stack[/, (], Output:2 3 * 2Token
-: Stack[/, (, -], Output:2 3 * 2Token
1: Stack[/, (, -], Output:2 3 * 2 1Token
): Stack[/], Output:2 3 * 2 1 -Token
+: Stack[+](pops/), Output:2 3 * 2 1 - /Token
5: Stack[+], Output:2 3 * 2 1 - / 5Token
*: Stack[+, *], Output:2 3 * 2 1 - / 5Token
3: Stack[+, *], Output:2 3 * 2 1 - / 5 3End of Input: Pop
*, then+Final Postfix Expression:
2 3 * 2 1 - / 5 3 * +
Algorithm for Postfix Evaluation:
Scan the postfix string from left to right token by token.
If the token is an operand, push its numerical value onto the evaluation stack.
If the token is an operator, pop two operands:
operand1 = pop()(top item) andoperand2 = pop()(second item).Compute
result = operand2 (operator) operand1.Push
resultback onto the stack.At string termination, pop the final remaining value as the computed result.
Worked Evaluation Trace for Postfix
5 3 + 8 2 - *:Read
5:push(5), Stack:[5]Read
3:push(3), Stack:[5, 3]Read
+:val1 = pop() = 3,val2 = pop() = 5;result = 5 + 3 = 8;push(8), Stack:[8]Read
8:push(8), Stack:[8, 8]Read
2:push(2), Stack:[8, 8, 2]Read
-:val1 = pop() = 2,val2 = pop() = 8;result = 8 - 2 = 6;push(6), Stack:[8, 6]Read
*:val1 = pop() = 6,val2 = pop() = 8;result = 8 * 6 = 48;push(48), Stack:[48]End marker: Final popped result is
48.
Infix to Prefix Conversion Algorithm:
Step 1: Reverse the infix expression string. Convert all
(to)and all)to(.Step 2: Convert the reversed expression to a modified postfix form (only popping operators from the stack that have strictly greater precedence).
Step 3: Reverse the resulting postfix expression to yield the final prefix string.
Example:
A + (B * C)reverses to(C * B) + APostfix:C B * A +Reversed to prefix:+ A * B C.
Prefix to Postfix Conversion Algorithm:
Scan symbols from right to left.
If an operand is read, push it onto the stack.
If an operator is read, pop two strings:
op1 = pop()andop2 = pop(). Construct the stringop1 + op2 + operatorand push it back onto the stack.The final item remaining on the stack is the postfix expression.
Queues, Circular Queues, and Priority Queues
Linear Queue ADT:
An ordered linear data structure operating under the First In, First Out (FIFO) principle.
Insertions occur at the
REARnode (enqueue), while deletions take place at theFRONTnode (dequeue).Core Operations:
enqueue(x): Adds itemxatREAR.dequeue(): Removes the element atFRONT.getFront(): Inspects the front item without deletion.getRear(): Inspects the rear item without deletion.isFull(): Validates if the queue has reached capacity.isEmpty(): Validates if the queue contains zero elements.size(): Returns total item count.Primary Limitation of Linear Queues: Once elements are dequeued, the space before
FRONTbecomes unusable in a static array.REARcan reach capacity while preceding slots remain empty, causing false overflow conditions.
Circular Queue Data Structure:
Resolves linear queue space wastage by conceptually linking the final array slot back to the first slot, forming a ring.
Circular Increment: Utilizes modulo arithmetic: .

Queue Full Boundary Conditions:
Case 1:
FRONT == 0 && REAR == SIZE - 1Case 2:
FRONT == REAR + 1
Circular Enqueue Algorithm:
Check if queue is full using the two conditions above.
If
FRONT == -1, initializeFRONT = 0.Set
REAR = (REAR + 1) % SIZE.Assign
QUEUE[REAR] = data.
Circular Dequeue Algorithm:
Check if
FRONT == -1(underflow).Retrieve
data = QUEUE[FRONT].If
FRONT == REAR(last remaining element removed), resetFRONT = -1andREAR = -1.Otherwise, advance
FRONT = (FRONT + 1) % SIZE.
Priority Queue ADT:
A queue variant where each element has an assigned priority value; elements with higher priorities are dequeued before lower-priority elements.
Elements of equal priority are dequeued according to standard FIFO ordering.
Types of Priority Queues:
Ascending Order Priority Queue: Lower numerical values correspond to higher scheduling priority (e.g., is highest priority, is lowest).
Descending Order Priority Queue: Higher numerical values correspond to higher scheduling priority.
Implementation Mechanisms: Arrays, Linked Lists, Binary Search Trees, and Heaps.
Heaps provide the most computationally efficient representation for priority queues.
Heap Priority Queue Operations:
Insertion: The new element is placed at the next available leaf position in the complete tree and bubbles upward ("heapifies up") by comparing and swapping with parent nodes until the heap invariant is restored.
Deletion: The root element (maximum in a max-heap) is extracted. The last leaf element replaces the root and bubbles downward ("heapifies down") by comparing and swapping with its larger child until the heap property is restored.

Linked Lists: Singly, Doubly, and Circular Implementations
Linked List Fundamentals:
A dynamic linear collection of nodes allocated non-contiguously in memory, connected sequentially via pointers.
Node Structure: Contains a
datafield and one or more pointer/link fields storing addresses of adjacent nodes.Terminologies:
head: Pointer identifying the entry/first node of the list.NULL: Pointer value indicating the end of a chain or an empty list.
Singly Linked List (SLL):
Each node contains a single address pointer linking to the succeeding node.
Traversal is strictly unidirectional (forward).
C Node Definition:
c struct node { int data; struct node *next; }; SLL Insertion Operations:
At Beginning: Allocate
newNode; setnewNode->next = head; sethead = newNode.At End: Allocate
newNode; setnewNode->next = NULL; traverse pointertempuntiltemp->next == NULL; settemp->next = newNode.After Specified Node: Traverse to target node; set
newNode->next = temp->next; settemp->next = newNode.SLL Deletion Operations:
At Beginning: Set
head = head->next.At End: Traverse to second-to-last node where
temp->next->next == NULL; settemp->next = NULL.After Position / Middle: Traverse to node before target; set
temp->next = temp->next->next.SLL Concatenation: Traverse list 1 until
curr->next == NULL, then assigncurr->next = head2.
Doubly Linked List (DLL):
Nodes store two pointers:
prev(pointing to the predecessor) andnext(pointing to the successor).Enables bidirectional traversal (forward and backward).
C Node Definition:
c struct node { struct node *prev; int data; struct node *next; };
Memory Representation Table for DLL: | Memory Address | Data | Prev Pointer | Next Pointer | | :---: | :---: | :---: | :---: | | 1 | 13 | -1 (NULL) | 4 | | 4 | 15 | 1 | 6 | | 6 | 19 | 4 | 8 | | 8 | 57 | 6 | -1 (NULL) |
Head pointer references starting address
1.
DLL Insertion in Between Two Nodes:
cpp newNode->next = prev_node->next; prev_node->next = newNode; newNode->prev = prev_node; if (newNode->next != NULL) newNode->next->prev = newNode; DLL Deletion (Target Node
del_node):cpp if (*head == del_node) *head = del_node->next; if (del_node->prev != NULL) del_node->prev->next = del_node->next; if (del_node->next != NULL) del_node->next->prev = del_node->prev; free(del_node);

Singly vs. Doubly Linked List Comparison: | Feature | Singly Linked List | Doubly Linked List | | :--- | :--- | :--- | | Pointers per node | Single pointer (
next) | Two pointers (prev,next) | | Traversal Direction | Unidirectional (forward only) | Bidirectional (forward and backward) | | Memory Consumption | Lower memory overhead per node | Higher memory overhead (extra pointer) | | Deletion Complexity | without previous pointer | if pointer to target node is given | | Backward Search | Impossible without full restart | Can search from tail backward | | Primary Use Cases | Stacks, simple queues | Deques, complex caches, binary tree backbones |Circular Linked Lists:
Singly Circular Linked List: The
nextpointer of the final node loops back to reference the first node (head). EliminatesNULLpointer termination.Doubly Circular Linked List: Two-way circular connection: the last node's
nextreferences the first node, and the first node'sprevreferences the last node. Allows constant-time jumps between head and tail in either direction.

Hash Tables, Collision Resolution, and Overflow Handling
Hash Table Fundamentals:
A data structure that maps keys to values, delivering average-case constant time complexity for insertions, lookups, and deletions.
Operates by passing keys through a mathematical hash function to compute integer bucket indices in an array.
Properties of an Optimal Hash Function:
Uniform Distribution: Disperses keys evenly across the array capacity to minimize cluster formation.
Determinism: The same input key must consistently map to the identical index.
Speed: Must compute hash values rapidly with minimal CPU overhead.
Bit Utilization: Efficiently incorporates all bits of the input key to enhance entropy.
Common Hash Function Architectures:
Division Method:
Multiplication Method: Uses fractional parts of key multiplications by constants (Knuth's method).
Universal Hashing: Selects hash functions at random from a family of functions to prevent worst-case distribution attacks.
Core Hashing Terminology:
Bucket (Slot): The physical array index storing key-value entries.
Collision: Occurs when two distinct keys evaluate to the identical hash index.
Synonym: Distinct keys that map to the exact same hash bucket.
Probe: The step-by-step examination of subsequent slots during open addressing searches.
Overflow: Occurs when a bucket exceeds its fixed storage capacity.
Load Density: The average number of elements stored per bucket.
Load Factor (): Ratio of total keys stored () to total bucket capacity ():
Rehashing: Allocating a larger table (often double the size) and re-inserting all existing keys using a revised hash function once crosses a defined threshold (e.g., ).
Collision Resolution Strategies:
Open Hashing (Separate Chaining):
Each bucket maintains a linked list of entries that map to that index.
Can accept more elements than the table's total bucket count ().
Deletions are straightforward linked list pointer manipulations.
Trade-off: Extra memory overhead for pointers; cache performance degrades due to scattered allocations.
Closed Hashing (Open Addressing):
All entries are stored directly in the main table array.
When collisions occur, the algorithm probes alternative slots:
Linear Probing: Sequentially checks adjacent slots:
Quadratic Probing: Offsets probe steps quadratically:
Double Hashing: Uses a secondary hash function to calculate dynamic step sizes.
Requires . Deletions require special tombstones/markers to preserve probe sequences.
Open Addressing versus Separate Chaining Comparison: | Attribute | Open Addressing | Separate Chaining | | :--- | :--- | :--- | | Storage Model | Directly inside array | Buckets point to external lists | | Memory Overhead | Minimal (no pointers) | Higher (pointer overhead per node) | | High Load Behavior | Degrades rapidly via clustering | Degrades gracefully into longer lists | | Deletion Operation | Complex (requires deleted flags) | Simple list node deletion | | Total Capacity | Strictly bounded by array slots | Unbounded (chains expand infinitely) |
Extendible Hashing:
A dynamic hashing technique suitable for file systems and databases.
Employs an in-memory directory pointing to data buckets on disk.
Global Depth: The number of hash bits used by the central directory.
Local Depth: The number of hash bits used by individual buckets.
When a bucket overflows, only that bucket splits; the global directory doubles in size only when a bucket's local depth equals the global depth.
Graphs: Representations, Traversals, and Minimum Spanning Trees
Mathematical Graph Representation:
A graph is defined as an ordered pair , where is a finite set of vertices (nodes) and is a set of edges connecting pairs of vertices.
Example Graph Definition:

Graph Terminology:
Vertex / Node: An individual data point in the graph network.
Edge: A link connecting two vertices.
Loop: An edge that connects a vertex to itself (e.g., node in the figure above).
Degree of a Vertex: The total number of edges incident upon a vertex (e.g., the degree of vertex is ).
Adjacency: Two nodes connected by a direct edge are adjacent.
Path: A sequence of alternating vertices and edges connecting two nodes (e.g., path ).
Leaf / Pendant Vertex: A vertex possessing a degree of exactly .
Graph Classifications:
Undirected Graph: Edges are bidirectional and symmetrical; order of vertices in an edge does not matter.
Directed Graph (Digraph): Edges possess directionality, pointing from a source vertex to a target vertex.
Weighted Graph: Edges carry assigned numerical values representing weights, distances, costs, or traversal latencies.
Bipartite Graph (Bigraph): The vertex set can be partitioned into two disjoint sets, and , such that every edge connects a node in to a node in , with no edges connecting nodes within the same set.

Graph Storage Representations:
Adjacency Matrix: A 2D array of dimensions , where
matrix[i][j] = 1indicates an edge between vertex and vertex (or the edge weight for weighted graphs), and0indicates no connection.Adjacency List: An array of linked lists where each array index represents a vertex, pointing to a list of all vertices directly adjacent to it.

Graph Traversals:
Breadth-First Search (BFS):
Explores vertices level-by-level using a FIFO Queue.
Visits the starting node, enqueues all its unvisited adjacent neighbors, and repeats until the queue is empty.
Uses a
visitedarray to guarantee each vertex is visited at most once.Depth-First Search (DFS):
Traverses as deep as possible along each branch before backtracking, using a LIFO Stack (or recursion).
Visited children take precedence over siblings; backtracks to the previous node upon encountering dead ends.
Minimum Spanning Tree (MST):
A connected, acyclic subgraph spanning all vertices of an edge-weighted undirected graph with the minimum possible total edge weight.
Kruskal's Algorithm:
A greedy algorithm that processes edges globally in increasing order of weight.
Initialize an empty MST edge set.
Sort all edges across the graph in non-decreasing order of weights.
Greedily insert edges one by one into the spanning forest, rejecting any edge that would introduce a cycle.
Terminate when edges have been selected.
Applications: Network cabling design, electrical grids, tour routing.

Prim's Algorithm:
A vertex-centric greedy algorithm similar to Dijkstra's algorithm.
Start from an arbitrary root vertex, initializing a tree with this single node.
Evaluate all edges connecting tree vertices to unvisited vertices outside the tree.
Select the edge with the minimum weight and incorporate both the edge and the new vertex into the growing tree.
Repeat until all vertices are included in the MST.

Trees, Binary Search Trees, and Expression Trees
Tree Terminology:
A tree is an acyclic, non-linear hierarchical data structure defined by parent-child node relationships.
Root Node: The unique topmost node without parents.
Subtree: Any tree structure formed by a descendant node and its offspring.
Degree: The number of direct children possessed by a node (a leaf node has degree ).
Leaf Node: A terminal node with no children.
Height: The count of nodes on the longest path from the root to a leaf.
Depth: The number of edges from the root to a given node.

Binary Tree Properties and Variations:
A tree where every node has at most two children, designated as the left child and right child.
Full Binary Tree: Every node has either zero or two children.
Complete Binary Tree: All levels are completely filled, with the possible exception of the lowest level, which is filled from left to right.
Balanced Binary Tree: The height difference between the left and right subtrees of every node does not exceed .

Mathematical Properties:
Maximum leaf count at height :
Maximum total nodes in a binary tree of height :
Maximum nodes at level :
Total edges in a full tree of nodes:
Binary Tree Memory Representations:
Sequential (Array-Based) Representation: Stored in a 1D array where the root resides at
TREE[1].The left child of node is located at index .
The right child of node is located at index .
Maximum array capacity required: .
Linked Representation: Nodes are allocated dynamically via structures containing data and two pointers:
struct node* leftandstruct node* right.Binary Tree Traversals:
Inorder Traversal: Left Subtree Root Right Subtree
Preorder Traversal: Root Left Subtree Right Subtree
Postorder Traversal: Left Subtree Right Subtree Root
Binary Search Tree (BST):
An ordered binary tree enforcing the invariant that for any given node with key :
All keys in its left subtree are less than or equal to ().
All keys in its right subtree are strictly greater than ().

BST Operations:
Insertion: Compare the new value against the current node starting from the root; branch left if smaller, right if larger, repeating down to a vacant leaf position.
Search: Traverse left if target is smaller than the current node, or right if larger, achieving average search time.
Deletion: Handles three structural scenarios:
Case 1 (Leaf Node): Directly unlink and delete the node.
Case 2 (One Child): Bypass the node by linking its parent directly to its child.
Case 3 (Two Children): Find the node's in-order successor (smallest node in right subtree) or in-order predecessor, swap values, and delete that successor/predecessor node.
Expression Trees:
Binary trees representing arithmetic expressions, where internal nodes store operators and leaf nodes store operands.
Stack-Based Construction from Postfix Expression
4 5 + 5 3 - *:Read operands
4and5, create single-node trees, and push their pointers onto a stack.Read operator
+: create a+node, pop5as its right child and4as its left child; push the resulting subtree back onto the stack.Read operands
5and3: push their respective node pointers onto the stack.Read operator
-: create a-node, pop3as right child and5as left child; push the subtree onto the stack.Read operator
*: create a*root node, pop the-subtree as right child and the+subtree as left child; push the final root onto the stack.

Practical Applications and Case Studies
E-Commerce Product Sorting (Divide and Conquer):
Large-scale retail platforms manage millions of items that require dynamic sorting based on price, customer ratings, and relevance.
Divide-and-conquer sorting (Merge Sort) guarantees stable performance regardless of initial data order, providing predictable latency for large catalog queries.
Google Calendar Event Scheduling (Greedy Strategy):
Models interval scheduling problems to maximize the number of non-overlapping meetings fitted within a workday.
Greedy Algorithm:
Sort all proposed meeting intervals by their end times (or earliest start times).
Schedule the first compatible event.
Iteratively add subsequent events only if their start times do not conflict with the finish time of the most recently scheduled meeting.
Social Network Connection Graph (Sparse Matrix):
Social media platforms model user relationships as adjacency matrices where
matrix[i][j] = 1indicates friendship.With millions of users, the matrix is exceptionally sparse (consisting primarily of zeros). Storing relationships via triplet formats or adjacency lists optimizes memory usage and accelerates graph traversal for friend recommendations and community clustering.
Dictionary Application using Hash Tables:
Words and their corresponding definitions are stored as key-value pairs.
A hash function maps word strings to specific bucket indices.
Separate chaining handles collisions, guaranteeing near-instantaneous average lookup time for dictionary queries.
GPS and City Map Navigation (Weighted Graphs):
Road systems are modeled as weighted graphs where intersections represent vertices and road segments represent edges with weights corresponding to travel time, distance, or congestion.
Pathfinding algorithms calculate the most efficient routes between origins and destinations across the weighted network.
ZIP/GZIP File Compression (Huffman Trees):
Employs frequency-based encoding to compress arbitrary binary files.
Frequency Analysis: Tallies byte frequencies across the input dataset.
Tree Construction: Uses a priority queue to iteratively merge the two least-frequent character nodes into composite subtrees, producing a complete binary tree where frequent characters reside nearest to the root.
Code Generation: Generates variable-length prefix-free bit codes by traversing from the root to each character leaf. Frequent characters receive short bit patterns, minimizing total file size during compression.
Lab Practical Assignment Specifications:
Undo/Redo System: Uses two stacks (
UndoStackandRedoStack) to track document revisions, reversions, and reapplications in text processing software.Real-Time Event Processing: Employs a FIFO Queue to manage event scheduling, handling pending events in the order received while allowing cancellations.
Call Center Simulation: Models customer queues with unique IDs and call durations, operating strictly under FIFO priority.
Student Record Management System: Uses Singly or Doubly Linked Lists to track student records (
Roll No,Name,Marks), supporting in-memory insertion, deletion, updating, searching, and sorting.