Data Structures and Algorithms · Unit 1
Fundamentals of Data Structures and Algorithms
Exam-focused notes for Fundamentals of Data Structures and Algorithms (Data Structures and Algorithms, BIT201): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.
Fundamentals of Data Structures and Algorithms in short
A computer program works on data. How we store that data decides how fast and how simply the program runs. This chapter explains data structures, abstract data types, and the basic structures used to hold lists of values.
What this unit covers
- Definition of data structure
- Definition of abstract data type (ADT)
- Benefits of using ADT
- Primitive data types with examples
- Array as an ADT
- Static versus dynamic list structures
Primitive data types with examples
2082 · 10 marks
Define primitive data type with example.What are the advantages of hashing?With your own example show the hash collision and how do you handle it? Explain.[2+2+6]
Show solved answerHide answer
Primitive Data Type, Hashing, Collision and Collision Handling
1. Primitive Data Type (2 marks)
Definition: A primitive data type is a basic, built-in data type provided directly by a programming language. It is the most fundamental type of data that cannot be broken down into simpler data types. These types are predefined by the language and have a fixed size in memory.
Examples:
| Data Type | Description | Example Value |
|---|---|---|
int | Integer numbers | 5, -20, 100 |
float | Decimal/floating point numbers | 3.14, -0.5 |
char | Single character | 'A', 'z' |
boolean | True or false value | true, false |
For example, in C/Java:
int age = 21;-- hereintis a primitive data type storing a whole number.
2. Advantages of Hashing (2 marks)
Hashing is a technique of mapping keys to positions in a hash table using a hash function.
Advantages:
-
Fast Search (O(1) average): Hashing provides constant time average-case complexity for search, insert, and delete operations, which is much faster than linear search O(n) or binary search O(log n).
-
Efficient Storage and Retrieval: Data can be stored and retrieved very efficiently using a key, making it ideal for dictionaries, databases, and caches.
-
Direct Address Mapping: The hash function directly computes the storage location, avoiding sequential scanning.
-
Useful for Large Data Sets: Even with a large number of records, hashing maintains near-constant performance.
-
Easy Implementation of Symbol Tables: Compilers use hashing to implement symbol tables efficiently.
3. Hash Collision and Collision Handling (6 marks)
What is Hash Collision?
A hash collision occurs when two or more different keys produce the same hash value (index) using the hash function, meaning they map to the same location in the hash table.
My Own Example:
Hash Function:
h(key) = key mod 7
Hash Table Size = 7 (indices 0 to 6)
Keys to insert: 10, 20, 17, 24, 31
| Key | h(key) = key mod 7 | Index |
|---|---|---|
| 10 | 10 mod 7 = 3 | 3 |
| 20 | 20 mod 7 = 6 | 6 |
| 17 | 17 mod 7 = 3 | 3 -- COLLISION with 10! |
| 24 | 24 mod 7 = 3 | 3 -- COLLISION again! |
| 31 | 31 mod 7 = 3 | 3 -- COLLISION again! |
Keys 10, 17, 24, and 31 all hash to index 3 -- this is a hash collision.
Collision Handling Techniques
Method 1: Chaining (Open Hashing)
In chaining, each slot of the hash table holds a linked list. All keys that hash to the same index are stored in the linked list at that index.
After inserting 10, 20, 17, 24, 31 using chaining:
Index 0: NULL
Index 1: NULL
Index 2: NULL
Index 3: [10] -> [17] -> [24] -> [31] -> NULL
Index 4: NULL
Index 5: NULL
Index 6: [20] -> NULL
Advantages of Chaining:
- Simple to implement
- Hash table never becomes full
- Deletion is easy
Method 2: Open Addressing - Linear Probing (Closed Hashing)
In linear probing, if a collision occurs at index i, we check the next slot i+1, then i+2, and so on until an empty slot is found.
Formula:
h(key, i) = (h(key) + i) mod TableSize
where i = 0, 1, 2, ... (probe number)
Inserting 10, 20, 17, 24, 31 using Linear Probing (Table Size = 7):
| Step | Key | h(key) | Probe | Final Index |
|---|---|---|---|---|
| 1 | 10 | 3 | i=0, slot 3 empty | 3 |
| 2 | 20 | 6 | i=0, slot 6 empty | 6 |
| 3 | 17 | 3 | i=0, slot 3 full; i=1, slot 4 empty | 4 |
| 4 | 24 | 3 | i=0 full, i=1 full, i=2, slot 5 empty | 5 |
| 5 | 31 | 3 | i=0 full, i=1 full, i=2 full, i=3, slot 6 full, i=4, slot 0 empty | 0 |
Final Hash Table:
Index 0: 31
Index 1: NULL
Index 2: NULL
Index 3: 10
Index 4: 17
Index 5: 24
Index 6: 20
Advantages of Linear Probing:
- No extra memory needed for pointers
- Better cache performance
Disadvantage:
- Primary clustering -- long chains of filled slots can form, slowing down operations.
Summary Table
| Method | Idea | Handles Full Table? |
|---|---|---|
| Chaining | Linked list at each slot | Yes |
| Linear Probing | Next available slot | No (table can fill up) |
Conclusion: Hash collision is unavoidable in practice, but with proper handling techniques like chaining or open addressing the table keeps giving almost constant time access. Chaining is preferred when the number of keys is not known in advance or when deletions are frequent, while linear probing suits a table of fixed size where memory for pointers is not available. In both cases the load factor should be kept low (roughly 0.7 or less for open addressing) so that the average number of probes stays close to one.
Static versus dynamic list structures
2082 · 10 marks
Distinguish between static and dynamic list structure.Explain about linked list implementation of stack and queue.[2+8]
Show solved answerHide answer
Static vs Dynamic List Structure & Linked List Implementation of Stack and Queue
(a) Static vs Dynamic List Structure
| Feature | Static List Structure | Dynamic List Structure |
|---|---|---|
| Memory Allocation | Memory is allocated at compile time (fixed size) | Memory is allocated at run time (as needed) |
| Size | Size is fixed and cannot change during execution | Size can grow or shrink during execution |
| Implementation | Implemented using arrays | Implemented using linked lists |
| Memory Utilization | May waste memory (if underused) or overflow (if overused) | Efficient memory utilization; no wastage |
| Insertion/Deletion | Costly; requires shifting of elements | Easy; only pointer adjustments needed |
| Access | Direct/random access using index | Sequential access only |
| Example | int arr[100] | Singly/doubly linked list |
(b) Linked List Implementation of Stack and Queue
A. Linked List Implementation of Stack
A stack is a linear data structure that follows the LIFO (Last In First Out) principle. In linked list implementation, each node contains data and a pointer to the next node. The top pointer always points to the most recently inserted node.
Node Structure
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
[data | next] --> [data | next] --> [data | next] --> NULL
^
TOP
i. PUSH Operation (Insert at top)
Steps:
- Create a new node.
- Assign data to the new node.
- Make new node's
nextpoint to currenttop. - Update
topto the new node.
void push(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Stack Overflow\n");
return;
}
newNode->data = value;
newNode->next = top; // new node points to old top
top = newNode; // top updated to new node
}
Diagram (Push 10, 20, 30):
After Push(10): TOP -> [10 | NULL]
After Push(20): TOP -> [20 | *] -> [10 | NULL]
After Push(30): TOP -> [30 | *] -> [20 | *] -> [10 | NULL]
ii. POP Operation (Delete from top)
Steps:
- Check if stack is empty (top == NULL).
- Store the top node in a temporary pointer.
- Move
topto the next node. - Free the temporary node.
void pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return;
}
struct Node* temp = top;
printf("Popped: %d\n", temp->data);
top = top->next; // move top to next node
free(temp); // free old top
}
iii. PEEK / Display
void peek() {
if (top == NULL)
printf("Stack is Empty\n");
else
printf("Top element: %d\n", top->data);
}
B. Linked List Implementation of Queue
A queue is a linear data structure that follows the FIFO (First In First Out) principle. In linked list implementation, two pointers are maintained:
- FRONT -- points to the first node (deletion end)
- REAR -- points to the last node (insertion end)
Node Structure
struct Node {
int data;
struct Node* next;
};
struct Node* front = NULL;
struct Node* rear = NULL;
FRONT REAR
| |
[data|next] -> [data|next] -> [data|NULL]
i. ENQUEUE Operation (Insert at rear)
Steps:
- Create a new node.
- Assign data to the new node; set its
nextto NULL. - If queue is empty, both
frontandrearpoint to new node. - Otherwise, link the current
rear's next to new node and updaterear.
void enqueue(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Queue Overflow\n");
return;
}
newNode->data = value;
newNode->next = NULL;
if (rear == NULL) { // queue is empty
front = rear = newNode;
return;
}
rear->next = newNode; // link at rear
rear = newNode; // update rear
}
Diagram (Enqueue 10, 20, 30):
After Enqueue(10):
FRONT -> [10|NULL] <- REAR
After Enqueue(20):
FRONT -> [10|*] -> [20|NULL] <- REAR
After Enqueue(30):
FRONT -> [10|*] -> [20|*] -> [30|NULL] <- REAR
ii. DEQUEUE Operation (Delete from front)
Steps:
- Check if queue is empty (front == NULL).
- Store the front node in a temporary pointer.
- Move
frontto the next node. - If
frontbecomes NULL, setrearto NULL as well. - Free the temporary node.
void dequeue() {
if (front == NULL) {
printf("Queue Underflow\n");
return;
}
struct Node* temp = front;
printf("Dequeued: %d\n", temp->data);
front = front->next; // move front forward
if (front == NULL) { // queue became empty
rear = NULL;
}
free(temp); // release the old front node
}
Diagram (Dequeue from FRONT -> [10|] -> [20|] -> [30|NULL] <- REAR):
After Dequeue() (removes 10):
FRONT -> [20|*] -> [30|NULL] <- REAR
After Dequeue() (removes 20):
FRONT -> [30|NULL] <- REAR
After Dequeue() (removes 30):
FRONT = NULL, REAR = NULL (queue is empty again)
iii. DISPLAY Operation
void display() {
if (front == NULL) {
printf("Queue is empty\n");
return;
}
struct Node* temp = front;
printf("Queue (front to rear): ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
Conclusion
A linked list removes the fixed-size limitation of an array, so both structures grow and shrink with the data. In the stack only one pointer (top) is needed and both PUSH and POP work at the head of the list, while the queue needs two pointers, since ENQUEUE attaches at rear and DEQUEUE detaches at front. In both cases every operation touches a constant number of nodes, so PUSH, POP, ENQUEUE and DEQUEUE all run in O(1) time, and overflow occurs only when malloc itself fails.
Definition of abstract data type
2080 · 5 marks
Define data type and ADT. What are the benefits of using ADT? Explain [5]
Array as an ADT
2078 · 5 marks
What is data Structure? Explain an array as an abstract data type. [5]
Make Unit 1 stick
Practice BIT201 with flashcards & quizzes