Docsity

Data Structure and algorithms, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
UNIT I โ€“ Linear Data Structures and Basic Algorithms
1. Introduction to Linear Data Structures
Definition:
A linear data structure arranges data elements sequentially, where each element is connected to
its previous and next element.
Examples: Arrays, Linked Lists, Stacks, Queues.
Importance:
Simplifies data access and manipulation.
Efficient memory utilization.
Foundation for complex structures (trees, graphs).
Used in searching, sorting, and memory management.
Characteristics:
Elements stored in contiguous or linked manner.
Traversal is sequential (one after another).
Fixed or dynamic size depending on implementation.
Examples:
Array: Static, index-based access.
Linked List: Dynamic, node-based access.
2. Abstract Data Types (ADTs) and Their Implementation
Definition:
ADT = Logical description of data + operations without specifying implementation.
Focuses on what operations are performed, not how.
Examples of ADTs:
1. List ADT: Insert, delete, traverse.
2. Stack ADT: Push, pop, peek.
3. Queue ADT: Enqueue, dequeue.
4. Map ADT: Key-value pairs.
Implementation:
Array-based: Fixed size, direct indexing.
Linked-based: Dynamic size, pointer connections.
Example: Stack ADT
Operations: push(x), pop(), peek()
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Data Structure and algorithms and more Study notes Data Structures and Algorithms in PDF only on Docsity!

UNIT I โ€“ Linear Data Structures and Basic Algorithms

1. Introduction to Linear Data Structures

Definition:

A linear data structure arranges data elements sequentially, where each element is connected to its previous and next element. Examples: Arrays, Linked Lists, Stacks, Queues.

Importance:

Simplifies data access and manipulation. Efficient memory utilization. Foundation for complex structures (trees, graphs). Used in searching, sorting, and memory management.

Characteristics:

Elements stored in contiguous or linked manner. Traversal is sequential (one after another). Fixed or dynamic size depending on implementation.

Examples:

Array: Static, index-based access. Linked List: Dynamic, node-based access.

2. Abstract Data Types (ADTs) and Their Implementation

Definition:

ADT = Logical description of data + operations without specifying implementation. Focuses on what operations are performed, not how.

Examples of ADTs:

  1. List ADT: Insert, delete, traverse.
  2. Stack ADT: Push, pop, peek.
  3. Queue ADT: Enqueue, dequeue.
  4. Map ADT: Key-value pairs.

Implementation:

Array-based: Fixed size, direct indexing. Linked-based: Dynamic size, pointer connections.

Example: Stack ADT

Operations: push(x), pop(), peek()

Implementation: Array: top index tracks last element. Linked List: top pointer points to last node.

3. Time and Space Complexity Analysis

Definition:

Time Complexity: Amount of time an algorithm takes. Space Complexity: Amount of memory used.

Notation:

Big O (O): Worst case. Omega (ฮฉ): Best case. Theta (ฮ˜): Average case.

Common Complexities:

Operation Best Average Worst Linear Search O(1) O(n) O(n) Binary Search O(1) O(log n) O(log n) Bubble Sort O(n) O(nยฒ) O(nยฒ) Selection Sort O(nยฒ) O(nยฒ) O(nยฒ) Insertion Sort O(n) O(nยฒ) O(nยฒ)

Example:

For an array of size n, accessing an element = O(1), traversing = O(n).

4. Searching Techniques

a) Linear Search

Definition:

Sequentially checks each element until the target is found.

Algorithm Steps:

  1. Start from first element.
  2. Compare each element with key.
  3. If match found โ†’ return index.
  4. If not found โ†’ return -1.

Example: [5, 3, 4, 1] โ†’ [3, 4, 1, 5] โ†’ [3, 1, 4, 5] โ†’ [1, 3, 4, 5]

b) Selection Sort

Definition:

Selects the smallest element and places it at the beginning.

Algorithm Steps:

  1. Find minimum element.
  2. Swap with first unsorted element.
  3. Repeat for all positions.

Complexity:

Best/Worst: O(nยฒ) Space: O(1)

Example: [4, 2, 5, 1] โ†’ [1, 2, 5, 4] โ†’ [1, 2, 4, 5]

c) Insertion Sort

Definition:

Builds sorted list one element at a time by inserting in correct position.

Algorithm Steps:

  1. Assume first element sorted.
  2. Pick next element.
  3. Insert into correct position in sorted part.

Complexity:

Best: O(n) Worst: O(nยฒ) Space: O(1)

Example: [5, 3, 4, 1] โ†’ [3, 5, 4, 1] โ†’ [3, 4, 5, 1] โ†’ [1, 3, 4, 5]

Summary Table

Topic Definition Example Time Complexity Linear Search Sequential search [10,20,30] O(n) Binary Search Divide & conquer [10,20,30,40] O(log n) Bubble Sort Swap adjacent [5,3,4,1] O(nยฒ) Selection Sort Select min [4,2,5,1] O(nยฒ) Insertion Sort Insert in order [5,3,4,1] O(nยฒ)

Perfect 10 Marks Answer Key Points:

Define each concept clearly. Mention algorithm steps. Include example. Write time and space complexity. Use short, crisp points.

Structure of Node:

struct Node { struct Node *prev; int data; struct Node *next; };

Representation: NULL โ† [Prev | Data | Next] โ†” [Prev | Data | Next] โ†’ NULL

Operations:

Traversal: Forward and backward using next and prev. Insertion: At beginning: new->next = head; head->prev = new; head = new. At end: Traverse till last node, adjust next and prev. At position: Adjust both next and prev pointers. Deletion: At beginning: head = head->next; head->prev = NULL. At end: last->prev->next = NULL. At position: Adjust both next and prev links. Searching: Traverse using next pointer.

Advantages: Bidirectional traversal, easier deletion. Disadvantages: Extra memory for prev pointer, complex insertion.

Example: NULL โ† 10 โ†” 20 โ†” 30 โ†’ NULL

3. Circular Linked List

Definition: Last node points back to the first node forming a circle.

Types:

Singly Circular Linked List: Last nodeโ€™s next points to head. Doubly Circular Linked List: Last nodeโ€™s next = head, headโ€™s prev = last.

Representation: Head โ†’ 10 โ†’ 20 โ†’ 30 โ†’ (back to Head)

Operations:

Traversal: Continue until reaching head again. Insertion: At beginning: Insert before head, adjust last nodeโ€™s next. At end: Insert after last node, link back to head.

Deletion: At beginning: Move head to next, adjust last nodeโ€™s next. At end: Traverse till second last, link to head. Searching: Traverse until found or back to head.

Advantages: No NULL, can traverse endlessly. Disadvantages: Complex insertion/deletion logic.

Example: 10 โ†’ 20 โ†’ 30 โ†’ (back to 10)

4. Comparing Arrays and Linked Lists

Feature Array Linked List Memory Allocation Static Dynamic Size Fixed Can grow/shrink Access Time O(1) (Direct) O(n) (Sequential) Insertion/Deletion Costly (shifting) Efficient (pointer change) Memory Usage Less (no pointers) More (extra pointer field) Traversal Forward only Forward/Backward (in DLL) Implementation Simple Complex

Example: Array: [10, 20, 30] Linked List: 10 โ†’ 20 โ†’ 30 โ†’ NULL

5. Applications of Linked Lists

Dynamic Memory Management: Used in memory allocation (malloc/free). Stacks and Queues: Implemented using linked lists. Polynomial Representation: Each term as a node. Sparse Matrices: Store only non-zero elements. Graphs: Adjacency list representation. Music/Video Playlists: Circular linked lists for continuous play. Undo/Redo Operations: Doubly linked lists. Hash Tables: Collision handling using chaining.

Example: Polynomial: 5xยณ + 4xยฒ + 2 โ†’ (5,3) โ†’ (4,2) โ†’ (2,0)

Summary Table

UNIT III โ€“ STACKS

1. Introduction to Stacks

Definition: A stack is a linear data structure that follows LIFO (Last In First Out) principle. Example: Stack of plates โ€“ last plate placed is the first to be removed. Representation: Top โ†’ [5] [4] [3] Bottom Terminology: Top: Pointer to the last inserted element. Push: Insert element into stack. Pop: Remove element from stack. Peek/Top: View top element without removing. Overflow: Stack full, cannot push. Underflow: Stack empty, cannot pop.

2. Properties of Stack

LIFO Order: Last inserted element is removed first. Single Access Point: Only top element accessible. Dynamic or Static: Can be implemented using arrays (static) or linked lists (dynamic). Reversibility: Can reverse order of elements easily. Recursive Nature: Supports recursion and backtracking.

3. Stack Operations

Operation Description Example (Stack: [10,20,30]) Push(x) Insert element x at top Push(40) โ†’ [10,20,30,40] Pop() Remove top element Pop() โ†’ returns 40, stack=[10,20,30] Peek() Return top element Peek() โ†’ 30 isEmpty() Check if stack empty False isFull() Check if stack full (array) Depends on size

4. Implementation of Stack Using Arrays

Representation: #define MAX 100 int stack[MAX];

int top = -1; Push Operation: if(top == MAX-1) printf("Overflow"); else stack[++top] = item; Pop Operation: if(top == -1) printf("Underflow"); else item = stack[top--]; Advantages: Simple, easy to implement. Disadvantages: Fixed size (static).

5. Implementation of Stack Using Linked List

Node Structure: struct Node { int data; struct Node* next; }; struct Node* top = NULL; Push Operation: newNode->next = top; top = newNode; Pop Operation: temp = top; top = top->next; free(temp); Advantages: Dynamic size, no overflow. Disadvantages: Extra memory for pointers.

6. Applications of Stack

a) Expression Evaluation

Types of Expressions: Infix: A + B Prefix (Polish): + A B Postfix (Reverse Polish): A B + Conversion: Infix โ†’ Postfix using stack for operators. Evaluation (Postfix Example): Expression: 5 6 2 + * 12 4 / - Steps: Push 5, Push 6, Push 2

  • โ†’ Pop 2,6 โ†’ 8 โ†’ Push 8
  • โ†’ Pop 8,5 โ†’ 40 โ†’ Push 40 Push 12, Push 4 / โ†’ Pop 4,12 โ†’ 3 โ†’ Push 3

10. Summary Table

Concept Key Point Structure LIFO Main Operations Push, Pop, Peek Implementations Array, Linked List Applications Expression evaluation, Backtracking, Reversal Advantages Simple, Efficient Disadvantages Limited access, Overflow/Underflow

UNIT IV โ€“ QUEUES AND DEQUES (10 MARKS NOTES)

1. Queues โ€“ Introduction

Definition: Linear data structure that follows FIFO (First In First Out) principle. Analogy: Like a queue at a ticket counter โ€“ first person in line is served first. Representation: Front โ†’ element to be deleted next Rear โ†’ position where new element is inserted

2. Properties of Queues

Linear structure with two ends: front and rear. Insertion (Enqueue) at rear end. Deletion (Dequeue) from front end. FIFO order maintained. Overflow: Queue is full (no more insertions). Underflow: Queue is empty (no deletions possible).

3. Queue Operations

  1. Enqueue(x): Insert element x at rear.
  2. Dequeue(): Remove element from front.
  3. Peek()/Front(): Return front element without removing.
  4. isEmpty(): Check if queue is empty.
  5. isFull(): Check if queue is full (for array implementation).

4. Implementation of Queue using Arrays

Representation: Use array Q[MAX] Two pointers: front, rear Initialization: front = -1, rear = - Enqueue Algorithm: a. Check if rear == MAX-1 โ†’ Overflow b. If front == -1, set front = 0 c. Increment rear and insert element Dequeue Algorithm: a. Check if front == -1 โ†’ Underflow b. Retrieve element at front c. If front == rear, reset both to - d. Else increment front Limitation: Wastage of space after deletions (solved by circular queue).

Example:

  1. getFront(): Return front element.
  2. getRear(): Return rear element.
  3. isEmpty(), isFull(): Check queue status.

Example:

Deque: [10, 20, 30] InsertFront(5) โ†’ [5, 10, 20, 30] DeleteRear() โ†’ [5, 10, 20]

9. Implementation of Deque

Array Implementation: Use circular array to efficiently manage both ends. Maintain front and rear pointers. Linked List Implementation: Doubly linked list preferred (easy access to both ends).

10. Applications of Deques

  1. Palindrome Checking: Compare characters from both ends.
  2. Sliding Window Problems: Maintain current window elements.
  3. Undo/Redo Operations: Insert/delete from both ends.
  4. Job Scheduling: Tasks can be added or removed from either end.

11. Comparison Table

Feature Queue Deque Insertion Rear only Both ends Deletion Front only Both ends Type FIFO Generalized queue Example Printer queue Palindrome checking

12. Summary

Queue: FIFO structure, used in BFS, scheduling. Deque: Double-ended, flexible insertion/deletion. Implementations: Array and Linked List. Key Operations: Enqueue, Dequeue, InsertFront, DeleteRear.

UNIT V โ€“ TREES AND HASHING (10 Marks Notes)

1. Introduction to Trees

Definition: A tree is a non-linear hierarchical data structure consisting of nodes connected by edges. Terminology: Root: Topmost node. Parent/Child: Directly connected nodes. Leaf: Node with no children. Degree: Number of children of a node. Depth/Height: Distance from root / longest path to leaf. Properties: If there are n nodes, there are (nโ€“1) edges. One root, multiple subtrees. Applications: Hierarchical data (file systems, organization charts). Expression evaluation. Routing algorithms.

2. Binary Search Tree (BST)

Definition: A binary tree where each node has: Left child < Parent node Right child > Parent node Properties: Efficient searching, insertion, and deletion (O(log n) average). In-order traversal gives sorted order.

3. BST Insertion

Steps: a. Compare new key with root. b. If smaller โ†’ go left; if larger โ†’ go right. c. Repeat until correct null position found. d. Insert new node. Example: Insert 50, 30, 70, 20, 40, 60, 80 โ†’ BST formed with 50 as root.

4. BST Deletion

Cases: a. Leaf Node: Delete directly. b. One Child: Replace node with its child. c. Two Children: Replace with inorder successor/predecessor.

All elements stored in table itself. Methods: Linear Probing: h(k,i) = (h(k)+i) mod m Quadratic Probing: h(k,i) = (h(k)+iยฒ) mod m Double Hashing: h(k,i) = (h1(k)+i*h2(k)) mod m

9. Hash Tables

Definition: Array-based structure storing key-value pairs using hash function. Operations: Insertion: Compute index โ†’ place key/value. Search: Compute index โ†’ compare keys. Deletion: Mark slot as deleted or remove key. Example: Keys: [10, 22, 31, 4, 15] h(k)=k mod 10 โ†’ Table indices: [0โ€“9].

10. Applications of Hashing

Unique Identifier Generation: Hash functions generate unique IDs (e.g., SHA, MD5). Caching: Quick lookup of stored results (e.g., web cache). Databases: Indexing and fast record retrieval. Symbol Tables: Compiler variable lookup. Password Storage: Store hashed passwords for security.

Summary Table

Concept Key Idea Example/Use

Tree Hierarchical structure File system

BST Ordered binary tree Search operations

Insertion Place node by comparison Insert 40 in BST

Deletion Remove node (3 cases) Delete 30

Traversal Visit nodes systematically Inorder โ†’ sorted

Hashing Map keys to indices Fast lookup

Hash Function Generates index h(k)=k mod m

Collision Same index for keys 10, 22 โ†’ index 2

Chaining Linked list at index Multiple keys

Open Addressing Probe next slot Linear probing

Hash Table Stores key-value pairs Database index

Applications Fast access, caching Unique IDs