Programming & Data Structures
Subject 3 of 10 · Exact transcription of the original notes, Chapters 1 to 10.
1. C Programming Basics
1.1 Data Types and Variables
Overview
A variable is a named storage location in memory that holds data during program execution.
Variable Declaration vs Definition:
Declaration: Introduces a variable name and type to the compiler without allocating memory.
Definition: Allocates memory and optionally assigns an initial value.
In C, declaration and definition typically happen together:
int count = 10; // Both declaration and definition
const (Constant Variables):
Variables marked with const cannot be modified after initialization.
const type variable = value;
Key notes:
- Must be initialized during declaration
- Value becomes read-only after initialization
- Compiler enforces immutability
const int MAX_SIZE = 100; Const with Pointers:
| Declaration | Pointer Modifiable |
|---|---|
int *ptr | Yes |
const int *ptr | Yes |
int *const ptr | No |
const int *const ptr | No |
Read as: "const applies to whatever is immediately to its right."
extern (External Linkage):
Declares that a variable or function is defined elsewhere - tells compiler to use existing memory allocation.
Key points:
- Declaration can appear multiple times
- Definition must appear exactly once
- Extends visibility across source files
- Functions have
externby default
Example:
extern int global_count; // Declared
extern int value = 10; //
static (Static Storage):
Variables that retain their value between function calls and exist for the program's lifetime.
Properties:
- Initialized only once at compile time
- Default value is 0 (or NULL for pointers)
- Memory allocated once, persists until program ends
Scope behavior:
- Local static: Visible only within declaring function
- Global static: Visible only within current source file
Example: Function call counter that remembers previous calls. [the full code for this example appears later, under Static Storage Class in 1.5 - as in source order it is only named here]
void (Empty Type):
Represents "no type" or "no value" - used for generic programming.
void pointers (void *):
- Can point to any data type
- Must be cast before dereferencing
- Used by
malloc()andcalloc()for generic memory allocation
Limitation: Cannot dereference void * directly - must cast first.
typedef (Type Aliasing):
Creates new names for existing data types to improve code readability.
typedef existing_type new_name;
Example:
typedef unsigned long ulong;
typedef struct Point Point; //
Remember: typedef creates aliases, not new types - just different names for the same underlying type.
Enumeration (or enum):
Enumeration (enum) is a user-defined data type that assigns names to integer constants, making code more readable and maintainable.
Basic syntax:
enum color {RED, GREEN, BLUE};
Default values: When no values are explicitly assigned, the compiler assigns values starting from 0:
- RED = 0, GREEN = 1, BLUE = 2
Custom values: You can assign specific integer values to enum constants:
enum status {PENDING = 10, ACTIVE = 20}; //
Auto-increment rule: Unassigned names get the value of the previous name plus 1:
enum level {LOW = 5, MEDIUM, HIGH};
// LOW = 5, MEDIUM = 6, HIGH = 7
Key properties:
- Multiple enum names can have the same value
- Values must be integer constants (within
intrange) - All enum constants must be unique within their scope
Scope conflict example: This code fails to compile because SUCCESS is defined in both enums:
enum result1 {SUCCESS, FAILURE};
enum result2 {SUCCESS, ERROR}; // Error
Note: Use enums instead of #define constants for better type checking and debugging support.
Introduction
Data structures can be classified based on two main criteria:
Manipulation-Based Classification
Primitive Data Structures:
- Basic building blocks that cannot be decomposed further
- Examples: integers, floating-point numbers, characters, boolean values
- Directly supported by programming languages
Non-Primitive Data Structures:
- Complex structures built using primitive types
- Examples: arrays, stacks, queues, records, files, linked lists, trees, graphs
- Require additional memory management and operations
Storage-Based Classification
Linear Data Structures:
- Elements arranged in sequential order
- Each element has exactly one predecessor and one successor (except first and last)
- Examples: arrays, records, stacks, queues, linked lists
- Memory access follows a linear pattern
Note: The classification helps determine appropriate algorithms and memory allocation strategies for different data manipulation needs.
Time and Space Complexity With Each Data Structure
Time and Space Complexity Reference for Data Structures
Read as: Each row shows the complexity for Access, Search, Insert, Delete operations under Average and Worst cases, plus Space complexity. [as written in source; in the screenshots only the first column group, Average Case: Access, is visible]
| Data Structure | Average Case: Access |
|---|---|
| Array | Θ(1) |
| Stack | Θ(n) |
| Queue | Θ(n) |
| Singly Linked List | Θ(n) |
| Doubly Linked List | Θ(n) |
| Skip List | Θ(log n) |
| Hash Table | N/A |
| Binary Search Tree | Θ(log n) |
| Cartesian Tree | N/A |
| B-Tree | Θ(log n) |
| Red-Black Tree | Θ(log n) |
| Splay Tree | N/A |
| AVL Tree | Θ(log n) |
| KD Tree | Θ(log n) |
Key Insights:
- Arrays: Constant access, linear for modifications due to shifting
- Stacks/Queues: Only top/front operations are Θ(1), others require traversal
- Hash Tables: Best average case but degrade to linear on collisions
- Balanced Trees (AVL, Red-Black, B-Tree): Guaranteed Θ(log n) operations
- Unbalanced BST: Can degrade to Θ(n) in worst case (skewed tree)
- Skip Lists: Probabilistic Θ(log n) with extra space overhead
Remember: N/A indicates the operation doesn't apply naturally to that structure's typical usage pattern.
1.2 Operators and Expressions
Operators in C
Arithmetic Operators:
Perform mathematical calculations on numeric values:
+Addition: a + b-Subtraction: a - b*Multiplication: a * b/Division: a / b%Modulus: remainder of a / b
int a = 17, b = 5; a + breturns 22a - breturns 12a * breturns 85a / breturns 3 (integer division)a % breturns 2 (remainder)
Relational Operators:
Compare two values and return true (1) or false (0):
==Equal to: checks if a == b!=Not equal to: checks if a != b>Greater than: checks if a > b<Less than: checks if a < b>=Greater than or equal: checks if a >= b<=Less than or equal: checks if a <= b
int x = 10, y = 20; x == yreturns 0 (false)x < yreturns 1 (true)x == 10returns 1 (true)
Logical Operators:
Combine or modify boolean expressions:
&&Logical AND: true only if both operands are true||Logical OR: true if at least one operand is true!Logical NOT: inverts the boolean value
Truth table:
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 1 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 0 |
| 1 | 1 | 1 | 1 | 0 |
Note: Logical operators use short-circuit evaluation - if the result can be determined from the first operand, the second isn't evaluated.
Short-circuiting in Logical Operators:
Short-circuiting occurs when logical operators stop evaluating operands once the result is determined:
- Logical AND (&&): If first operand is false, second operand is not evaluated (result is already false)
- Logical OR (||): If first operand is true, second operand is not evaluated (result is already true)
Example:
if (ptr != NULL && ptr->value > 10) //
if (count == 0 || total/count > 5) //
Operator Precedence and Associativity:
Higher precedence operators are evaluated first. When precedence is equal, associativity determines evaluation order.
| Precedence | Operators |
|---|---|
| 1 (highest) | ( ), [ ], -> , . |
| 2 | ! , ~ , ++ , -- , - (unary), * unary |
| 3 | * , / , % |
| 4 | + , - |
| 5 | << , >> |
| 6 | < , <= , > , >= |
| 7 | == , != |
| 8 | & (bitwise AND) |
| 9 | ^ (bitwise XOR) |
| 10 | | (bitwise OR) |
| 11 | && (logical AND) |
| 12 | || (logical OR) |
| 13 | ?: (ternary) |
Note: Comparisons like a < b < c do not behave as a mathematical chained comparison in C.
Key Operators:
sizeof operator:
- Returns size in bytes of a data type or variable
- Useful for finding array length:
sizeof(arr)/sizeof(arr[0]) - Essential for dynamic memory allocation
Modulus (%) with negative numbers:
The result takes the sign of the left operand:
- 7 % 3 = 1
- -7 % 3 = -1
- 7 % -3 = 1
String vs Character Array:
Character array: char s[] = "Test";
- Creates modifiable array in stack/data segment
- Can change individual characters:
s[0] = 'T' - Cannot reassign entire array:
s = "new"(invalid)
String pointer: char *s = "Test";
- Points to string literal in read-only memory
- Cannot modify characters:
s[0] = 'T'(undefined behavior) - Can reassign pointer:
s = "new"(valid)
1.3 Control Flow (if, switch, loops)
Switch Case
The switch statement in C provides multi-way branching based on the value of an expression.
Basic syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}
Key Rules:
Expression type: Must be integral type only
- Valid:
int,char,enum - Invalid:
float,double,string, pointers
Case values: Must be compile-time constants
- Valid:
case 5:,case 'A':,case MAX_SIZE: - Invalid:
case x:,case getValue():
Fall-through behavior: Execution continues until break is encountered
- Without
break, control flows to next case - Use this intentionally for grouped cases
Default placement: Can appear anywhere in the switch block
- Executes when no case matches
- Position doesn't affect execution order
Important Notes:
No duplicate cases: Each case value must be unique
case 1: // Valid
case 1: // Error - duplicate value
Unreachable code: Statements before the first case are never executed
switch (x) {
printf("Never runs"); // Unreachable
case 1:
printf("Runs if x == 1");
}
Example: Menu selection
switch (choice) {
case 1:
case 2:
printf("Option 1 or 2 selected"); //
break;
case 3:
printf("Option 3 selected");
break;
default:
printf("Invalid choice");
}
Remember: Always include break unless you intentionally want fall-through behavior.
1.4 Recursion
Recursion
Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem.
Basic Examples:
Factorial calculation:
int fact(int n) {
if (n == 0) return 1;
else return n * fact(n-1);
}
Fibonacci sequence:
int fib(int n) {
if (n < 2) return n; //
else return fib(n-1) + fib(n-2);
}
Fibonacci complexity analysis:
- Function calls: 2 * fib(n+1) - 1
- Addition operations: fib(n+1) - 1
- First addition occurs after (n+1) function calls
Tower of Hanoi:
Move n discs from source to destination using temporary peg:
TOH(source, temp, dest, n) {
if (n == 1)
dest.push(source.pop());
else {
TOH(source, dest, temp, n-1);
dest.push(source.pop());
TOH(temp, source, dest, n-1);
}
}
Complexity:
- Function calls: 2^n - 1
- Disc moves: 2^n - 1
GCD Algorithms:
Iterative approach:
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
Recursive approach:
int gcd(int a, int b) {
if (a == b) return a;
else if (a > b) return gcd(a - b, b); //
else return gcd(a, b - a); //
}
Finding Second Maximum:
Among three distinct numbers:
int secondMax(int a, int b, int c) {
if ((a > b) && (b > c)) return b; //
else if ((a > b)) return secondMax(a, c, b); //
else return secondMax(b, a, c); //
}
Pointer Declarations:
Basic pointers:
int *p- pointer to integerint *p[10]- array of 10 pointers to integersint (*p)[10]- pointer to array of 10 integers
Function pointers:
int *p()- function returning pointer to integerint (*p)()- pointer to function returning integerint (*p)(char *a)- pointer to function taking char pointer, returning integer
Complex declarations:
int (*p)(char *a)[10]- function taking char pointer, returning pointer to integer arrayint (*p[10])()- array of 10 function pointers, each returning integerint *(*p[10])(char x)- array of 10 function pointers, each taking char and returning int pointer
Parameter variations:
char *a[]- array of character pointerschar (*a)[]- pointer to character arraychar a[]- character array
Remember: Read declarations from inside out, following parentheses and brackets from right to left.
1.5 Storage Classes (auto, static, extern, register)
Storage Classes
C provides four storage classes that determine where variables are stored in memory and their lifetime:
Auto Storage Class:
Default storage class for variables declared inside functions:
auto int x; // 'auto' keyword optional
int y; // same as above
Characteristics:
- Stored in stack memory
- Initialized with garbage values (undefined)
- Scope limited to the block where declared
- Memory freed when function exits
Static Storage Class:
Variables that retain their value between function calls:
static int count = 0; //
Key properties:
- Stored in data segment (not stack)
- Initialized to zero by default
- Can only be initialized with constant values
- Lifetime extends throughout program execution
- Scope remains local to declaring function
Example: Function call counter
void increment() {
static int calls = 0; // retains value between
calls++;
printf("Called %d times", calls);
}
Register Storage Class:
- Compiler may or may not use actual register
- If no register available, stored in memory like auto
- Significantly faster access when actually in register
- Same scope and lifetime as auto variables
Restrictions:
- Cannot use address operator
&with register variables - Cannot combine with static storage class
- Typically used for frequently accessed variables like loop counters
Example usage:
for (register int i = 0; i < 100000; i++) //
// Frequent access to 'i' - good candidate
Extern Storage Class:
Declares a variable defined elsewhere (covered in separate topic).
Remember: Choose storage class based on variable usage pattern - frequent access (register), persistent state (static), or default behavior (auto).
1.6 Scope and Lifetime of Variables
Scope Rules in C
Global Scope: Variables declared outside all functions. Accessible from any function in the program.
int count = 0; // Global variable
void function1() {
count++; // Can access global
}
void function2() {
count = 5; // Can modify global
}
Local Scope: Variables declared inside a function. Only accessible within that specific function.
void calculate() {
int result = 10; // Local to calculate()
// 'result' cannot be used outside
}
void display() {
// printf("%d", result); // ERROR
}
Block Scope: Variables declared within braces {}. Accessible only within that block and any nested blocks inside it.
void example() {
int x = 5; // Function scope
if (x > 0) {
int y = 10; // Block scope
x = x + y; // This works:
{
int z = 20; // Nested block scope
y = z; // Can access outer
}
// z = 30; // ERROR: z out of scope
}
// y = 15; // ERROR: y out of scope
}
Block Scope: Variables declared within braces { }. Accessible only within that block and any nested blocks inside it.
void function() {
int x = 5; // Function scope
if (x > 0) {
int y = 10; // Block scope
x = y + 1; // Can access both
{
int z = 20; // Nested block
x = z; // Can access
}
// z = 30; // ERROR: 'z'
}
// y = 40; // ERROR: 'y'
}
Variable Shadowing: Inner scope variables can hide outer scope variables with the same name.
int value = 100; // Global
void test() {
int value = 50; // Local - shadows [global]
printf("%d", value); // Prints 50
}
Remember: Scope determines where a variable can be accessed, not its lifetime in memory.
---
2. Pointers and Memory
2.1 Pointer Basics and Arithmetic
Null Pointer
A NULL pointer is a pointer that points to no valid memory location. It's used when you don't have a specific address to assign to a pointer variable. Declaration and assignment:
int *ptr = NULL;
Key distinctions:
- NULL vs Uninitialized pointer: An uninitialized pointer contains garbage value (random memory address). A NULL pointer explicitly stores the value 0, indicating it points nowhere valid.
- NULL vs Void pointer: NULL is a value (0) that can be assigned to any pointer type. A void pointer (
void*) is a data type that can point to any data type but requires casting before dereferencing.
Example comparison:
int *uninit; // Contains garbage
int *null_ptr = NULL; // Contains 0
void *void_ptr; // Can point to any [type]
Safety check before use:
if (ptr != NULL) {
*ptr = 10; // Safe to dereference
}
Remember: Always initialize pointers to NULL if you don't have an immediate address to assign. Dereferencing a NULL pointer causes runtime error (segmentation fault).
Wild Pointer
A wild pointer is an uninitialized pointer that contains garbage values instead of a valid memory address or NULL.
int *ptr; // Wild pointer - contains random memory [address]
Characteristics:
- Points to arbitrary memory locations
- Contains unpredictable garbage values
- Not initialized to NULL or any valid address
- Accessing them leads to undefined behavior
Why wild pointers are dangerous:
- May crash the program when dereferenced
- Can corrupt data in random memory locations
- Behavior is unpredictable and system-dependent
- Difficult to debug since errors appear random
Example of wild pointer problem:
int *ptr; // Wild pointer
*ptr = 100; // Undefined behavior
Safe alternatives:
- Initialize to NULL:
int x = 5;
int *ptr = &x; // Safe - points to [x]
- Allocate memory explicitly:
int *ptr = malloc(sizeof(int)); // Allocate
*ptr = 10; // Now safe to use
Remember: Always initialize pointers before use. A pointer pointing to a known variable or allocated memory is not wild.
2.2 Dynamic Memory Allocation (malloc, calloc, realloc, free)
Dangling Pointer
A dangling pointer points to memory that has been deallocated or is no longer valid. Accessing such pointers leads to undefined behavior and potential crashes.
Three Common Scenarios:
1. Memory Deallocation When memory is freed but the pointer still holds the old address:
int *ptr = malloc(sizeof(int));
*ptr = 20;
free(ptr); // Memory deallocated
// ptr is now dangling - still points [to freed memory]
2. Function Scope Issues When a pointer references local variables that go out of scope:
int* getLocalAddress() {
int local = 100;
return &local; // Returns address [of local]
}
// Returned pointer becomes dangling
3. Automatic Variable References When pointers reference stack variables that become invalid:
int* ptr;
{
int temp = 50;
ptr = &temp; // ptr points to [temp]
}
// temp destroyed, ptr now dangling
Prevention Strategies:
- Set pointers to NULL after freeing:
ptr = NULL - Avoid returning addresses of local variables
- Use dynamic allocation for data that outlives function scope
- Check for NULL before dereferencing:
if (ptr != NULL)
Remember: A dangling pointer looks valid but points to invalid memory - always nullify after freeing.
Memory Leak
A memory leak occurs when dynamically allocated memory is not properly deallocated, causing the program to gradually consume more memory over time.
When it happens:
- Memory allocated using
malloc(),calloc(), orrealloc() - Corresponding
free()call is missing or unreachable - Pointer to allocated memory is lost before freeing
Critical for long-running programs:
- Daemons and servers that never terminate
- Programs with loops that allocate memory repeatedly
- Eventually leads to system memory exhaustion
Prevention rules:
- Every
malloc()must have a matchingfree() - Free memory before pointer goes out of scope
- Set pointer to
NULLafter freeing (prevents double free errors)
Example of memory leak:
void function() {
int *ptr = malloc(100 * sizeof(int));
// Some operations
return; // Memory not freed - LEAK
}
Correct approach:
void function() {
int *ptr = malloc(100 * sizeof(int));
// Some operations
free(ptr);
ptr = NULL;
}
Note: Stack memory (local variables) is automatically freed when function ends. Only heap memory requires manual management.
---
3. Arrays and Strings
3.1 1D Arrays
Array
An array is a data structure that stores multiple elements of the same data type in consecutive memory locations.
Key Properties:
- Homogeneous: All elements must be of the same data type
- Contiguous memory: Elements are stored in adjacent memory locations
- Static size: Array size is fixed at declaration time
- Index-based access: Elements accessed using zero-based indexing
Memory Layout: If array starts at address A and each element takes D bytes, then element at index i is located at:
Address = A + (i × D)
Advantages:
- Fast access: O(1) time complexity for accessing any element
- Cache friendly: Sequential memory layout improves cache performance
- Simple indexing: Direct calculation of element addresses
Limitations:
- Fixed size: Cannot resize after declaration
- Memory waste: Unused allocated space cannot be reclaimed
- Insertion/deletion: Expensive operations requiring element shifting
Example: Integer array with 5 elements
arr[5] = {10, 20, 30, 40, 50};
Index: 0 1 2 3 4
Note: Array indexing starts from 0, so valid indices for an array of size n are 0 to (n-1).
1-d Array
The memory address of any element in a 1-dimensional array can be calculated using:
Address of A[i] = Base(A) + (i - start_index) × element_size
where:
- Base(A) = starting memory address of the array
- i = index of the desired element
- start_index = first valid index (0 in most languages, 1 in some)
- element_size = bytes occupied by each element
Example: Integer array starting at memory address 1000
- Array: [10, 20, 30, 40, 50] (0-indexed)
- Each integer = 4 bytes
- Address of A[2]: 1000 + (2 - 0) × 4 = 1008
Language variations:
- C/C++/Java: start index = 0
- Some older languages: start index = 1
Note: This formula assumes elements are stored contiguously in memory, which is standard for arrays.
Insertion
Array Insertion Time Complexity Insertion performance depends on position:
- Best case: Insert at end → O(1) constant time
- No elements need shifting
- Simply place at next available index
- Worst case: Insert at beginning → O(n) linear time
- All existing elements must shift right
- Requires n shift operations
- Average case: Insert at middle → O(n) linear time
- On average, half the elements need shifting
- Still linear complexity overall
Example: Insert 15 into array [10, 20, 30, 40]
- At end: [10, 20, 30, 40, 15] → 1 operation
- At start: [15, 10, 20, 30, 40] → 4 shifts + 1 insert
- At index 2: [10, 20, 15, 30, 40] → 2 shifts + 1 insert
Note: Dynamic arrays may need resizing when capacity is exceeded, adding O(n) copy cost.
Deletion
Array Deletion Time Complexity Deletion operation performance depends on the position of the element being removed:
Best Case: O(1)
- Deleting from the end of the array
- No shifting of elements required
- Simply reduce the array size
Worst Case: O(n)
- Deleting from the beginning of the array
- All remaining elements must shift one position left
- Requires n - 1 shift operations
Average Case: O(n)
- Deleting from a random middle position
- On average, half the elements need shifting
- Expected shifts: n/2, which is O(n)
Example: Array [10, 20, 30, 40, 50]
- Delete 50: No shifts needed → O(1)
- Delete 10: Shifts 4 elements left → O(n)
- Delete 30: Shifts 2 elements left → O(n)
Note: Unlike insertion, deletion always maintains array contiguity by shifting elements to fill gaps.
Traversal
Array Traversal - Direct Access Arrays provide constant-time access to any element using its index:
Access Time = O(1)
Key Property: Given an array arr and index i, accessing arr[i] takes the same time regardless of array size or element position.
Why O(1)?
- Array elements are stored in contiguous memory locations
- Address calculation: base_address + (index × element_size)
- No need to traverse from beginning to reach target element
Example: In array [10, 20, 30, 40, 50]
- Accessing arr[0] takes same time as arr[4]
- Both operations: single memory lookup
Contrast with Linked Lists: Linked list traversal requires O(n) time to reach the n-th element, as you must follow pointers sequentially from the head.
3.2 2D Arrays and Row/Column Major Order
2-d Array
A 2-D array A[m][n] has m rows and n columns. Elements are stored in memory using one of two ordering schemes:
Row Major Order Elements are stored row by row (complete first row, then second row, etc.). Address formula:
where:
- i₀, j₀ = starting indices (usually 0 or 1)
- size = bytes per element
Example: Array A[3][4] with base address 1000, element size 4 bytes, 0-indexed
- A[1][2] address = 1000 + [(1 × 4 + 2)] × 4 = 1024
Column Major Order Elements are stored column by column (complete first column, then second column, etc.). Address formula:
Example: Same array A[3][4] in column major order
- A[1][2] address = 1000 + [(2 × 3 + 1)] × 4 = 1028
Key difference: In row major, row index multiplies by n (columns). In column major, column index multiplies by m (rows). Memory tip: Row major is standard in C/C++. Column major is used in Fortran and MATLAB.
Lower Triangular Matrix
Elements below and on the main diagonal are non-zero (aᵢⱼ ≠ 0 when i ≥ j). Storage size:
Row Major Order (store row by row):
Index = (j - 1) + i(i - 1) / 2
Column Major Order (store column by column):
Index = (i - j) + (j - 1)(2n - j + 2) / 2
Example: For 3×3 matrix, element a₂₃ in RMO:
- Index = (2 - 1) + 3(3 - 1) / 2 = 1 + 3 = 4
Upper Triangular Matrix
Elements above and on the main diagonal are non-zero (aᵢⱼ ≠ 0 when i ≤ j). Storage size:
Row Major Order:
Index = (j - i) + (i - 1)(2n - i + 2) / 2
Column Major Order:
Index = (j - 1) + j(j - 1) / 2
Strictly Lower Triangular Matrix
Only elements below the main diagonal are non-zero (aᵢⱼ ≠ 0 when i > j). Storage size:
Row Major Order:
Index = (j - 1) + (i - 1)(i - 2) / 2
Column Major Order:
Index = (i - 1) + (j - 1)(2n - j) / 2
Tridiagonal Matrix
Non-zero elements only on main diagonal and adjacent diagonals (|i - j| ≤ 1). Storage size:
Row Major mapping:
Index = 2i + j - 3
Column Major mapping:
Index = i + 2j - 3
Note: Tridiagonal matrices appear in solving differential equations and sparse linear systems.
3.3 String Handling in C
Strlen()
The strlen() function calculates the length of a string by counting characters until it reaches the null terminator '\0'. Syntax: strlen(string_variable)
- Takes one argument: pointer to the string
- Returns: number of characters (excluding null terminator)
Example:
char str[] = "GATE";
int len = strlen(str); // returns 4
Parameter Passing Techniques
Different methods for passing arguments to functions:
| Technique | Uses Actual Values |
|---|---|
| Call by value | Yes |
| Call by reference | Yes |
| Call by result | No |
| Call by value-result | Yes |
| Call by need | Yes |
| Call by table | Yes |
| Call by constant | Yes |
Key Differences:
- Call by reference vs call by name: Different results when passing array element addresses
- Call by reference vs call by value-result: Different behavior inside loops
Variable Scope
Scope = Range of program statements where a variable can be referenced.
Static Scoping Variable scope determined at compile time based on code structure.
- Scope known before execution
- More readable and reliable
- Faster execution
Dynamic Scoping Variable scope determined at run-time based on function call sequence.
- Scope resolved during execution
- More flexible but less efficient
- Harder to debug and maintain
Note: Most modern languages use static scoping for predictability.
---
4. Linked Lists
4.1 Singly Linked List Operations
Linked Lists
A linked list is a linear data structure where elements (nodes) are stored in sequence, but not in contiguous memory locations. Structure: Each node contains:
- Data field: Stores the actual value
- Pointer field: Stores address of the next node
Key Properties:
- Dynamic allocation: Memory allocated during runtime as needed
- Non-contiguous storage: Nodes scattered throughout memory
- Sequential access: Must traverse from head to reach any element
Memory allocation:
Node size = sizeof(data) + sizeof(pointer)
Example Structure:
[Data| Next] -> [Data| Next] -> Data| N... [
Advantages:
- Dynamic size - grows/shrinks during execution
- Efficient insertion/deletion at any position
- No memory waste (allocates exactly what's needed)
Disadvantages:
- No random access (must traverse sequentially)
- Extra memory overhead for storing pointers
- Poor cache locality due to non-contiguous storage
Time Complexity:
- Access: O(n)
- Search: O(n)
- Insertion: O(1) if position known, O(n) otherwise
- Deletion: O(1) if position known, O(n) otherwise
Insertion
Linked List Insertion Operations All insertion operations in a singly linked list require exactly 2 pointer modifications, regardless of position.
Insert at End:
node->next = newnode;
newnode->next = NULL;
- Point current last node to new node
- Set new node's next to NULL
Insert at Beginning:
newnode->next = head;
head = newnode;
- Point new node to current first node
- Update head pointer to new node
Insert in Middle:
newnode->next = node->next;
node->next = newnode;
- Point new node to the next node in sequence
- Point previous node to new node
Key Insight: The 2 pointer rule holds because:
- One pointer connects the new node into the chain
- One pointer updates an existing connection (or head/tail)
Example: Insert value 15 between nodes with values 10 and 20
newnode->next = node10->next(points to node20)node10->next = newnode(connects node10 to new node)
Remember: Order matters - always set the new node's pointer first to avoid losing the reference to the rest of the list.
Deletion
The content appears to be about linked list operations, but there's a mismatch between the title "Deletion" and the insertion example shown. Here's the enhanced content covering both operations:
Pointer Modifications in Linked List Operations
Insertion at Beginning To insert a new node at the start of a linked list:
- Pointers modified: 1
- Set new node's next pointer to current head
- Update head to point to new node
newNode->next = head;
head = newNode;
Deletion at Beginning To delete the first node from a linked list:
- Pointers modified: 1
- Update head to point to second node
- The first node becomes unreachable
head = head->next;
Key Insight: Both insertion and deletion at the beginning require modifying exactly one pointer - the head pointer. This makes these operations O(1) in time complexity.
Note: The original code head->next = head->next->next would actually skip a node, effectively deleting the second element rather than inserting at the beginning.
4.2 Doubly Linked List Operations
Operations on Doubly Linked List
A doubly linked list is a linear data structure where each node contains data and two pointers - one pointing to the previous node and one to the next node.
Node Structure
struct node {
int data;
struct node *prev; // Points to previous node
struct node *next; // Points to next node
};
Memory Layout
Each node connects bidirectionally:
- Forward traversal: Follow 'next' pointers from head to tail
- Backward traversal: Follow 'prev' pointers from tail to head
- First node: 'prev' pointer is 'NULL'
- Last node: 'next' pointer is 'NULL'
Key Operations
Insertion:
- At beginning: Update head's 'prev' and new node's 'next'
- At end: Update tail's 'next' and new node's 'prev'
- At position: Adjust four pointers (two nodes, two directions)
Deletion:
- Update 'prev' node's 'next' pointer
- Update 'next' node's 'prev' pointer
- Handle edge cases for head/tail nodes
Search: Can traverse in either direction for efficiency
Advantages over Singly Linked List
- Bidirectional traversal: Move forward or backward
- Efficient deletion: No need to traverse from head to find previous node
- Better for certain algorithms: Like LRU cache implementation
Trade-off: Extra memory overhead for the additional 'prev' pointer in each node.
Insertion
Doubly Linked List Insertion Operations
Insertion in a doubly linked list requires updating multiple pointers to maintain both forward and backward links.
Insert at Beginning (4 pointer modifications):
newnode->next = rootnewnode->prev = nullroot->prev = newnoderoot = newnode
The new node becomes the head, pointing forward to the old head and backward to null.
Insert at End (3 pointer modifications):
newnode->next = nullnewnode->prev = lastnodelastnode->next = newnode
The new node becomes the tail, with the previous tail now pointing to it.
Insert Between Nodes (4 pointer modifications):
newnode->next = currentnode->nextnewnode->prev = currentnodecurrentnode->next->prev = newnodecurrentnode->next = newnode
The new node is inserted between currentnode and its successor, requiring updates to both neighboring nodes.
Key Pattern: Beginning and middle insertions need 4 updates because they affect the prev pointer of an existing node. End insertion needs only 3 because the new node's next is simply null.
Remember: Always update the new node's pointers first, then update the existing nodes to point to the new node.
Deletion
Deleting a node from a doubly linked list:
To delete a node from the middle of a doubly linked list, exactly 2 pointers need modification:
- Update previous node's next pointer:
node->prev->next = node->next;
- Update next node's previous pointer:
node->next->prev = node->prev;
- Free the deleted node:
free(node);
Example: Removing node B from A ⇄ B ⇄ C
- A's next pointer changes from B to C
- C's prev pointer changes from B to A
- Result: A ⇄ C
Edge cases:
- First node: Only modify next node's prev pointer
- Last node: Only modify previous node's next pointer
- Single node: Update head pointer to NULL
Remember: Always check for NULL pointers before accessing prev/next to avoid segmentation faults.
5. Stacks
5.1 Stack Operations (Push, Pop, Peek)
Stack
A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. All insertions and deletions occur at one end called the top.
Key Components:
- Top: Pointer that tracks the topmost element
- Bottom: Fixed base of the stack
- Capacity: Maximum number of elements the stack can hold
Primary Operations:
- Push: Add element to the top
- Pop: Remove element from the top
- Peek/Top: View top element without removing it
- isEmpty: Check if stack is empty
- isFull: Check if stack is at capacity
LIFO Behavior: The last element pushed is the first one popped.
Example: Stack with elements [5, 3, 8] where 8 is at top
- Push 12: Stack becomes [5, 3, 8, 12]
- Pop: Returns 12, stack becomes [5, 3, 8]
- Peek: Returns 8 without changing stack
Applications:
- Function call management (call stack)
- Expression evaluation and syntax parsing
- Undo operations in editors
- Browser back button functionality
Remember: Stack = "plate stack" - you can only add/remove from the top.
Stack Operations
Stack operations manage data using Last-In-First-Out (LIFO) principle. The main operations are:
- push() - Add element to top
- pop() - Remove element from top
- isEmpty() - Check if stack is empty
- isFull() - Check if stack is full
- peek() - View top element without removing
- change() - Modify element at specific position
Push Operation
Adds element x to the top of stack S:
push(S, Top, N, x) {
if (Top == N - 1) {
printf("Stack overflow");
exit(1);
}
Top++;
S[Top] = x;
}
Process:
- Check if stack is full (Top == N - 1)
- If full, report overflow and exit
- Increment top pointer
- Insert element at new top position
- Before push(15): Stack has 2 elements
- After push(15): Top = 2, element 15 at position 2
Pop Operation
Removes and returns the top element:
pop(S, Top, N) {
int y;
if (Top == -1) {
printf("Stack underflow");
exit(1);
}
y = S[Top];
Top--;
return y;
}
Process:
- Check if stack is empty (Top == -1)
- If empty, report underflow and exit
- Store top element in temporary variable
- Decrement top pointer
- Return the stored element
Note: Top = -1 indicates empty stack, Top = N - 1 indicates full stack.
5.2 Tower of Hanoi
Applications of Stack
Stacks are fundamental data structures with Last-In-First-Out (LIFO) behavior, making them ideal for several computational problems.
Recursion Implementation
Every recursive function call uses an implicit stack to store:
- Function parameters and local variables
- Return addresses for each call level
- Current execution state
When a function calls itself, the system pushes a new frame onto the call stack. Upon return, frames are popped in reverse order.
Expression Evaluation
Postfix Evaluation: Stack processes operators after operands appear:
- Push operands onto stack
- When operator found: pop two operands, apply operation, push result
- Final stack element is the answer
Infix to Postfix Conversion
Converts human-readable expressions to stack-friendly format:
- Scan infix expression left to right
- Push operands directly to output
- For operators: pop stack until lower precedence found, then push current operator
- Handle parentheses by treating them as precedence boundaries
Precedence order: ^ > * / > + -
Tower of Hanoi
Classic recursive puzzle using stack principle:
- Move n disks from source to destination using auxiliary rod
- Recursive calls create implicit stack of pending moves
- Total moves required: 2^n - 1
Mathematical Sequences
Permutation Generation: Stack tracks current permutation state and backtracking points when generating all possible arrangements.
Symbol Balancing
Validates matching brackets, parentheses, and braces:
- Push opening symbols onto stack
- Pop and match when closing symbol encountered
- Expression is balanced if stack is empty at end
Common pairs: { }, [ ], ( )
Subroutine Management
Stack maintains the call hierarchy in programs:
- Stores return addresses when functions call other functions
- Manages parameter passing between caller and callee
- Handles local variable scope and memory allocation
Note: Modern compilers optimize tail recursion to avoid stack overflow in deep recursive calls.
6. Queues
6.1 Queue Operations (Enqueue, Dequeue)
Queue
A Queue follows First-In-First-Out (FIFO) ordering - elements are removed in the same order they were added.
Structure:
- Front: Where elements are removed (dequeue)
- Rear: Where elements are added (enqueue)
Basic Operations:
- Enqueue: Add element to rear
- Dequeue: Remove element from front
- isEmpty(): Check if queue is empty
- isFull(): Check if queue is full (for fixed-size queues)
Example: Enqueue 1, 2, 6 then dequeue twice
- After enqueues: Front → [1, 2, 6] → Rear
- First dequeue removes 1: [2, 6]
- Second dequeue removes 2: [6]
Queue Variants
Double-Ended Queue (Deque):
- Insertion and deletion allowed at both ends
- More flexible than standard queues
Input Restricted Queue:
- Insertion only at rear
- Deletion allowed at both front and rear
Output-Restricted Queue:
- Insertion allowed at both front and rear
- Deletion only at front
Priority Queue:
- Elements have associated priorities
- Ascending: Lower priority values served first
- Descending: Higher priority values served first
- Not strictly FIFO - priority determines order
Implementation Note
A queue can be implemented using two stacks by transferring elements between stacks to maintain FIFO order. One stack handles enqueue operations, the other handles dequeue operations.
Enqueue Operation for Queue
The enqueue operation adds an element to the rear of a queue. This implementation handles both linear and circular queue scenarios.
Algorithm Structure:
Enqueue(QUEUE, n, front, rear, element)
Parameters:
QUEUE[0..n-1]= array representing the queuefront= index of first element (-1 when empty)rear= index of last element (-1 when empty)element= new element to insert
Complete Algorithm:
Step 1: Check for overflow
if ((front == 0 and rear == n-1) or (front == rear+1)) {
print "Overflow"
exit()
}
Step 2: Handle empty queue
if (front == -1)
front = rear = 0
Step 3: Handle circular wrap-around
else if (rear == n-1)
rear = 0
else
rear = rear + 1
Step 4: Insert element
QUEUE[rear] = element
- Next enqueue triggers overflow since 'rear' == n-1 and 'front' == 0
Note: This algorithm supports circular queues by wrapping 'rear' to 0 when it reaches the array end, maximizing space utilization.
Applications of Queue
Queues are fundamental data structures used across various computing applications due to their First-In-First-Out (FIFO) property.
Operating System Applications:
- Multiprogramming: Process scheduling where jobs wait in queue for CPU allocation
- CPU Scheduling: Ready queue holds processes waiting for execution time
- Resource Sharing: Print queues manage document printing order, ensuring fair access
Algorithm Applications:
- Breadth-First Search (BFS): Queue stores vertices to visit level by level in graph traversal
- Radix Sort: Uses queues (buckets) to sort numbers digit by digit from least to most significant
System Applications:
- Real-time Systems: Task queues prioritize time-critical operations
- Expression Evaluation: Queue temporarily stores operands during prefix expression parsing
Key Advantage: FIFO ordering ensures fairness - first request gets first service, preventing starvation in resource allocation.
Example - BFS Queue Usage
Starting from vertex A in graph traversal:
- Enqueue A
- Dequeue A, enqueue its neighbors B, C
- Dequeue B, enqueue its unvisited neighbors
- Continue until queue is empty
Remember: Choose queues when order of processing matters and fairness is required.
6.2 Circular Queue
Queue Operation for Queue
Dequeue Operation - removes element from front of circular queue:
dequeue(QUEUE, n, front, rear) {
if (front == -1) {
print "Queue Underflow"
exit(1)
}
element = QUEUE[front]
if (front == rear) {
// Please
}
}
Key Steps:
- Check if queue is empty (front == -1)
- Store element at front position
- Update front pointer based on queue state
Pointer Updates:
- Empty after removal: Set both front = rear = -1
- Front at last index: Wrap to front = 0 (circular behavior)
- Normal case: Increment front = front + 1
- Before: front = 3, rear = 1
- Remove element at position 3
- After: front = 4, rear = 1
Remember: Circular queue wraps front pointer to maintain continuous operation without shifting elements.
6.3 Double-Ended Queue (Deque)
Deque (Double Ended Queue)
A Deque (Double Ended Queue) is a linear data structure that allows insertions and deletions at both ends, combining the flexibility of stacks and queues.
Four basic operations:
- Insert Left (add element to front)
- Insert Right (add element to rear)
- Delete Left (remove element from front)
- Delete Right (remove element from rear)
Key properties:
- Elements can be accessed from both ends
- No restriction on which end to use for insertion/deletion
- Maintains linear ordering of elements
- Size can grow and shrink dynamically
Common implementations:
- Input-restricted deque: Insertion allowed at one end only, deletion at both ends
- Output-restricted deque: Deletion allowed at one end only, insertion at both ends
Example operations on deque [6, 7, 9]:
- Insert Left(3): [3, 6, 7, 9]
- Insert Right(14): [3, 6, 7, 9, 14]
- Delete Left(): removes 3, gives [6, 7, 9, 14]
- Delete Right(): removes 14, gives [6, 7, 9]
Applications:
- Palindrome checking
- Sliding window problems
- Undo-redo operations in applications
Time complexity: O(1) for all four operations when implemented with doubly linked list or circular array.
7. Trees
7.1 Tree Terminology (Root, Leaf, Height, Depth)
Overview
Trees, BSTs, and Binary Heaps are fundamental hierarchical data structures used extensively in computer science and programming.
Tree: A connected acyclic graph with nodes arranged in parent-child relationships. Each node has at most one parent (except root) and can have multiple children.
Binary Search Tree (BST): A binary tree where for each node:
- Left subtree contains values < node value
- Right subtree contains values > node value
- Enables efficient search, insertion, and deletion in O(log n) average time
Binary Heap: A complete binary tree satisfying the heap property:
- Max Heap: Parent ≥ children
- Min Heap: Parent ≤ children
- Used in priority queues and heap sort algorithm
Key Applications:
- BSTs: Database indexing, expression parsing
- Heaps: Priority scheduling, finding kth largest element
- General trees: File systems, decision trees, parsing
Time Complexities (Average Case):
- BST operations: O(log n)
- Heap insertion/deletion: O(log n)
- Heap peek (min/max): O(1)
Remember: Trees provide logarithmic performance for many operations, making them essential for efficient algorithm design.
Tree
- V = set of vertices (nodes)
- E = set of edges (connections)
Key Properties:
- Exactly one path exists between any two vertices
- No cycles or self-loops allowed
- Always connected (cannot be empty)
- Binary trees can be empty (special case)
Node Types:
Internal Node: Any node with at least one child
- Has degree ≥ 1
- Forms the structure of the tree
Leaf Node: A node with no children
- Has degree = 0
- Terminal points of the tree
External Node: Conceptual nodes that replace null pointers
- Used in theoretical analysis
- Not actual nodes but placeholders for missing children
Node Degree
The degree of a node is the number of children it has.
- Root can have degree ≥ 1
- Internal nodes have degree ≥ 1
- Leaf nodes have degree = 0
Tree Structure Example
Consider this tree organization:
Root
/ \
Node A Node B
/ \ / \
L1 L2 L3 L4
- Root: 1 internal node (degree 2)
- Internal nodes: A and B (degrees 2 and 2)
- Leaf nodes: L1, L2, L3, L4 (all degree 0)
- External nodes: 10 conceptual nodes (replacing null pointers)
Remember: In any tree with n nodes, there are exactly n - 1 edges.
7.2 Binary Tree
Properties
Basic Tree Properties
For any tree with n nodes:
- Number of edges = n - 1
- In linked representation: Number of NULL pointers = n + 1
Binary Tree Node Relationships
In any binary tree, if:
- n₀ = nodes with 0 children (leaf nodes)
- n₂ = nodes with 2 children
Then: n₀ = n₂ + 1
Heap/Array Indexing
0-based indexing (array starts at index 0):
- Parent of node at index i: (i - 1)/2
- Left child of node at index i: 2i + 1
- Right child of node at index i: 2i + 2
1-based indexing (array starts at index 1):
- Parent of node at index i: i/2
- Left child of node at index i: 2i
- Right child of node at index i: 2i + 1
Binary Tree Types
- Complete Binary Tree: Nodes filled level by level, left to right. Last level may be partially filled.
- Full Binary Tree: Every internal node has exactly 2 children, all leaves at same level.
- Strict Binary Tree: Every node has either 0 or 2 children (no nodes with exactly 1 child).
Note: All full binary trees are complete, but not vice versa.
Tree Size and Height Bounds
For a binary tree with n nodes:
- Maximum height: n (degenerate tree)
- Minimum height: ⌈log₂(n + 1)⌉ - 1
For a binary tree of height h:
- Maximum nodes: 2^(h+1) - 1
Array Storage Requirements
To store a binary tree with n nodes in array format:
- Maximum array size needed: 2^n - 1
- Minimum array size needed: 2^(h+1) - 1
Advanced Formulas
BST Count: Number of structurally different BSTs with n distinct keys:
T(n) = Σ_{k=1}^{n} T(k - 1) · T(n - k)
Node Rank: In binary tree, rank of node r:
Rank(r) = Number of nodes in left subtree of r
Total Binary Trees: Number of different binary trees with n labeled nodes:
(²ⁿCₙ / (n + 1)) × n!
where Cₙ is the n-th Catalan number.
7.3 Tree Traversals (Inorder, Preorder, Postorder, Level Order)
Binary Tree Traversals
Tree traversal is the process of visiting each node in a binary tree exactly once in a systematic order.
Main Traversal Methods
Depth-First Traversals (using recursion or stack):
- Inorder: Left → Root → Right
- Preorder: Root → Left → Right
- Postorder: Left → Right → Root
Breadth-First Traversal:
- Level Order: Visit nodes level by level from top to bottom
Traversal Details
Inorder Traversal
- For Binary Search Trees, gives nodes in sorted order
- Sequence: Process left subtree, visit root, process right subtree
Preorder Traversal
- Root is processed first
- Useful for deleting trees or calculating directory sizes
- Sequence: Process left subtree, process right subtree, visit root
Level Order Traversal
- Uses queue data structure
- Visits all nodes at depth d before visiting nodes at depth d + 1
Example Tree:
Traversal Techniques
Tree Traversal Methods
Four fundamental ways to visit nodes in a binary tree:
- Preorder Traversal (Root → Left → Right)
- Visit root first, then left subtree, then right subtree
- Used for: copying trees, prefix expressions
- Inorder Traversal (Left → Root → Right)
- Visit left subtree, then root, then right subtree
- Used for: sorted output in BSTs, infix expressions
- Postorder Traversal (Left → Right → Root)
- Visit left subtree, then right subtree, then root last
- Used for: deleting trees, postfix expressions
- Level Order Traversal (Breadth-First)
- Visit nodes level by level from top to bottom
- Used for: tree serialization, finding height
Example Tree Structure:
This represents the expression: (a + b) - (c * (d / (e + f)))
Traversal Results:
| Method | Output |
|---|---|
| Preorder | - + a b * c / d + e f |
| Inorder | a + b - c * d / e + f |
| Postorder | a b + c d e f + / * - |
| Level Order | - + * a b c / d + e f |
Note: Inorder traversal of expression trees naturally produces infix notation with proper operator precedence.
7.4 Binary Search Tree (BST)
Binary Search Tree (BST)
A Binary Search Tree maintains the ordering property where each node's value is greater than all values in its left subtree and less than all values in its right subtree.
BST Property: Left child < Root < Right child
Key Characteristics:
- Minimum element: leftmost node (keep going left from root)
- Maximum element: rightmost node (keep going right from root)
- Inorder traversal produces sorted sequence in ascending order
Time Complexity:
| Operation | Average Case |
|---|---|
| Space | O(n) |
| Search | O(log n) |
| Insert | O(log n) |
| Delete | O(log n) |
| Build | O(n log n) |
Note: Worst case occurs when BST becomes skewed (essentially a linked list).
Node Deletion Strategy:
- No children: Remove the node directly
- One child: Replace node with its child
- Two children: Replace node with either:
- Inorder successor (smallest value in right subtree)
- Inorder predecessor (largest value in left subtree)
Example: Deleting node with value 15 that has two children
- Find inorder successor: go right once, then keep going left
- Replace 15 with successor value and delete the successor node
Remember: Inorder traversal of any BST always gives sorted data - this property makes BSTs useful for maintaining sorted collections with efficient insertions and deletions.
7.5 Balanced BST Properties
B-tree (Balanced Search Tree)
A B-tree is a self-balancing search tree where all leaf nodes are at the same level, ensuring optimal search performance.
Node Structure
Root node: Contains 2 to p children (pointers)
Internal nodes: Each has ⌈p/2⌉ to p children
Leaf nodes: All positioned at the same level for balanced access
Block Size Formula
The storage requirement for each block:
Block Size = p × (pointer size) + (p - 1) × (key size)
where p is the maximum number of pointers per node.
Node Count Formulas
Minimum nodes in a B-tree of height h:
Min nodes = 1 + [2((p/2)^h - 1)] / [(p/2) - 2]
Maximum nodes in a B-tree of height h:
Max nodes = (p^(h+1) - 1) / (p - 1)
Height Calculations
Given l leaf nodes:
Minimum height: ⌈log_p l⌉
- Occurs when tree is completely filled
Example: For p = 4 and l = 10 leaves:
- Min height: log₄(10) = 2
- Max height: 1 + log₂((l + 1)/2) = 4
Remember: Lower height means faster search - B-trees automatically maintain balance to keep height minimal.
7.6 AVL Tree and Rotations
AVL Search Tree
AVL trees are height-balanced binary search trees that maintain optimal search performance by automatically rebalancing after insertions and deletions.
Balance Factor: For any node, the height difference between left and right subtrees:
B_f = h_L - h_R
AVL Property: |B_f| ≤ 1 for every node
Valid balance factors: -1, 0, or 1
Rotation Operations
When insertions or deletions violate the AVL property, rotations restore balance. Four rotation types handle different imbalance patterns:
- Right-Right (RR) Rotation - Single rotation for right-heavy imbalance
- Unbalanced structure: Root → Right child → Right grandchild
- Solution: Promote right child to new root, demote original root to left child
- Left-Left (LL) Rotation - Single rotation for left-heavy imbalance
- Unbalanced structure: Root → Left child → Left grandchild
- Solution: Promote left child to new root, demote original root to right child
- Left-Right (LR) Rotation - Double rotation:
- Unbalanced structure: Root → Left child → Right grandchild
- Solution: First rotate left child right, then rotate root left
- Right-Left (RL) Rotation - Double rotation:
- Unbalanced structure: Root → Right child → Left grandchild
- Solution: First rotate right child left, then rotate root right
Note: Double rotations handle "zigzag" patterns where the imbalance path changes direction.
Minimum Nodes Formula
For an AVL tree of height h, the minimum number of nodes follows:
This recurrence relation ensures the tree maintains the minimum possible nodes while preserving the AVL height constraint.
Example: For height 3:
- N_min(3) = 1 + N_min(2) + N_min(1) = 1 + 4 + 2 = 7 nodes
Remember: AVL trees guarantee O(log n) operations by keeping height approximately 1.44 log₂ n .
8. Heaps
8.1 Binary Heap (Min-Heap, Max-Heap)
Heap Tree
A heap is a complete binary tree that satisfies the heap property, where parent nodes maintain a specific ordering relationship with their children.
Types of Heaps
Min Heap: Every parent node has a value smaller than or equal to its children:
Max Heap: Every parent node has a value greater than or equal to its children:
Key Properties
- Complete binary tree: All levels filled except possibly the last, which fills left to right
- Heap property: Maintained at every subtree, not just the root
- Root access: Min heap root = smallest element, Max heap root = largest element
Heap Sort Algorithm
- Build a heap from the input array
- Repeatedly extract the root (min/max element)
- Place extracted element in the sorted output
- Restore heap property after each extraction
Time Complexity: O(n log n) for sorting n elements
Output ordering:
- Min heap deletion → ascending order (smallest first)
- Max heap deletion → descending order (largest first)
Example: Max heap [9, 7, 6, 2, 1]
- Extract 9 → remaining heap: [7, 2, 6, 1]
- Extract 7 → remaining heap: [6, 2, 1]
- Continue until sorted: [9, 7, 6, 2, 1] (descending)
Note: Heap sort is in-place but not stable (equal elements may change relative order).
9. Hashing
9.1 Hash Functions (Division, Multiplication, Universal)
Hashing
Hashing is a searching technique that achieves constant O(1) time complexity by using an indexing mechanism with a hash function to map keys directly to array positions.
Core Components
Hash Table: Array structure where elements are stored
Hash Function: Maps keys to array indices
Collision: When multiple keys map to the same index
Load Factor: Measures table fullness
Load Factor = Number of elements / Hash table size
Direct Address Table
Keys serve as direct array indices without transformation. While simple, this approach requires table size equal to the key range.
Limitation: If keys can be 64-bit values, table needs 2^64 - 1 positions, making it impractical for large key ranges.
Hash Functions
Division Method: Most common approach:
H(X) = X mod m
where m is the hash table size and X is the key.
Other Methods:
- Digit Extraction: Use specific digits from the key
- Mid Square: Square the key, extract middle digits
- Folding: Split key into parts, combine using fold shifting or fold boundary
Collision Resolution
When multiple keys hash to the same location, collision resolution techniques handle the conflict.
Open Addressing
All elements stored within the hash table itself.
Linear Probing: Check successive locations until empty slot found
- Disadvantage: Primary clustering - occupied slots form long consecutive sequences
Quadratic Probing: Use quadratic sequence for probing
Next position = h + i²
- Disadvantage: Secondary clustering - keys with same initial hash follow identical probe sequence
- Limitation: Not all table positions examined due to quadratic nature
Random Probing: Use random number generator for probe sequence
Y_new = (Y_old * C) mod m
where r is seed value, C is constant, m is table size
- Disadvantage: Random clustering still occurs
Double Hashing: Use second hash function to determine probe step size
- Advantage: Reduces clustering compared to other methods
- Disadvantage: Cannot completely eliminate clustering
Chaining
Store colliding elements in linked lists at each table position. Allows unlimited elements but requires additional memory for pointers.
Performance Note: Maximum comparisons for successful search equals size of largest cluster plus one.
9.2 Collision Resolution: Chaining
Chaining
Chaining is a collision resolution technique in hash tables that uses linked lists to handle multiple keys mapping to the same hash location.
Key Properties
- Uses linked list implementation at each hash table slot
- Number of elements at a location equals the length of that linked list
- No overflow issues since linked lists can grow dynamically
- Load factor: α = n/m where n = number of elements, m = table size, and α > 0
Operations Complexity
Deletion: Same as deleting a node from a singly linked list - requires traversal to find the element.
Search: Maximum comparisons for successful search equals the size of the largest linked list in the table.
Average Search Performance
The table below shows average number of comparisons for different collision resolution methods:
| Method | Successful Search |
|---|---|
| Linear Probing | (1/2)(1 + 1/(1 - α)) |
| Chaining | 1 + α/2 |
Read as: Method applied gives average comparisons for the search type.
Advantages
- No table overflow since chains can extend indefinitely
- Simple implementation using standard linked list operations
- Performance degrades gracefully as load factor increases
Note: Chaining performs better than linear probing when load factor α > 0.5, making it suitable for applications with high table utilization.
9.3 Load Factor and Rehashing
Note
Load Factor in hash tables measures how full the table is:
where:
- n = number of elements stored in the hash table
- m = total size of the hash table (number of slots)
Impact on Performance:
- Lower α → fewer collisions → better performance
- Higher α → more collisions → slower operations
Free Space Calculation:
Free space = (1 - α) × 100%
Example: If α = 0.7, then 30% of slots are empty.
Constraint for Open Addressing:
0 ≤ α ≤ 1
In open addressing (linear probing, quadratic probing), the load factor cannot exceed 1 since all elements must fit within the original table size.
Note: For separate chaining, α can exceed 1 as multiple elements can occupy the same slot through linked lists.
10. Graph Data Structures
10.1 Adjacency Matrix Representation
Time and Space Complexity With Each Data Structure
Time and Space Complexity Reference for Data Structures
Read as: Each row shows Average case complexities, then Worst case complexities, then Space complexity for that data structure.
Note: only the first part of this table is visible in the screenshot. The columns beyond "Average Case: Access" run off the right edge of the screen, so only the Data Structure column and the Average Case Access column are transcribed below.
| Data Structure | Average Case: Access |
|---|---|
| Array | O(1) |
| Stack | O(1) |
| Doubly Linked List | O(n) |
| Skip List | O(log n) |
| Hash Table | N/A |
| Binary Search Tree | O(log n) |
| Cartesian Tree | N/A |
| B-Tree | O(log n) |
| Red-Black Tree | O(log n) |
| Splay Tree | N/A |
| AVL Tree | O(log n) |
| KD Tree | O(log n) |
Key Insights
- Arrays: Direct access but expensive insertions/deletions due to shifting
- Linked Lists: Fast insertion/deletion at known positions, but linear search
- Hash Tables: Best for key-based operations, worst case occurs with collisions
- Balanced Trees (AVL, Red-Black, B-Tree): Guaranteed O(log n) operations
- BST: Can degrade to O(n) when unbalanced (becomes like a linked list)
- Skip Lists: Probabilistic data structure with expected O(log n) performance
Remember: θ notation shows tight bounds (average case), O notation shows upper bounds (worst case).