Vault Notes 🎧Listen

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:

Example: const int MAX_SIZE = 100;

Const with Pointers:

DeclarationPointer Modifiable
int *ptrYes
const int *ptrYes
int *const ptrNo
const int *const ptrNo

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:

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:

Scope behavior:

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 *):

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:

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:

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:

Non-Primitive Data Structures:

Storage-Based Classification

Linear Data Structures:

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 StructureAverage Case: Access
ArrayΘ(1)
StackΘ(n)
QueueΘ(n)
Singly Linked ListΘ(n)
Doubly Linked ListΘ(n)
Skip ListΘ(log n)
Hash TableN/A
Binary Search TreeΘ(log n)
Cartesian TreeN/A
B-TreeΘ(log n)
Red-Black TreeΘ(log n)
Splay TreeN/A
AVL TreeΘ(log n)
KD TreeΘ(log n)

Key Insights:

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:

Example: For int a = 17, b = 5;

Relational Operators:

Compare two values and return true (1) or false (0):

Example: For int x = 10, y = 20;

Logical Operators:

Combine or modify boolean expressions:

Truth table:

ABA && BA || B!A
00001
01011
10010
11110

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:

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.

PrecedenceOperators
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:

Modulus (%) with negative numbers:

The result takes the sign of the left operand:

String vs Character Array:

Character array: char s[] = "Test";

String pointer: char *s = "Test";

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

Case values: Must be compile-time constants

Fall-through behavior: Execution continues until break is encountered

Default placement: Can appear anywhere in the switch block

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:

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:

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:

Function pointers:

Complex declarations:

Parameter variations:

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:

Static Storage Class:

Variables that retain their value between function calls:

static int count = 0;  // 

Key properties:

Example: Function call counter

void increment() {
    static int calls = 0;  // retains value between
    calls++;
    printf("Called %d times", calls);
}

Register Storage Class:

Restrictions:

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:

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:

Why wild pointers are dangerous:

Example of wild pointer problem:

int *ptr;      // Wild pointer
*ptr = 100;    // Undefined behavior

Safe alternatives:

  1. Initialize to NULL:
int x = 5;
int *ptr = &x;   // Safe - points to [x] 
  1. 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:

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:

Critical for long-running programs:

Prevention rules:

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:

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:

Limitations:

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:

Example: Integer array starting at memory address 1000

Language variations:

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:

Example: Insert 15 into array [10, 20, 30, 40]

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)

Worst Case: O(n)

Average Case: O(n)

Example: Array [10, 20, 30, 40, 50]

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)?

Example: In array [10, 20, 30, 40, 50]

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:

Address(A[i][j]) = Base(A) + [(i - i₀) × n + (j - j₀)] × size

where:

Example: Array A[3][4] with base address 1000, element size 4 bytes, 0-indexed

Column Major Order Elements are stored column by column (complete first column, then second column, etc.). Address formula:

Address(A[i][j]) = Base(A) + [(j - j₀) × m + (i - i₀)] × size

Example: Same array A[3][4] in column major order

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:

n(n + 1) / 2

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:

Upper Triangular Matrix

Elements above and on the main diagonal are non-zero (aᵢⱼ ≠ 0 when i ≤ j). Storage size:

n(n + 1) / 2

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:

n(n - 1) / 2

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:

3n - 2

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)

Example:

char str[] = "GATE";
int len = strlen(str);   // returns 4

Parameter Passing Techniques

Different methods for passing arguments to functions:

TechniqueUses Actual Values
Call by valueYes
Call by referenceYes
Call by resultNo
Call by value-resultYes
Call by need Yes
Call by table Yes
Call by constant Yes

Key Differences:

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.

Dynamic Scoping Variable scope determined at run-time based on function call sequence.

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:

Key Properties:

Memory allocation:

Node size = sizeof(data) + sizeof(pointer)

Example Structure:

[Data| Next] -> [Data| Next] -> Data| N... [
DataNextDataNextDataN...
A singly linked list is drawn as a chain of node boxes in a row, read left to right. Each box is split into two parts: the first part holds the data value, and the second part, labelled Next, holds a pointer. An arrow leaves the Next part of each node and points to the next node in the chain, so the first node points to the second, and the second points to the third. The takeaway is that the nodes are linked one after another by pointers stored inside each node, and you follow the arrows in order to walk through the list.

Advantages:

Disadvantages:

Time Complexity:

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;

Insert at Beginning:

newnode->next = head;
head = newnode;

Insert in Middle:

newnode->next = node->next;
node->next = newnode;

Key Insight: The 2 pointer rule holds because:

  1. One pointer connects the new node into the chain
  2. One pointer updates an existing connection (or head/tail)

Example: Insert value 15 between nodes with values 10 and 20

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:

newNode->next = head;
head = newNode;

Deletion at Beginning To delete the first node from a linked list:

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:

Key Operations

Insertion:

Deletion:

Search: Can traverse in either direction for efficiency

Advantages over Singly Linked List

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):

  1. newnode->next = root
  2. newnode->prev = null
  3. root->prev = newnode
  4. root = newnode

The new node becomes the head, pointing forward to the old head and backward to null.

Insert at End (3 pointer modifications):

  1. newnode->next = null
  2. newnode->prev = lastnode
  3. lastnode->next = newnode

The new node becomes the tail, with the previous tail now pointing to it.

Insert Between Nodes (4 pointer modifications):

  1. newnode->next = currentnode->next
  2. newnode->prev = currentnode
  3. currentnode->next->prev = newnode
  4. currentnode->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:

  1. Update previous node's next pointer:
node->prev->next = node->next;
  1. Update next node's previous pointer:
node->next->prev = node->prev;
  1. Free the deleted node:
free(node);

Example: Removing node B from A ⇄ B ⇄ C

Edge cases:

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:

Primary Operations:

LIFO Behavior: The last element pushed is the first one popped.

Example: Stack with elements [5, 3, 8] where 8 is at top

Applications:

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 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:

  1. Check if stack is full (Top == N - 1)
  2. If full, report overflow and exit
  3. Increment top pointer
  4. Insert element at new top position
Example: Stack size N = 5, Current Top = 1

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:

  1. Check if stack is empty (Top == -1)
  2. If empty, report underflow and exit
  3. Store top element in temporary variable
  4. Decrement top pointer
  5. 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:

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:

Example: 5 3 2 * + evaluates as 5 + (3 * 2) = 11

Infix to Postfix Conversion

Converts human-readable expressions to stack-friendly format:

  1. Scan infix expression left to right
  2. Push operands directly to output
  3. For operators: pop stack until lower precedence found, then push current operator
  4. Handle parentheses by treating them as precedence boundaries

Precedence order: ^ > * / > + -

Tower of Hanoi

Classic recursive puzzle using stack principle:

Mathematical Sequences

Fibonacci Calculation: Stack stores intermediate values during recursive computation of F(n) = F(n - 1) + F(n - 2)

Permutation Generation: Stack tracks current permutation state and backtracking points when generating all possible arrangements.

Symbol Balancing

Validates matching brackets, parentheses, and braces:

Common pairs: { }, [ ], ( )

Subroutine Management

Stack maintains the call hierarchy in programs:

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:

Basic Operations:

Example: Enqueue 1, 2, 6 then dequeue twice

Queue Variants

Double-Ended Queue (Deque):

Input Restricted Queue:

Output-Restricted Queue:

Priority Queue:

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:

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

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:

Algorithm Applications:

System Applications:

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:

  1. Enqueue A
  2. Dequeue A, enqueue its neighbors B, C
  3. Dequeue B, enqueue its unvisited neighbors
  4. 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:

  1. Check if queue is empty (front == -1)
  2. Store element at front position
  3. Update front pointer based on queue state

Pointer Updates:

Example: Queue with n = 5, elements at positions 3, 4, 0, 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:

Key properties:

Common implementations:

Example operations on deque [6, 7, 9]:

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:

Binary Heap: A complete binary tree satisfying the heap property:

Key Applications:

Time Complexities (Average Case):

Remember: Trees provide logarithmic performance for many operations, making them essential for efficient algorithm design.

Tree

A tree is a hierarchical data structure defined as T = (V, E) where:

Key Properties:

Node Types:

Internal Node: Any node with at least one child

Leaf Node: A node with no children

External Node: Conceptual nodes that replace null pointers

Node Degree

The degree of a node is the number of children it has.

Tree Structure Example

Consider this tree organization:

RootABL1L2L3L4
This diagram shows a tree with three levels. At the top is the root, the single starting node. The root has two children: Node A on the left and Node B on the right. Node A has two children, the leaves L1 and L2. Node B has two children, the leaves L3 and L4. Reading top to bottom and left to right: Root, then A and B, then L1, L2, L3 and L4. Every internal node here has exactly two children, and the four bottom nodes are leaves with no children. The takeaway: a tree branches downward from one root through internal nodes and ends at leaf nodes.
        Root
       /    \
   Node A    Node B
   /  \      /  \
  L1   L2   L3   L4

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:

Binary Tree Node Relationships

In any binary tree, if:

Then: n₀ = n₂ + 1

Heap/Array Indexing

0-based indexing (array starts at index 0):

1-based indexing (array starts at index 1):

Binary Tree Types

Note: All full binary trees are complete, but not vice versa.

Tree Size and Height Bounds

For a binary tree with n nodes:

For a binary tree of height h:

Array Storage Requirements

To store a binary tree with n nodes in array format:

Advanced Formulas

BST Count: Number of structurally different BSTs with n distinct keys:

T(n) = Σ_{k=1}^{n} T(k - 1) · T(n - k)

m-ary Tree Leaves: In complete m-ary tree, if nᵢ = nodes with degree i:
n₀ = 1 + Σ_{i=2}^{m} (i - 1)nᵢ

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):

  1. Inorder: Left → Root → Right
  2. Preorder: Root → Left → Right
  3. Postorder: Left → Right → Root

Breadth-First Traversal:

  1. Level Order: Visit nodes level by level from top to bottom

Traversal Details

Inorder Traversal

Preorder Traversal

Level Order Traversal

Example Tree:

This diagram shows an example binary tree drawn as text art. At the top is one root node. From the root, two edges slant down, one to the left and one to the right, reaching two child nodes. Each child again splits into two children below it, so the tree has three levels and ends in leaf nodes at the bottom with no children. The takeaway is the shape of a binary tree: every node has at most two children, a left child and a right child, arranged level by level under the root.
Remember: Inorder of BST = sorted sequence

Traversal Techniques

Tree Traversal Methods

Four fundamental ways to visit nodes in a binary tree:

  1. Preorder Traversal (Root → Left → Right)
  1. Inorder Traversal (Left → Root → Right)
  1. Postorder Traversal (Left → Right → Root)
  1. Level Order Traversal (Breadth-First)

Example Tree Structure:

-+*abc/d+ef
This diagram shows an expression tree, a binary tree where the inner nodes are arithmetic operators and the leaves are operands. Start at the top: the root is a minus sign. Down-left from the root is a plus sign with two leaves under it, a on the left and b on the right, meaning a plus b. Down-right from the root is a multiplication sign. Its left leaf is c. Its right child is a division sign. The division sign has d as its left leaf, and a plus sign as its right child, and that plus sign has leaves e on the left and f on the right, meaning e plus f. Putting it together in reading order, the tree represents the expression: open bracket a plus b close bracket, minus, open bracket c multiplied by open bracket d divided by open bracket e plus f close bracket close bracket close bracket. The takeaway is that the tree structure itself fixes the order of operations, so no brackets are needed when the tree is traversed.

This represents the expression: (a + b) - (c * (d / (e + f)))

Traversal Results:

MethodOutput
Preorder- + a b * c / d + e f
Inordera + b - c * d / e + f
Postordera 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:

Time Complexity:

OperationAverage Case
SpaceO(n)
SearchO(log n)
InsertO(log n)
DeleteO(log n)
Build O(n log n)

Note: Worst case occurs when BST becomes skewed (essentially a linked list).

Node Deletion Strategy:

  1. No children: Remove the node directly
  2. One child: Replace node with its child
  3. Two children: Replace node with either:

Example: Deleting node with value 15 that has two children

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⌉

Example: For p = 4 and l = 10 leaves:

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:

  1. Right-Right (RR) Rotation - Single rotation for right-heavy imbalance
  1. Left-Left (LL) Rotation - Single rotation for left-heavy imbalance
  1. Left-Right (LR) Rotation - Double rotation:
  1. Right-Left (RL) Rotation - Double rotation:

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:

N_min(h) = { 1, if h = 0; 2, if h = 1; 1 + N_min(h - 1) + N_min(h - 2), if h > 1 }

This recurrence relation ensures the tree maintains the minimum possible nodes while preserving the AVL height constraint.

Example: For height 3:

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:

parent ≤ children

Max Heap: Every parent node has a value greater than or equal to its children:

parent ≥ children

Key Properties

Heap Sort Algorithm

  1. Build a heap from the input array
  2. Repeatedly extract the root (min/max element)
  3. Place extracted element in the sorted output
  4. Restore heap property after each extraction

Time Complexity: O(n log n) for sorting n elements

Output ordering:

Example: Max heap [9, 7, 6, 2, 1]

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:

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

Quadratic Probing: Use quadratic sequence for probing

Next position = h + i²

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

Double Hashing: Use second hash function to determine probe step size

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

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:

MethodSuccessful Search
Linear Probing(1/2)(1 + 1/(1 - α))
Chaining1 + α/2

Read as: Method applied gives average comparisons for the search type.

Advantages

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:

α = n/m

where:

Impact on Performance:

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 StructureAverage Case: Access
ArrayO(1)
StackO(1)
Doubly Linked ListO(n)
Skip ListO(log n)
Hash TableN/A
Binary Search TreeO(log n)
Cartesian TreeN/A
B-TreeO(log n)
Red-Black TreeO(log n)
Splay TreeN/A
AVL TreeO(log n)
KD TreeO(log n)

Key Insights

Remember: θ notation shows tight bounds (average case), O notation shows upper bounds (worst case).