0% found this document useful (0 votes)
8 views23 pages

DSA import q&a

The document provides a comprehensive overview of pointers in C, detailing their advantages such as dynamic memory allocation and efficient memory usage, as well as disadvantages like complexity and memory leaks. It also covers the declaration and initialization of pointers, accessing values through dereferencing, and the concept of multiple pointers to a variable. Additionally, the document discusses memory allocation types, stack operations, linked lists, and the differences between ordinary and circular queues.

Uploaded by

Mr. LION
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views23 pages

DSA import q&a

The document provides a comprehensive overview of pointers in C, detailing their advantages such as dynamic memory allocation and efficient memory usage, as well as disadvantages like complexity and memory leaks. It also covers the declaration and initialization of pointers, accessing values through dereferencing, and the concept of multiple pointers to a variable. Additionally, the document discusses memory allocation types, stack operations, linked lists, and the differences between ordinary and circular queues.

Uploaded by

Mr. LION
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Module -1

1) Define Pointer. Explain advantages and disadvantages of pointers. How do you


declare and ini alize the pointer? How do you access the value pointed to by a
pointer?

Ans: Pointer: a pointer is a programming language data type whose value refers
directly to (or "points to") another value stored elsewhere in the computer memory
using its address.

Advantages of Pointers in C for DSA

1. Dynamic Memory Alloca on:


o C provides func ons like malloc, calloc, realloc, and free that rely on pointers
to allocate and manage memory at run me, which is essen al for
implemen ng dynamic data structures like linked lists, trees, and graphs.
2. Efficient Memory Usage:
o Pointers allow efficient handling of large data structures by avoiding
unnecessary copying. For example, passing a pointer to an array instead of
copying the en re array to a func on reduces memory overhead.
3. Implementa on of Complex Data Structures:
o Pointers are the backbone of advanced data structures like linked lists, stacks,
queues, trees, and graphs, which cannot be implemented using only sta c
arrays.
4. Pass by Reference:
o Func ons in C can modify actual arguments by using pointers, enabling
efficient handling of data and reducing memory consump on.
5. Memory Access:
o Pointers enable direct access to memory addresses, allowing fine-grained
control over data manipula on and enabling low-level programming tasks.
6. Efficient Algorithm Implementa on:
o Algorithms involving recursion or backtracking, such as depth-first search
(DFS) in graphs, heavily rely on pointers for managing dynamic data structures
like stacks.
7. Interfacing with Hardware:
o In systems programming, pointers are essen al for interac ng directly with
hardware registers and memory-mapped devices.

Disadvantages of Pointers in C for DSA


1. Complexity:
o Understanding and debugging pointer opera ons can be challenging,
especially for beginners. Errors such as incorrect pointer arithme c or
mismanagement of memory are common.
2. Memory Leaks:
o Forge ng to free dynamically allocated memory using free leads to memory
leaks, which consume system resources over me.
3. Dangling Pointers:
o Dereferencing pointers that point to memory loca ons that have already
been freed (dangling pointers) can cause unpredictable behavior or crashes.
4. Null Pointer Dereferencing:
o Accessing or dereferencing null pointers leads to run me errors like
segmenta on faults.
5. Buffer Overflows:
o Improper pointer usage can result in buffer overflows, which are security
vulnerabili es that a ackers can exploit to execute malicious code.
6. Segmenta on Faults:
o Accessing invalid memory addresses (e.g., out-of-bounds array access) o en
causes segmenta on faults, leading to program crashes.
7. Manual Memory Management:
o C requires programmers to explicitly manage memory. This increases the risk
of errors like double freeing memory or memory fragmenta on.
8. Harder Maintenance:
o Programs using pointers tend to be harder to read, understand, and maintain
due to their complexity and the poten al for subtle bugs.
Declaring and Ini alizing a Pointer
1. Declara on: A pointer is declared using the * operator. The type of the pointer
indicates the type of the value it points to.
int *p; // Pointer to an integer
char *c; // Pointer to a character
float *f; // Pointer to a float
2. Ini aliza on: A pointer is ini alized by assigning it the address of a variable using the
address-of operator (&).
int a = 10;
int *p = &a; // Pointer `p` now holds the address of `a`
Alterna vely, a pointer can be ini alized to NULL (a null pointer) if it doesn't point to any
valid memory address yet.
int *p = NULL; // Pointer is ini alized but not poin ng to anything

Accessing the Value Pointed to by a Pointer


To access the value stored at the memory loca on the pointer points to, use the dereference
operator (*).
Example:
#include <stdio.h>
int main() {
int a = 10; // Declare a variable
int *p = &a; // Ini alize a pointer to the address of `a`
prin ("Value of a: %d\n", a);
prin ("Address of a: %p\n", &a);
prin ("Value of a using pointer: %d\n", *p);
prin ("Address stored in pointer: %p\n", p);
*p = 20;
prin ("Modified value of a: %d\n", a);
return 0;
}
2) Can we have mul ple pointers to a Variable? How pointers can be dangerous
ANS: Yes, in C, mul ple pointers can point to the same variable. Each pointer stores the
memory address of the variable, and any pointer can be used to access or modify the
value of the variable.

Example of Mul ple Pointers


#include <stdio.h>
int main() {
int a = 10;
int *p1 = &a;
int *p2 = &a;
prin ("Value of a using p1: %d\n", *p1);
prin ("Value of a using p2: %d\n", *p2);
*p1 = 20;
prin ("Value of a a er modifica on using p1: %d\n", *p2);
return 0;
}
How pointers can be dangerous : Answer is disadvantages of pointers
3) Differen ate between Sta c and Dynamic memory alloca ons.
ANS:

Aspect Sta c Memory Alloca on Dynamic Memory Alloca on


Alloca on Time Memory is allocated at compile- Memory is allocated at run me.
me.
Flexibility Fixed size; memory cannot be Flexible; memory can be resized
resized a er alloca on. dynamically during program
execu on.
Memory Allocated on the stack or in the Allocated in the heap memory.
Loca on global/sta c memory area.
Performance Faster, as memory alloca on and Slower, due to run me alloca on
dealloca on overhead are and dealloca on overhead.
minimal.
Life me Exists for the en re scope of the Exists un l explicitly deallocated
variable (e.g., local or global using free.
scope).
Applica ons Used for fixed-size arrays and Used for data structures like linked
variables where the size is lists, trees, graphs, and dynamic
known. arrays.
Syntax Example int arr[10]; (array size fixed at int *arr = (int *)malloc(10 *
compile- me). sizeof(int)); (allocated at run me).
Memory Automa cally handled by the Requires manual management
Management system. using malloc, calloc, realloc, and
free.
Error Risk Low risk of errors, as alloca on is Higher risk of errors, such as
handled by the compiler. memory leaks or dangling
pointers.
4) Differen ate between Structure and union . With Suitable example.

ANS:

5) Define Stack and its applica on and list and implement pop, push, is empty, isfull
opera on in stack using c .

ANS: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.
This means that the element that is inserted last is the one to be removed first. Stacks
can be implemented using arrays or linked lists.

Basic Opera ons on Stack:

1. Push: Adds an element to the top of the stack.

2. Pop: Removes the top element from the stack.

3. Peek (or Top): Returns the top element without removing it.

4. isEmpty: Checks if the stack is empty.

5. isFull: Checks if the stack is full (in case of array implementa on).

Applica ons of Stack


Stacks have numerous prac cal applica ons, some of which are outlined below:

1. Func on Call Management (Call Stack):

o When a func on is called, the local variables and the return address are
pushed onto the stack. Once the func on execu on is completed, the values
are popped off the stack, and control is returned to the calling func on.

2. Expression Evalua on:

o Stacks are widely used in evalua ng arithme c expressions, especially in


conver ng infix to pos ix expressions and evalua ng pos ix expressions. The
operators and operands are stored in the stack for processing.

3. Undo/Redo Opera ons:

o Stacks are used in applica ons that require undo and redo func onality. Each
opera on is pushed onto a stack, and the undo opera on pops from the stack
to revert the last change.

4. Backtracking Algorithms:

o Stacks are used in backtracking algorithms, such as solving mazes or puzzles.


The current path or state is stored in the stack, and when a dead-end is
reached, the algorithm pops the stack to backtrack.

5. Depth First Search (DFS):

o Stacks are used in the DFS algorithm for traversing graphs and trees. The stack
stores the nodes to be visited, and the algorithm processes them in a LIFO
manner.

6. Memory Management:

o In memory alloca on, stacks are used for managing the local variables of
func ons. The memory is allocated in a stack-like structure where each
func on call gets its own block of memory.

7. Parsing:

o Stacks are used in compilers to parse expressions, especially in syntax tree


construc on and evalua ng language grammar.

6) Study Sparse matrices


MODULE- 2

1) What is Linked list? Explain different types of linked list with a diagram.

Ans:

A linked list is a linear data structure, in which the elements are not stored at con guous
memory loca ons. The elements in a linked list are linked using pointers. In simple
words, a linked list consists of nodes where each node contains a data field and
a reference(link) to the next node in the list.

Types Of Linked Lists:

1. Singly Linked List

Singly linked list is the simplest type of linked list in which every node contains some data
and a pointer to the next node of the same data type.

The node contains a pointer to the next node means that the node stores the address of
the next node in the sequence. A single linked list allows the traversal of data only in one
way. Below is the image for the same:

2. Doubly Linked List

A doubly linked list or a two-way linked list is a more complex type of linked list that
contains a pointer to the next as well as the previous node in sequence.

Therefore, it contains three parts of data, a pointer to the next node, and a pointer to
the previous node. This would enable us to traverse the list in the backward direc on as
well.
3. Circular Linked List

A circular linked list is a type of linked list in which the last node’s next pointer points back
to the first node of the list, crea ng a circular structure. This design allows for con nuous
traversal of the list, as there is no null to end the list.

While traversing a circular linked list, we can begin at any node and traverse the list in
any direc on forward and backward un l we reach the same node we started. Thus, a
circular linked list has no beginning and no end. Below is the image for the same:

4. Doubly Circular linked list

Doubly Circular linked list or a circular two-way linked list is a complex type of linked list
that contains a pointer to the next as well as the previous node in the sequence. The
difference between the doubly linked and circular doubly list is the same as that
between a singly linked list and a circular linked list. The circular doubly linked list does
not contain null in the previous field of the first node.

2) Give the structure and defini on of singly linked list (SLL).

ANS: Singly Linked List (SLL)

A Singly Linked List (SLL) is a linear data structure where each element (node) contains
two parts:

1. Data: The actual data or value that the node stores.

2. Next: A pointer that holds the address of the next node in the list. The last node's
next pointer points to NULL, indica ng the end of the list.
The primary characteris c of a singly linked list is that it allows traversing in only one
direc on, from the first node (head) to the last node.

Structure of Singly Linked List (SLL)

Here’s the structure defini on of a singly linked list in C:

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data; // Data part of the node

struct Node *next; // Pointer to the next node in the list

};

3) What are the disadvantages of ordinary queue over circular queue? Discuss the
implementa on of circular queue

ANS:

1. Memory Wastage: An ordinary queue wastes memory as the front pointer moves
forward and unused space can't be reused, while a circular queue efficiently reuses
space by wrapping around.

2. Inefficient Use of Memory: An ordinary queue can’t use available space at the front
a er dequeuing elements, whereas a circular queue makes full use of available
memory.

3. Complexity: In an ordinary queue, dequeuing elements requires shi ing, adding


complexity, while a circular queue doesn’t need shi ing and is simpler to implement.

4. Risk of Overflow with Free Space: An ordinary queue may overflow even if there's
free space, while a circular queue only overflows when it’s genuinely full.

5. Difficulty in Implemen ng Circular Opera ons: An ordinary queue doesn’t support


circular behavior without complex adjustments, whereas a circular queue na vely
supports circular opera ons.

6. Fixed Size: An ordinary queue has a fixed size and cannot dynamically resize, whereas
a circular queue allows efficient use of memory and dynamic resizing.
4) Write a note on mul ple stack and priority queue.

ANS:

Mul ple Stack

A Mul ple Stack is a data structure that consists of mul ple stacks, where each stack
operates independently but they share a common underlying storage. The main idea is
to manage more than one stack in a single array or set of data structures.

Types of Mul ple Stacks:

1. Mul ple stacks in a single array: In this case, a single array is used to hold elements
of all the stacks. A common approach is to divide the array into segments, each
represen ng a separate stack. Each stack has its own set of pointers (top indices) to
keep track of the top element.

2. Independent stacks: Mul ple separate arrays are used to represent each stack
independently.

Opera ons:

 Push: Insert an element into one of the stacks.

 Pop: Remove an element from one of the stacks.

 Peek/Top: View the top element of a par cular stack without removing it.

 Is Empty: Check if a specific stack is empty.

Advantages of Mul ple Stacks:

 Efficient memory usage when mul ple stacks are needed, as they can share a single
array.

 Convenient for certain applica ons, such as implemen ng recursive algorithms or


managing different types of data concurrently.

Priority Queue

A Priority Queue is a special type of queue where each element is assigned a priority.
Elements with higher priority are dequeued before elements with lower priority,
regardless of their order of arrival. It is similar to a regular queue but differs in the way
elements are ordered.

Types of Priority Queues:


1. Max-priority Queue: The element with the highest priority is dequeued first.

2. Min-priority Queue: The element with the lowest priority is dequeued first.

Priority queues are typically implemented using:

 Heap (binary heap, Fibonacci heap)

 Array (sorted or unsorted)

 Linked List (sorted)

Opera ons:

1. Insert: Add an element to the queue with a specified priority.

2. Extract-Max/Min: Remove and return the element with the highest/lowest priority.

3. Peek: View the element with the highest/lowest priority without removing it.

4. Change Priority: Modify the priority of an element (if supported by the


implementa on).

Applica ons:

 Job scheduling: Tasks with higher priority are executed first.

 Huffman encoding: Used in data compression algorithms.

 Dijkstra's algorithm: Used in shortest path finding.

5) Define queue. Discuss how to represent queue using dynamic array.

ANS: Queue Defini on

A Queue is a linear data structure that follows the First In, First Out (FIFO) principle. This
means that the element that is inserted first is the one that gets removed first. It
operates like a queue at a cket counter, where the first person to arrive is the first one
to be served.

Basic Queue Opera ons:

1. Enqueue: Insert an element into the queue.

2. Dequeue: Remove an element from the queue.

3. Peek: View the front element without removing it.

4. Is Empty: Check if the queue is empty.

5. Is Full: Check if the queue is full (if using a fixed-size array).


Queue Representa on Using Dynamic Array

A dynamic array is an array that can grow and shrink in size during program execu on.
This dynamic nature allows us to represent a queue with a flexible size, unlike a sta c
array that requires a fixed size.

Dynamic Array Representa on of Queue:

In a dynamic array-based queue, the queue grows automa cally as elements are added
and shrinks as elements are removed. The basic opera ons in the dynamic array queue
are similar to those in a sta c array queue but with the ability to resize the array as
needed.

Opera ons in a Dynamic Array-Based Queue:

1. Enqueue: Add an element to the rear of the queue.

o If the array is full, dynamically resize it (typically doubling its size).

2. Dequeue: Remove an element from the front of the queue.

o A er removing an element, shi all other elements forward to maintain the


queue's structure.

3. Peek: View the front element without removing it.

4. Resize: The array size changes when the queue is full or when there’s unused space
a er dequeue opera ons.

MODULE – 3
1) Discuss Inorder, Preorder, postorder and level order traversal with suitable recursive
func on for each

ANS:

Tree Traversal

Tree traversal is the process of visi ng all the nodes in a tree in a specific order. The major
types of tree traversal are Inorder, Preorder, Postorder, and Level-order traversal. These
traversals are commonly used for binary trees.

1. Inorder Traversal (Le , Root, Right)

In Inorder traversal, the le subtree is visited first, followed by the root, and then the right
subtree.

 Recursive Func on:


Traverse the le subtree, visit the root node, and then traverse the right subtree.
 Example:
Given a binary tree:

/\

2 3

/\

4 5

The Inorder traversal would be: 4, 2, 5, 1, 3

2. Preorder Traversal (Root, Le , Right)

In Preorder traversal, the root is visited first, followed by the le subtree, and then the
right subtree.

 Recursive Func on:


Visit the root node, traverse the le subtree, and then traverse the right subtree.

 Example:
Given the same tree:

/\

2 3

/\

4 5

The Preorder traversal would be: 1, 2, 4, 5, 3

3. Postorder Traversal (Le , Right, Root)

In Postorder traversal, the le subtree is visited first, followed by the right subtree, and
then the root node.

 Recursive Func on:


Traverse the le subtree, then traverse the right subtree, and finally visit the root.

 Example:
Given the same tree:
1

/\

2 3

/\

4 5

The Postorder traversal would be: 4, 5, 2, 3, 1

4. Level-order Traversal (Breadth-First Traversal)

Level-order traversal visits all the nodes level by level, star ng from the root, and moving
from le to right across each level.

 Algorithm:
This traversal is typically implemented using a queue. We enqueue the root, and
then keep dequeueing nodes, visi ng them, and enqueuing their children un l the
queue is empty.

 Example:
Given the same tree:

/\

2 3

/\

4 5

The Level-order traversal would be: 1, 2, 3, 4, 5

2) Define Threaded Binary Tree. Discuss In-Threaded Binary Tree.

ANS: Threaded Binary Tree

A Threaded Binary Tree is a special type of binary tree in which the null pointers replaced
with threads. These threads point to either the in-order predecessor or in-order successor of
the node, which makes traversal more efficient.

The primary purpose of a threaded binary tree is to op mize the tree traversal process,
par cularly in-order traversal, by elimina ng the need for a stack or recursion. The threads
facilitate easy access to the next node in the traversal order.
In-Threaded Binary Tree

An In-Threaded Binary Tree is a type of threaded binary tree where only the right null
pointers are replaced by threads. These threads point to the in-order successor of the node,
which allows efficient in-order traversal without the need for recursion or a stack.

In a tradi onal binary tree, the right child pointer of a node is NULL for leaf nodes. In an in-
threaded binary tree, these NULL pointers are used to point to the next node in the in-order
traversal sequence, i.e., the in-order successor.

This modifica on helps in performing in-order traversal efficiently by following the threads
instead of recursively traversing the tree or using a stack.

Key Features of In-Threaded Binary Tree:

1. In-Order Successor Threading:


In an in-threaded binary tree, the right child of any node can either be a direct child
or a thread to the in-order successor (next node in the in-order traversal).

2. Le Subtree is Unchanged:
The le child pointers are not changed. They con nue to point to the actual le
children of the nodes (if they exist).

3. Right Child as Thread:


If the right child is NULL, it is converted into a thread that points to the node's in-
order successor. If the right child is not NULL, it behaves like a regular pointer.

4. Efficient In-Order Traversal:


In in-threaded binary trees, in-order traversal can be done without using a stack or
recursion because the threads guide you directly to the next node in the in-order
sequence.

Advantages of In-Threaded Binary Tree:

1. Efficient In-Order Traversal:


The main advantage of in-threaded binary trees is that in-order traversal can be
done in a non-recursive manner without using a stack, which improves efficiency and
reduces memory usage.

2. Simpler Traversal:
In-threaded binary trees eliminate the need for addi onal data structures like a
stack, making the traversal process simpler and more direct.

3. Memory Efficient:
Since the threads are embedded within the tree structure itself, there is no need for
an extra stack or recursion stack to maintain the state during traversal.
Disadvantages of In-Threaded Binary Tree:

1. Complexity in Inser on and Dele on:


Inser ng or dele ng nodes in an in-threaded binary tree is more complex than in a
regular binary tree because the threads must be updated appropriately a er any
modifica on.

2. Space Overhead:
Although the threads help in efficient traversal, they require addi onal memory. For
each node, the extra rightThread flag and the modified right pointer require extra
space.

3. Maintenance of Threads:
When nodes are inserted or deleted, the threading structure must be maintained
correctly, which adds complexity to opera ons on the tree.

MODULE- 4

1) Discuss Selec on Trees with example.

Ans: Page number: 127 in DSA notes

2) Define Graph.

Ans: Graph is an abstract data type (ADT) that consists of a set of objects that are connected
to each other via links. These objects are called ver ces and the links are called edges.

Usually, a graph is represented as G = {V, E}, where G is the graph space, V is the set of
ver ces and E is the set of edges. If E is empty, the graph is known as a forest.

And read the adjacency matrix construc on and adjacency list construc on

3) Define the following terminology with examples.

ANS: (i) Digraph : A Digraph (short for Directed Graph) is a type of graph in which the edges
have a direc on. In a directed graph, each edge has a star ng node (also called a source) and
an ending node (also called a des na on).
(ii) Weighted Graph : A weighted graph is a type of graph in which each edge has a weight or
cost associated with it. The weight of an edge typically represents a value such as distance,
me, cost, or any other quan ta ve measurement depending on the context of the problem
being modeled.

(iii) Self loop : A self-loop (or loop) is an edge in a graph that connects a vertex to itself. In
other words, it is a directed or undirected edge that starts and ends at the same vertex.

(iv) Parallel Edges: A parallel edge (or mul ple edge) refers to two or more edges that
connect the same pair of ver ces in a graph. In other words, mul ple edges exist between
the same two ver ces.
MODULE -5

1)Define collision ? What are the methods to resolve collision? Explain Linear probing with
an example.

Ans: Collision : A collision occurs when two or more keys are assigned the same hash
value. This can happen if the hash table is too small or the hash func on is poor.

Methods to Resolve Collisions


There are several methods used to handle collisions in hashing:
1. Chaining: This is the most common technique, where each table index contains a
linked list (or another dynamic data structure) to store mul ple values that hash to
the same index.
o If two keys collide, they are stored in a linked list at that index.
2. Open Addressing: This technique resolves collisions by finding another available slot
in the hash table. Several methods can be used within open addressing:
o Linear Probing
o Quadra c Probing
o Double Hashing
3. Rehashing: When the hash table becomes too full, rehashing can be done, which
involves resizing the table and rehashing all the keys.

Linear Probing
Linear Probing is a method of open addressing where, upon encountering a collision, the
algorithm checks the next available slot sequen ally in the hash table (i.e., in a linear
fashion) un l an empty slot is found.
How Linear Probing Works:
1. When a key is inserted into the hash table, the hash func on computes an index.
2. If the index is already occupied, the algorithm checks the next slot in the table (index
+ 1, index + 2, etc.) un l it finds an empty slot.
3. If the end of the table is reached, the search con nues from the beginning of the
table (wrapping around).
The main idea is to probe the table linearly for the next available slot, which helps in
resolving collisions.

Example of Linear Probing


Consider a hash table with 7 slots, and we use the hash func on hash(key) = key % 7 to
map the keys to their corresponding indices. The table size is 7.
Let’s insert the following keys: 10, 20, 15, 25, 30.
1. Insert key 10:
o hash(10) = 10 % 7 = 3
o The slot at index 3 is empty, so we insert 10 at index 3.
2. Insert key 20:
o hash(20) = 20 % 7 = 6
o The slot at index 6 is empty, so we insert 20 at index 6.
3. Insert key 15:
o hash(15) = 15 % 7 = 1
o The slot at index 1 is empty, so we insert 15 at index 1.
4. Insert key 25:
o hash(25) = 25 % 7 = 4
o The slot at index 4 is empty, so we insert 25 at index 4.
5. Insert key 30:
o hash(30) = 30 % 7 = 2
o The slot at index 2 is empty, so we insert 30 at index 2.

3) Explain in detail , about sta c and dynamic hashing.

Ans:

What is Sta c Hashing?

It is a hashing technique that enables users to lookup a definite data set. Meaning, the data
in the directory is not changing, it is "Sta c" or fixed. In this hashing technique, the resul ng
number of data buckets in memory remains constant.

Opera ons Provided by Sta c Hashing

 Delete- Search a record address and delete a record at the same address or delete a
chunk of records from records for that address in memory.
 Inser on -While entering a new record using sta c hashing, the hash func on (h)
calculates bucket address "h(K)" for the search key (k), where the record is going to
be stored.
 Search -A record can be obtained using a hash func on by loca ng the address of the
bucket where the data is stored.
 Update – It supports upda ng once it is traced in data bucket.

Advantages of Sta c Hashing

 Offers unparalleled performance for small-size databases.


 Allows Primary Key value to be used as a Hash Key.

Disadvantages of Sta c Hashing

 It cannot work efficiently with the databases that can be scaled.


 It is not a good op on for large-size databases.
 Bucket overflow issue occurs if there is more data and less memory.
What is Dynamic Hashing?

It is a hashing technique that enables users to lookup a dynamic data set. Means, the data
set is modified resul ng data bucket keeps increasing or decreasing depending on the
number of records.

In this hashing technique, the resul ng number of data buckets in memory is ever-changing.

Opera ons Provided by Dynamic Hashing

 Delete- Locate the desired loca on and support dele ng data (or a chunk of data) at
that loca on.
 Inser on -Support inser ng new data into the data bucket if there is a space available
in the data bucket.
 Query -Perform querying to compute the bucket address.
 Update – Perform a query to update the data.

Advantages of Dynamic Hashing

 It works well with scalable data.


 It can handle addressing large amount of memory in which data size is always
changing.
 Bucket overflow issue comes rarely or very late.

Disadvantages of Dynamic Hashing

 The loca on of the data in memory keeps changing according to the bucket size.
Hence if there is a phenomenal increase in data, then maintaining the bucket address
table becomes a challenge.

4) Discuss AVL tree with an example.

Ans:

5) Define red-black tree, Splay Tree. Discuss the method to insert an elemnt into Red-
Black Tree.

ANS:

Red-Black Tree:

A Red-Black Tree is a type of self-balancing binary search tree (BST) with an addi onal
property that helps maintain balance during inser on and dele on opera ons. The tree
sa sfies the following proper es:

1. Node Color: Each node is either red or black.


2. Root Property: The root is always black.

3. Leaf Property: Every leaf (NIL node) is black.

4. Red-Red Property: If a red node has children, both of them must be black. No two
red nodes can appear consecu vely along any path from the root to the leaf.

5. Black Height Property: Every path from a node to its descendant NIL nodes must
have the same number of black nodes.

These proper es ensure that the tree remains balanced with a me complexity of O(log n)
for search, inser on, and dele on opera ons, even a er a series of inser ons and
dele ons.

Splay Tree:

A Splay Tree is a self-adjus ng binary search tree in which recently accessed elements are
moved to the root of the tree using a series of tree rota ons. The key opera ons (search,
insert, delete) are followed by a splaying opera on that moves the accessed node to the
root, ensuring that frequently accessed nodes are quicker to access in the future.

The splay opera on is typically performed using three basic tree rota ons:

 Zig: Single rota on (if the node is the child of the root).

 Zig-Zig: Double rota on (if the node is the le or right child of a le or right child).

 Zig-Zag: Double rota on (if the node is the le child of a right child or right child of a
le child).

Though the average me complexity of a splay tree opera on is O(log n), the worst-case
me complexity can be O(n), as the tree might become unbalanced a er a sequence of
opera ons. However, the amor zed me complexity over a series of opera ons is s ll
O(log n).

Method to Insert an Element into a Red-Black Tree:

Inser ng an element into a Red-Black Tree involves two major steps:

1. Insert the node as in a regular binary search tree.

2. Fix the Red-Black Tree proper es that may be violated a er inser on.

The inser on procedure ensures that the Red-Black proper es are maintained through a
series of color flips and rota ons (le or right). Here’s how the process works:

Step-by-Step Method to Insert into a Red-Black Tree:

1. Inser on as a BST:
o Insert the new node as you would in a standard binary search tree (BST),
which involves finding the correct loca on for the new node.

o Ini ally, the new node is colored red.

2. Fix Viola ons of Red-Black Proper es: A er inser ng the node, there are three
poten al cases that can violate the Red-Black proper es, par cularly the Red-Red
property (two consecu ve red nodes) or the black height property. The following
steps are taken to fix these viola ons:

o Case 1: Parent of the new node is black:

 If the parent of the newly inserted node is black, the tree remains
valid, and no further ac ons are needed.

o Case 2: Parent of the new node is red:

 If the parent is red, then this violates the Red-Red property (two
consecu ve red nodes).

 In this case, the color of the parent and the uncle node must be
considered:

3. Case 2.1: Uncle is red:

 In this case, we perform a color flip. The parent and uncle


nodes are turned black, and the grandparent node is turned
red.

 A er the color flip, the grandparent becomes the new focus,


and the inser on process con nues.

4. Case 2.2: Uncle is black or NIL:

 Perform rota ons (le or right) to ensure balance:

 If the newly inserted node is the right child of the le


child of the grandparent or the le child of the right
child of the grandparent, a double rota on is
performed (le rota on followed by a right rota on, or
right rota on followed by a le rota on).

 If the newly inserted node is the le child of the le


child or the right child of the right child of the
grandparent, a single rota on is performed.

 A er rota on, the colors of the grandparent and parent nodes


are adjusted to maintain the Red-Black proper es.
3. Recoloring: A er performing rota ons and fixing the viola ons, the root node is
always recolored to black to maintain the property that the root is black.

Example of Inser on in Red-Black Tree:

Let’s take an example where we insert the element 10 into an ini ally empty Red-Black
Tree:

1. Insert 10:

o 10 becomes the root node, and since the root must always be black, it is
colored black.

10 (black)

2. Insert 20:

o 20 is inserted as the right child of 10 (in a typical binary search tree).

o 20 is colored red ini ally.

o Since the parent of 20 (node 10) is black, no further changes are needed.

10 (black)

20 (red)

3. Insert 30:

o 30 is inserted as the right child of 20.

o 30 is colored red ini ally.

o The parent (20) is red, viola ng the Red-Red property.

o The uncle (NIL node) is black.

o Since 30 is inserted as the right child of 20, perform a le rota on at 10.

o Recolor the parent and grandparent.

A er rota on and recoloring:

20 (black)

/ \

10 (red) 30 (red)

You might also like