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 (α\alpha), 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.

Classification of Data Structures
  • 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 L2L_2 onto L1L_1 under persistence, a deep copy of list nodes can be duplicated to preserve the pristine state of L1L_1 and L2L_2, 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.

Persistent Linked List Concatenation

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 nn.

  • Order of Growth Hierarchy:

    • The asymptotic growth rates of algorithmic runtimes scale according to the following mathematical order:     c<log⁡(log⁡(n))<log⁡(n)<n1/3<n1/2<n<nlog⁡(n)<n2<n2log⁡(n)<n3<n4<2n<nnc < \log(\log(n)) < \log(n) < n^{1/3} < n^{1/2} < n < n \log(n) < n^2 < n^2 \log(n) < n^3 < n^4 < 2^n < n^n     where cc 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; } &nbsp;&nbsp;&nbsp;&nbsp;

    • The parameter a occupies 2 bytes2\,\text{bytes}, and the return value consumes 2 bytes2\,\text{bytes}.

    • Total memory required is 4 bytes4\,\text{bytes}, which remains fixed regardless of the magnitude of a, yielding O(1)O(1) 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; } &nbsp;&nbsp;&nbsp;&nbsp;

    • Array parameter A[] requires 2n bytes2n\,\text{bytes}.

    • Integer parameter n requires 2 bytes2\,\text{bytes}.

    • Local integer variables sum and i require 2 bytes2\,\text{bytes} each (4 bytes4\,\text{bytes} total).

    • The return value requires 2 bytes2\,\text{bytes}.

    • Total memory required evaluates to 2n+8 bytes2n + 8\,\text{bytes}. As nn scales, space demand increases linearly, demonstrating O(n)O(n) linear space complexity.

  • Asymptotic Notations:

    • Big-O Notation (OO) — 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: f(n)=O(g(n))f(n) = O(g(n)) if and only if there exist positive constants C>0C > 0 and n0≥1n_0 \ge 1 such that:       f(n)≤C⋅g(n)for all n≥n0f(n) \le C \cdot g(n) \quad \text{for all } n \ge n_0

    • Big-Omega Notation (Ω\Omega) — Lower Bound:

    • Defines the best-case execution time, establishing the baseline minimum computational time required by an algorithm.

    • Mathematical Definition: f(n)=Ω(g(n))f(n) = \Omega(g(n)) if and only if there exist positive constants C>0C > 0 and n0≥1n_0 \ge 1 such that:       f(n)≥C⋅g(n)for all n≥n0f(n) \ge C \cdot g(n) \quad \text{for all } n \ge n_0

    • Theta Notation (Θ\Theta) — Tight Bound (Average Bound):

    • Encapsulates the function within tight upper and lower bounds, characterizing the exact average growth rate.

    • Mathematical Definition: f(n)=Θ(g(n))f(n) = \Theta(g(n)) if and only if there exist positive constants C1>0C_1 > 0, C2>0C_2 > 0, and n0≥1n_0 \ge 1 such that:       C1⋅g(n)≤f(n)≤C2⋅g(n)for all n≥n0C_1 \cdot g(n) \le f(n) \le C_2 \cdot g(n) \quad \text{for all } n \ge n_0

  • 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; } &nbsp;&nbsp;&nbsp;&nbsp;

    • Line sum = 0;: Step count per execution = 11, Frequency = 11, Total steps = 11.

    • Line for i = 1 to n do: Step count per execution = 11, Frequency = n+1n + 1, Total steps = n+1n + 1.

    • Line sum = sum + a[i];: Step count per execution = 11, Frequency = nn, Total steps = nn.

    • Line return sum;: Step count per execution = 11, Frequency = 11, Total steps = 11.

    • Total cumulative step count: 1+(n+1)+n+1=2n+31 + (n + 1) + n + 1 = 2n + 3.

    • Asymptotic complexity: O(n)O(n).

  • Analysis of Programming Constructs:

    • Constant Time (O(1)O(1)): Independent of input size. Example: A = A + B;.

    • Linear Time (O(n)O(n)): Execution scales proportionally with nn. c for (i = 1; i <= n; i++) a = a * b; &nbsp;&nbsp;&nbsp;&nbsp;

  • Quadratic Time (O(n2)O(n^2)): Nested loops where execution scales with n2n^2. c for (i = 1; i <= n; ++i) for (j = 1; j <= n; j++) a = a * b; &nbsp;&nbsp;&nbsp;&nbsp;

  • Cubic Time (O(n3)O(n^3)): Triple-nested loops scaling with n3n^3. c for (i = 1; i <= n; ++i) for (j = 1; j <= n; j++) for (k = 1; k <= n; k++) a = a * b; &nbsp;&nbsp;&nbsp;&nbsp;

  • Logarithmic Time (O(log⁡(n))O(\log(n))): 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; &nbsp;&nbsp;&nbsp;&nbsp;

  • 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 00 to n−1n - 1.

    • Key Characteristics: Fixed capacity determined at initialization (static memory allocation), direct random access in O(1)O(1) time complexity, high memory locality for hardware caching efficiency.

Array Memory Structure
  • Array Operations and Complexities:

    • Traversal: Sequentially accessing each element from index 00 to n−1n - 1 for evaluation, printing, or aggregation; Time Complexity: O(n)O(n).

    • Insertion: Inserting a value at a designated index. Requires right-shifting elements from n−1n - 1 down to index kk.

    • Best Case (insertion at end): O(1)O(1)

    • Worst Case (insertion at index 00): O(n)O(n)

    • Deletion: Removing an item at index kk, followed by left-shifting all subsequent elements from k+1k + 1 to n−1n - 1 to close the void; Time Complexity: O(n)O(n).

    • Updating: Directly indexing and assigning a new value to arr[k]; Time Complexity: O(1)O(1).

    • Searching: Scanning for a target value using Linear Search (O(n)O(n)) or Binary Search (O(log⁡(n))O(\log(n)) for sorted data).

  • Memory Address Calculation for 1D Arrays:

    • In a one-dimensional array, the physical memory address for the element at index ii is computed via the formula:     Address(A[i])=Base Address+(i×Size of Data Type)\text{Address}(A[i]) = \text{Base Address} + (i \times \text{Size of Data Type})

    • Example: Given a base address of 10001000 and an integer type size of 2 bytes2\,\text{bytes}:

    • Index 00: 1000+(0×2)=10001000 + (0 \times 2) = 1000

    • Index 11: 1000+(1×2)=10021000 + (1 \times 2) = 1002

    • Index 22: 1000+(2×2)=10041000 + (2 \times 2) = 1004

    • Index 77: 1000+(7×2)=10141000 + (7 \times 2) = 1014

1-D Array Memory Arrangement
  • 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 00 are stored contiguously, followed by row 11, then row 22.

    • Column-Major Order: Elements are stored column by column. All elements of column 00 are laid out in contiguous memory, followed by column 11, through column mm.

Row Major vs Column Major Order
  • 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 O(1)O(1) (target located at index 00), Worst case O(n)O(n) (target located at index n−1n - 1 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 (M=⌊(L+H)/2⌋M = \lfloor(L + H)/2\rfloor). If the target is smaller, the upper half is discarded; if larger, the lower half is eliminated.

    • Time Complexity: O(log⁡(n))O(\log(n)).

Binary Search Step-by-Step
  • Fibonacci Search:

    • A divide-and-conquer searching method that uses Fibonacci numbers (0,1,1,2,3,5,8,13,…0, 1, 1, 2, 3, 5, 8, 13, \dots) 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: i=min⁡(offset+FibM2,n−1)i = \min(\text{offset} + \text{FibM2}, n - 1).

    • Time Complexity: O(log⁡(n))O(\log(n)).

  • 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 (O(n2)O(n^2) vs. O(nlog⁡(n))O(n \log(n))) 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: O(n2)O(n^2); Auxiliary Space: O(1)O(1); 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: O(n2)O(n^2); Auxiliary Space: O(1)O(1); 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: O(n2)O(n^2); Auxiliary Space: O(1)O(1); 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 O(nlog⁡(n))O(n \log(n)), Worst case O(n2)O(n^2) (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: O(nlog⁡(n))O(n \log(n)) across all cases (best, average, worst); Auxiliary Space: O(n)O(n); Stability: Stable.

Merge Sort Divide and Conquer Tree

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 top of 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 if TOP == -1, otherwise false.

    • isFull(): Returns true if TOP == MAX - 1, otherwise false.

    • size(): Returns the total count of elements currently resident (TOP+1\text{TOP} + 1).

  • Stack Primitive Algorithms:

    • Push Operation:text if TOP == MAX - 1 then return "Overflow" endif TOP = TOP + 1 STACK[TOP] = item end &nbsp;&nbsp;&nbsp;&nbsp;

  • Pop Operation:text if TOP == -1 then return "Underflow" endif item = STACK[TOP] TOP = TOP - 1 return item end &nbsp;&nbsp;&nbsp;&nbsp;

Stack Push and Pop Trace
  • 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: n=10n = 10 (indices 00 through 99).

    • Stack A expands left-to-right starting from index 00, with TOP_A initialized to −1-1.

    • Stack B expands right-to-left starting from index 99, with TOP_B initialized to nn (1010).

    • Condition for Stack Overflow: TOP_A + 1 == TOP_B.

    • Combined capacity remains bounded by nn, allowing flexible space sharing when stack growth rates are asymmetrical.

Multiple Stacks in a Single Array
  • 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., A+BA + B). 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., +AB+ A B).

    • Postfix Notation (Reverse Polish Notation — RPN): Operators follow their respective operands (e.g., AB+A B +). 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:

    1. Scan tokens of the infix expression from left to right.

    2. If the token is an operand, append it directly to the output postfix string.

    3. If the token is an opening parenthesis (, push it onto the operator stack.

    4. 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.

    1. If the token is a closing parenthesis ): Pop operators from the stack to the output until an opening parenthesis ( is encountered; discard both parentheses.

    2. Repeat until the input is exhausted, then pop all remaining operators from the stack to the output.

  • Worked Example — Infix to Postfix Conversion:

    • Expression: 2×3/(2−1)+5×32 \times 3 / (2 - 1) + 5 \times 3

    • Trace Steps:

    • Token 2: Stack [], Output: 2

    • Token *: Stack [*], Output: 2

    • Token 3: Stack [*], Output: 2 3

    • Token /: Stack [/] (pops *), Output: 2 3 *

    • Token (: Stack [/, (], Output: 2 3 *

    • Token 2: Stack [/, (], Output: 2 3 * 2

    • Token -: Stack [/, (, -], Output: 2 3 * 2

    • Token 1: Stack [/, (, -], Output: 2 3 * 2 1

    • Token ): Stack [/], Output: 2 3 * 2 1 -

    • Token +: Stack [+] (pops /), Output: 2 3 * 2 1 - /

    • Token 5: Stack [+], Output: 2 3 * 2 1 - / 5

    • Token *: Stack [+, *], Output: 2 3 * 2 1 - / 5

    • Token 3: Stack [+, *], Output: 2 3 * 2 1 - / 5 3

    • End of Input: Pop *, then +

    • Final Postfix Expression: 2 3 * 2 1 - / 5 3 * +

  • Algorithm for Postfix Evaluation:

    1. Scan the postfix string from left to right token by token.

    2. If the token is an operand, push its numerical value onto the evaluation stack.

    3. If the token is an operator, pop two operands: operand1 = pop() (top item) and operand2 = pop() (second item).

    4. Compute result = operand2 (operator) operand1.

    5. Push result back onto the stack.

    6. 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) + A →\rightarrow Postfix: C B * A + →\rightarrow Reversed to prefix: + A * B C.

  • Prefix to Postfix Conversion Algorithm:

    1. Scan symbols from right to left.

    2. If an operand is read, push it onto the stack.

    3. If an operator is read, pop two strings: op1 = pop() and op2 = pop(). Construct the string op1 + op2 + operator and push it back onto the stack.

    4. 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 REAR node (enqueue), while deletions take place at the FRONT node (dequeue).

    • Core Operations:

    • enqueue(x): Adds item x at REAR.

    • dequeue(): Removes the element at FRONT.

    • 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 FRONT becomes unusable in a static array. REAR can 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: REAR=(REAR+1) mod SIZE\text{REAR} = (\text{REAR} + 1) \bmod \text{SIZE}.

Circular Queue Incrementation
  • Queue Full Boundary Conditions:

    • Case 1: FRONT == 0 && REAR == SIZE - 1

    • Case 2: FRONT == REAR + 1

  • Circular Enqueue Algorithm:

    1. Check if queue is full using the two conditions above.

    2. If FRONT == -1, initialize FRONT = 0.

    3. Set REAR = (REAR + 1) % SIZE.

    4. Assign QUEUE[REAR] = data.

  • Circular Dequeue Algorithm:

    1. Check if FRONT == -1 (underflow).

    2. Retrieve data = QUEUE[FRONT].

    3. If FRONT == REAR (last remaining element removed), reset FRONT = -1 and REAR = -1.

    4. 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., 11 is highest priority, 2222 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.

Heapify Operation in Priority Queue

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 data field 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; }; &nbsp;&nbsp;&nbsp;&nbsp;

    • SLL Insertion Operations:

    • At Beginning: Allocate newNode; set newNode->next = head; set head = newNode.

    • At End: Allocate newNode; set newNode->next = NULL; traverse pointer temp until temp->next == NULL; set temp->next = newNode.

    • After Specified Node: Traverse to target node; set newNode->next = temp->next; set temp->next = newNode.

    • SLL Deletion Operations:

    • At Beginning: Set head = head->next.

    • At End: Traverse to second-to-last node where temp->next->next == NULL; set temp->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 assign curr->next = head2.

  • Doubly Linked List (DLL):

    • Nodes store two pointers: prev (pointing to the predecessor) and next (pointing to the successor).

    • Enables bidirectional traversal (forward and backward).

    • C Node Definition:c struct node { struct node *prev; int data; struct node *next; }; &nbsp;&nbsp;&nbsp;&nbsp;

  • 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; &nbsp;&nbsp;&nbsp;&nbsp;

  • 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); &nbsp;&nbsp;&nbsp;&nbsp;

Doubly Linked List Structure
  • 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 | O(n)O(n) without previous pointer | O(1)O(1) 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 next pointer of the final node loops back to reference the first node (head). Eliminates NULL pointer termination.

    • Doubly Circular Linked List: Two-way circular connection: the last node's next references the first node, and the first node's prev references the last node. Allows constant-time O(1)O(1) jumps between head and tail in either direction.

Circular Singly Linked List

Hash Tables, Collision Resolution, and Overflow Handling

  • Hash Table Fundamentals:

    • A data structure that maps keys to values, delivering average-case constant time complexity O(1)O(1) 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:     hash(key)=key mod table_size\text{hash}(key) = key \bmod \text{table\_size}

    • 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 (α\alpha): Ratio of total keys stored (nn) to total bucket capacity (mm):     α=nm\alpha = \frac{n}{m}

    • Rehashing: Allocating a larger table (often double the size) and re-inserting all existing keys using a revised hash function once α\alpha crosses a defined threshold (e.g., 0.70.7).

  • 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 (α>1\alpha > 1).

    • 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: index+1,index+2,…\text{index} + 1, \text{index} + 2, \dots

      • Quadratic Probing: Offsets probe steps quadratically: index+12,index+22,…\text{index} + 1^2, \text{index} + 2^2, \dots

      • Double Hashing: Uses a secondary hash function to calculate dynamic step sizes.

    • Requires α<1\alpha < 1. 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 G=(V,E)G = (V, E), where VV is a finite set of vertices (nodes) and EE is a set of edges connecting pairs of vertices.

    • Example Graph Definition:

    • V={A,B,C,D,E}V = \{A, B, C, D, E\}

    • E={{A,B},{A,C},{B,C},{B,D},{C,D},{D,D},{B,E},{D,E}}E = \{\{A, B\}, \{A, C\}, \{B, C\}, \{B, D\}, \{C, D\}, \{D, D\}, \{B, E\}, \{D, E\}\}

Graph with Self Loop
  • 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 DD in the figure above).

    • Degree of a Vertex: The total number of edges incident upon a vertex (e.g., the degree of vertex BB is 44).

    • Adjacency: Two nodes connected by a direct edge are adjacent.

    • Path: A sequence of alternating vertices and edges connecting two nodes (e.g., path C−A−B−EC-A-B-E).

    • Leaf / Pendant Vertex: A vertex possessing a degree of exactly 11.

  • 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, UU and VV, such that every edge connects a node in UU to a node in VV, with no edges connecting nodes within the same set.

Bipartite Graph Structure
  • Graph Storage Representations:

    • Adjacency Matrix: A 2D array of dimensions V×VV \times V, where matrix[i][j] = 1 indicates an edge between vertex ii and vertex jj (or the edge weight for weighted graphs), and 0 indicates 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.

Adjacency Matrix Representation
  • 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 visited array 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.

    1. Initialize an empty MST edge set.

    2. Sort all edges across the graph in non-decreasing order of weights.

    3. Greedily insert edges one by one into the spanning forest, rejecting any edge that would introduce a cycle.

    4. Terminate when V−1V - 1 edges have been selected.

    • Applications: Network cabling design, electrical grids, tour routing.

Kruskal Algorithm MST
  • Prim's Algorithm:

    • A vertex-centric greedy algorithm similar to Dijkstra's algorithm.

    1. Start from an arbitrary root vertex, initializing a tree with this single node.

    2. Evaluate all edges connecting tree vertices to unvisited vertices outside the tree.

    3. Select the edge with the minimum weight and incorporate both the edge and the new vertex into the growing tree.

    4. Repeat until all vertices are included in the MST.

Prim Algorithm MST Progression

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 00).

    • 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.

General Tree Structure
  • 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 11.

Balanced vs Unbalanced Binary Tree
  • Mathematical Properties:

    • Maximum leaf count at height hh: 2h2^h

    • Maximum total nodes in a binary tree of height hh: 2h+1−12^{h+1} - 1

    • Maximum nodes at level ll: 2l2^l

    • Total edges in a full tree of nn nodes: n−1n - 1

    • 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 KK is located at index 2K2K.

    • The right child of node KK is located at index 2K+12K + 1.

    • Maximum array capacity required: 2h−12^h - 1.

  • Linked Representation: Nodes are allocated dynamically via structures containing data and two pointers: struct node* left and struct node* right.

    • Binary Tree Traversals:

  • Inorder Traversal: Left Subtree →\rightarrow Root →\rightarrow Right Subtree

  • Preorder Traversal: Root →\rightarrow Left Subtree →\rightarrow Right Subtree

  • Postorder Traversal: Left Subtree →\rightarrow Right Subtree →\rightarrow Root

    • Binary Search Tree (BST):

  • An ordered binary tree enforcing the invariant that for any given node with key K1K_1:

    • All keys in its left subtree are less than or equal to K1K_1 (K2≤K1K_2 \le K_1).

    • All keys in its right subtree are strictly greater than K1K_1 (K3>K1K_3 > K_1).

BST Node Relationship Property
  • 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 O(log⁡(n))O(\log(n)) 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 - *:

    1. Read operands 4 and 5, create single-node trees, and push their pointers onto a stack.

    2. Read operator +: create a + node, pop 5 as its right child and 4 as its left child; push the resulting subtree back onto the stack.

    3. Read operands 5 and 3: push their respective node pointers onto the stack.

    4. Read operator -: create a - node, pop 3 as right child and 5 as left child; push the subtree onto the stack.

    5. 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.

Expression Tree Structure

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 O(nlog⁡(n))O(n \log(n)) 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:

    1. Sort all proposed meeting intervals by their end times (or earliest start times).

    2. Schedule the first compatible event.

    3. 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] = 1 indicates 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 O(1)O(1) 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 (UndoStack and RedoStack) 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.