0% found this document useful (0 votes)
4 views16 pages

DSA Important Questions & Solutions

Uploaded by

mocoj50257
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)
4 views16 pages

DSA Important Questions & Solutions

Uploaded by

mocoj50257
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

Great — I see this is a photo of DSA important questions (3rd sem VTU), covering Module 2 &

Module 3.
You asked for solutions, so let me write them neatly, one by one.

---

✅ Module 2 (Queues & Linked Lists)


Q21. Define queue. Describe queue insert and delete procedure for queue using arrays.

Queue: Linear data structure following FIFO (First In First Out) principle.

Insert (Enqueue): Add element at rear.

Delete (Dequeue): Remove element from front.

👉 Pseudocode (array implementation):


#define SIZE 5
int queue[SIZE], front = -1, rear = -1;

void enqueue(int x) {
if (rear == SIZE - 1)
printf("Overflow");
else {
if (front == -1) front = 0;
rear++;
queue[rear] = x;
}
}

void dequeue() {
if (front == -1 || front > rear)
printf("Underflow");
else {
printf("Deleted: %d", queue[front]);
front++;
}
}

---
Q22. What are circular queues? Write its advantages/disadvantages. Solve problem using
dynamic allocation arrays.

Circular Queue: Queue where last element connects back to first → avoids wasted space.

Advantages: Efficient use of space, no shifting.

Disadvantages: Harder implementation than linear queue.

👉 Example (dynamic allocation):


int *cq, front = -1, rear = -1, SIZE;

void enqueue(int x) {
if ((front == 0 && rear == SIZE-1) || (rear+1)%SIZE == front)
printf("Overflow");
else {
if (front == -1) front = 0;
rear = (rear+1) % SIZE;
cq[rear] = x;
}
}

void dequeue() {
if (front == -1) printf("Underflow");
else {
printf("Deleted: %d", cq[front]);
if (front == rear) front = rear = -1;
else front = (front+1) % SIZE;
}
}

---

Q23. Difference between arrays and linked lists.

Arrays​ Linked Lists

Fixed size​ Dynamic size


Contiguous memory​ Non-contiguous
Easy random access​ Sequential access
Insertion/deletion costly​ Efficient insertion/deletion
Memory may waste​ No wastage, but overhead of pointers

---

Q24. Operations on singly linked lists. Write C programs.


(i) Deletion from end
(ii) Insertion at position

👉 Example:
struct Node { int data; struct Node* next; };

void insertAtPos(struct Node** head, int pos, int val) {


struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = val;
if (pos == 1) {
newNode->next = *head;
*head = newNode;
return;
}
struct Node* temp = *head;
for (int i=1; i<pos-1 && temp!=NULL; i++)
temp = temp->next;
if (temp == NULL) return;
newNode->next = temp->next;
temp->next = newNode;
}

void deleteFromEnd(struct Node** head) {


if (*head == NULL) return;
struct Node* temp = *head;
if (temp->next == NULL) { free(temp); *head = NULL; return; }
while (temp->next->next != NULL) temp = temp->next;
free(temp->next);
temp->next = NULL;
}

---

Q25. Develop a C function to add 2 polynomials using singly linked list.


👉 Represent polynomial as linked list nodes (coeff, pow). Traverse both lists and add powers.
---

Q26. Discuss how to implement stacks and queues using linked list.

Stack (LIFO): Insert/delete at head.

Queue (FIFO): Insert at rear, delete at front.

---

Q27. What is linked list? Explain different types.

Linked List: Collection of nodes connected by pointers.

Types:

1. Singly linked list

2. Doubly linked list

3. Circular linked list

4. Circular doubly linked list

---

✅ Module 3 (Doubly & Circular Linked Lists)


Q28. Define doubly linked list. Write its advantages/disadvantages.

DLL: Node contains data, next pointer, and prev pointer.


Advantages: Bi-directional traversal, easy deletion.

Disadvantages: Extra memory for prev, slower due to two links.

---

Q29. What is circular doubly linked list?

CDLL: Last node’s next points to first, and first node’s prev points to last.

---

Q30. Write a function to perform insertion & deletion in circular doubly linked list.

👉 Example:
struct Node { int data; struct Node* next; struct Node* prev; };

void insertEnd(struct Node** head, int val) {


struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = val;
if (*head == NULL) {
newNode->next = newNode->prev = newNode;
*head = newNode;
return;
}
struct Node* last = (*head)->prev;
newNode->next = *head;
(*head)->prev = newNode;
newNode->prev = last;
last->next = newNode;
}

void deleteNode(struct Node** head, int key) {


if (*head == NULL) return;
struct Node* curr = *head, *prev;
while (curr->data != key) {
if (curr->next == *head) return;
curr = curr->next;
}
if (curr->next == curr && curr->prev == curr) { free(curr); *head = NULL; return; }
if (curr == *head) *head = (*head)->next;
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
free(curr);
}

---

👉 These are complete solutions for the questions shown in your image.
Do you want me to also prepare short handwritten-style notes/answers (like exam-ready)
instead of full C code?

Perfect 👍 this page contains Binary Trees & Graphs (Module-4) important questions.​
I’ll give you exam-ready solutions (definitions, explanations + short pseudocode) for each.

✅ Binary Trees
Q31. Define binary tree. List & discuss any two properties of binary tree.

●​ Binary Tree: A tree where each node has at most two children (left & right).

👉 Properties:
1.​ Maximum nodes at level k = 2^k.
2.​ Maximum nodes in a binary tree of height h = 2^(h+1) – 1.

Q32. Explain threaded binary tree. Discuss its types.

●​ Threaded Binary Tree: Uses NULL pointers in binary tree to store special links called
“threads” → helps in inorder traversal without recursion/stack.

👉 Types:
1.​ Single threaded → either left or right NULL replaced with thread.
2.​ Double threaded → both left & right NULL pointers replaced with threads.
Q33. Discuss how binary tree nodes are represented using arrays & linked list.

●​ Array Representation:​

○​ Root stored at index 1.


○​ For node at i: left child = 2i, right child = 2i+1.
○​ Efficient for complete binary tree.

Linked List Representation:​



struct Node {
int data;
struct Node *left, *right;
};

●​ Each node has pointers to left & right children.​

Q34. Discuss inorder, preorder, postorder & level order traversal. Write recursive
functions.

👉 Traversals
1.​ Inorder (L, Root, R)
2.​ Preorder (Root, L, R)
3.​ Postorder (L, R, Root)
4.​ Level order – BFS using queue.

👉 Recursive functions (C):


void inorder(struct Node* root) {
if(root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}

void preorder(struct Node* root) {


if(root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}

void postorder(struct Node* root) {


if(root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}

Q35. What is tree? Explain its types with suitable examples.

●​ Tree: Hierarchical data structure with nodes connected by edges.


●​ Types:
○​ Binary tree
○​ Binary search tree (BST)
○​ AVL tree (balanced)
○​ Complete binary tree
○​ Full binary tree
○​ Threaded binary tree

Q36. Problems on binary tree (example given in image).

👉 If tree is:
A
/\
B C
/\ \
D E H
/\ \
F G I
\
J

●​ Inorder (L,Root,R): D B F E G A C H I J
●​ Preorder (Root,L,R): A B D E F G C H I J
●​ Postorder (L,R,Root): D F G E B J I H C A
Q37. Draw binary search tree (BST) from array {10,20,30,40,50}. Show linked list
representation.

👉 BST from {10,20,30,40,50}:


10
\
20
\
30
\
40
\
50

👉 Linked list representation (C):


struct Node {
int data;
struct Node* left;
struct Node* right;
};

✅ Graphs
Q38. What is graph? Give difference between tree & graph.

●​ Graph: Set of vertices (V) and edges (E). Can be directed/undirected.

👉 Tree vs Graph
Tree Graph

Hierarchical General structure

Connected, no cycles May be cyclic/disconnected

If n nodes → (n-1) edges No fixed edge rule

Q39. Write an algorithm for BFS & DFS.


👉 BFS (using queue):
BFS(G, start):
create a queue Q
mark start as visited, enqueue it
while Q not empty:
v = dequeue(Q)
for each unvisited neighbor u of v:
mark u visited
enqueue(u)

👉 DFS (using recursion):


DFS(v):
mark v visited
for each unvisited neighbor u of v:
DFS(u)

✅ These are full solutions for Module-4 (Binary Trees & Graphs).
Would you like me to also create a summary notes PDF (exam-crash sheet) combining
Modules 2, 3, and 4?

Nice 👍 this page has continuation of Graphs & Trees problems + start of Module-5
(Hashing & Advanced Trees).​
Let’s solve them one by one in a clear exam-ready format.

✅ Graphs & Trees (continuation)


👉
Q40. Explain the types of graphs with suitable examples. Define the following:​
Types of Graphs

●​ Directed Graph (Digraph): Edges have direction. Example: (A→B).


●​ Undirected Graph: Edges don’t have direction. Example: (A—B).
●​ Weighted Graph: Edges have weights/costs. Example: Road map with distances.
●​ Complete Graph: Every node connected to every other node.
●​ Cyclic Graph: Contains at least one cycle.
●​ Acyclic Graph: No cycles (e.g., trees).

👉 Definitions:
1.​ Degree of node: Number of edges incident on a node. (In-degree / Out-degree for
directed graphs).
2.​ Level of a binary tree: Distance of a node from the root (root = level 0).
3.​ Complete binary tree: All levels except possibly last are completely filled, last level
filled left to right.
4.​ Full binary tree: Every node has either 0 or 2 children.

Q41. Problems on graphs & trees.​


This refers to practice problems like BFS/DFS traversals, finding levels, computing height, etc.

Q42. Develop C functions to implement:​


(i) Search key in Binary Search Tree (BST)

struct Node { int data; struct Node* left; struct Node* right; };

struct Node* search(struct Node* root, int key) {


if (root == NULL || root->data == key) return root;
if (key < root->data) return search(root->left, key);
else return search(root->right, key);
}

(ii) Copying a binary tree

struct Node* copy(struct Node* root) {


if (root == NULL) return NULL;
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = root->data;
newNode->left = copy(root->left);
newNode->right = copy(root->right);
return newNode;
}

Q43. Explain concept of Binary Search Tree (BST). How it maintains order of elements?

●​ BST: Binary tree where left child < root < right child.
●​ Order maintained:
○​ Insertion places node at correct position based on comparisons.
○​ Traversals (e.g., inorder) give sorted order of elements.
👉 Operations:
●​ Insertion: Place new node by comparing with root.
●​ Deletion: 3 cases → delete leaf, delete node with 1 child, delete node with 2 children
(replace with inorder successor).
●​ Searching: Repeated comparisons (similar to binary search).

Q44. Define Selection Tree. Explain its application in finding kth smallest/largest element.

●​ Selection Tree: A complete binary tree used to find the smallest/largest element
efficiently.
●​ Process: Compare elements pairwise, propagate winners up the tree.
●​ Application: Used in tournament problems, finding kth element by repeated elimination.

Q45. Explain forests. How do they differ from trees? Explain adjacency sets & methods of
representation.

●​ Forest: Collection of disjoint trees.


●​ Difference: Tree is connected + acyclic; forest is group of multiple disconnected trees.
●​ Adjacency sets: Each vertex has a set of its neighbors.
●​ Representations:
1.​ Adjacency matrix (2D array)
2.​ Adjacency list (linked lists or vectors)
3.​ Incidence matrix

✅ Module 5 (Hashing & Advanced Trees)


Q46. Define hashing. What are the two criteria of a good hash strategy? Discuss open
addressing & chaining methods with examples.

●​ Hashing: Technique to map keys into fixed-size table using a hash function.
●​ Good hash criteria:
1.​ Should distribute keys uniformly.
2.​ Should minimize collisions.

👉 Collision handling:
1.​ Open Addressing: Store colliding item in another open slot (methods → linear probing,
quadratic probing, double hashing).
2.​ Chaining: Each table slot stores a linked list of all colliding keys.

Q47. Define Red-Black Tree, Splay Tree, and B-Tree. Discuss insertion in Red-Black Tree.

●​ Red-Black Tree: Self-balancing BST with rules:


1.​ Every node is red/black.
2.​ Root = black.
3.​ Red node cannot have red child.
4.​ Every path from root to leaf has same black-height.
●​ Splay Tree: Self-adjusting BST → recently accessed elements moved to root by
rotations.
●​ B-Tree: Balanced multi-way search tree used in databases and file systems.

👉 Insertion in RBT: Insert as red, then fix violations using recoloring & rotations.
Q48. Comparison between static hashing & dynamic hashing.

●​ Static Hashing: Fixed table size, collisions handled by chaining/open addressing.


●​ Dynamic Hashing: Table grows/shrinks dynamically (e.g., extendible hashing, linear
hashing).
●​ Advantage: Dynamic hashing avoids overflow & maintains efficiency with growing data.

✅ That covers all Graph + BST + Hashing + Advanced Trees solutions (Module 4 & 5).
Do you want me to compile all module-wise solutions (2–5) into one neat PDF notes for easy
revision?

Perfect👍 this is the next page of DSA Important Questions (VTU 3rd sem).​
I’ll give you clear solutions/short notes for each question shown in the image.

Q46

👉 What is collision? Explain the collision resolution techniques with proper example.
✅ Solution:
●​ Collision: In hashing, a collision occurs when two different keys map to the same hash
table index.
●​ Collision Resolution Techniques:
○​ Open Addressing:
■​ Linear Probing → If index h(k) is occupied, try (h(k)+1) % m.
■​ Quadratic Probing → Try (h(k) + i²) % m.
■​ Double Hashing → Use second hash function.
○​ Chaining: Store multiple elements in the same slot using a linked list.
●​ Example:​
Hash table size = 7, keys = {50, 63, 85}, h(k) = k % 7​
→ h(50)=1, h(63)=0, h(85)=1 (collision at index 1).
○​ With chaining: index 1 → [50 → 85]

Q47

👉 Discuss the time complexity of priority queue operations in various implementations.


✅ Solution:
●​ Priority Queue: Abstract data type where each element has a priority.
●​ Implementations:
○​ Unordered Array: Insert O(1), DeleteMin O(n)
○​ Ordered Array: Insert O(n), DeleteMin O(1)
○​ Unordered Linked List: Insert O(1), DeleteMin O(n)
○​ Ordered Linked List: Insert O(n), DeleteMin O(1)
○​ Binary Heap: Insert O(log n), DeleteMin O(log n), FindMin O(1)

Q48

👉 Explain how leftist trees are used to implement priority queues. Discuss their properties and
advantages.

✅ Solution:
●​ Leftist Tree: A binary tree where the rank (null path length) of left child ≥ right child.
●​ Priority Queue Operations:
○​ Implemented using merge operation.
○​ Insert = merge new node with existing tree.
○​ DeleteMin = remove root and merge its children.
●​ Advantages:
○​ Efficient merging O(log n).
○​ Useful when frequent merging is required (better than heaps in such cases).
Q49

👉 Define priority queues. Differentiate single-ended vs double-ended priority queues.


✅ Solution:
●​ Priority Queue: A queue where each element has a priority and elements are dequeued
based on priority.
●​ Types:
○​ Single-Ended PQ: Only deletion of min (or max) allowed.
○​ Double-Ended PQ (DEPQ): Both min and max deletions allowed.
●​ Example:
○​ Single-ended PQ → Print Spooler (highest priority job prints first).
○​ Double-ended PQ → Deque with priorities (used in scheduling, stock market
ranges).

Q50

👉 Define Optimal Binary Search Tree (OBST). Explain their importance in efficient data
retrieval.

✅ Solution:
●​ OBST: A binary search tree built to minimize the expected search cost, given
probabilities of searching each key.
●​ Why Important?
○​ Regular BST → depends on insertion order, may become skewed.
○​ OBST → ensures minimum average search time using dynamic programming.
●​ Applications:
○​ Compiler symbol table lookup.
○​ Database query optimization.

Q51

👉 Provide examples of real-world applications where OBSTs are used to optimize data retrieval
operations.

✅ Solution:
●​ Applications of OBST:
1.​ Searching reserved keywords in a compiler.
2.​ Efficient dictionary/word lookup.
3.​ Database indexing.
4.​ Caching & memory management.
5.​ AI decision trees (when probabilities are known).

Problems (from image)

1.​ Constructing an OBST → Use dynamic programming with cost matrix.


○​ Formula: cost[i][j] = min ( cost[i][r-1] + cost[r+1][j] +
sum(freq[i..j]) )
2.​ Problems on Hashing → Practice on linear probing, quadratic probing, chaining.

Would you like me to write step-by-step solved examples (like constructing an OBST or
solving a hashing collision table), or just keep it as short notes for quick revision?

You might also like