DSA import q&a
DSA import q&a
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.
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.
3. Peek (or Top): Returns the top element without removing it.
5. isFull: Checks if the stack is full (in case of array implementa on).
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.
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 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:
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.
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:
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:
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.
A Singly Linked List (SLL) is a linear data structure where each element (node) contains
two parts:
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.
#include <stdio.h>
#include <stdlib.h>
struct Node {
};
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.
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.
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:
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.
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:
Peek/Top: View the top element of a par cular stack without removing it.
Efficient memory usage when mul ple stacks are needed, as they can share a single
array.
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.
2. Min-priority Queue: The element with the lowest priority is dequeued first.
Opera ons:
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.
Applica ons:
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.
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.
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.
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.
In Inorder traversal, the le subtree is visited first, followed by the root, and then the right
subtree.
/\
2 3
/\
4 5
In Preorder traversal, the root is visited first, followed by the le subtree, and then the
right subtree.
Example:
Given the same tree:
/\
2 3
/\
4 5
In Postorder traversal, the le subtree is visited first, followed by the right subtree, and
then the root node.
Example:
Given the same tree:
1
/\
2 3
/\
4 5
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
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.
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).
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:
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
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
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.
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.
Ans:
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.
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.
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.
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.
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.
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:
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).
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:
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.
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:
If the parent of the newly inserted node is black, the tree remains
valid, and no further ac ons are needed.
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:
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 Since the parent of 20 (node 10) is black, no further changes are needed.
10 (black)
20 (red)
3. Insert 30:
20 (black)
/ \
10 (red) 30 (red)