Data Structures and Algorithms Questions
Data Structures and Algorithms Questions
Here is Set 1 of solved 10-mark questions for Data Structures and Algorithms, with each
answer detailed and at least 200 words:
Data structures are categorized into two main types: linear and non-linear, based on the
way their elements are organized.
In linear data structures, data is organized sequentially or linearly, where each element is
connected to its previous and next element. They follow a straightforward memory allocation
and are easy to implement. Examples include arrays, stacks, queues, and linked lists.
Array is a static linear structure where data elements are stored in contiguous memory
locations.
Stack uses LIFO (Last In First Out) operations, while queue uses FIFO (First In First Out).
In non-linear data structures, elements are not placed in a sequential manner. Instead, they
are connected hierarchically or through complex relationships. Examples include trees and
graphs.
In a tree, elements are arranged in a parent-child hierarchy. A binary tree is a type where
each node has at most two children.
A graph consists of nodes (vertices) and edges and can be used to represent networks.
Key Differences:
1/51
Understanding these types helps in choosing the right data structure for a given problem,
enhancing efficiency and performance.
A stack is a linear data structure that follows the Last In First Out (LIFO) principle. It means
the last element inserted is the first to be removed. Conceptually, it works like a pile of books
where only the top book can be accessed or removed.
Basic Operations:
1. Push – Inserts an element on the top of the stack.
Stacks can be implemented using arrays (static stack) or linked lists (dynamic stack).
Applications of Stack:
Expression Evaluation: Stack is used to evaluate and convert infix expressions to postfix
or prefix.
Function Call Management: The system stack stores function calls and local variables.
Undo Mechanisms: Applications like word processors use stacks to track user actions.
Stacks offer a simple yet powerful way to manage data and control flow, especially when
tracking order of execution or nested operations.
2/51
Q3. Explain binary search with an example. Also, compare it with
linear search.
Answer:
Binary Search is an efficient algorithm for finding an element in a sorted array. It uses a
divide and conquer approach by repeatedly dividing the search space in half.
Steps:
1. Find the middle index of the array.
3. If the target is less than the middle element, repeat the process on the left half.
Example:
Search for 25 in array: [10, 20, 25, 30, 40]
Time Complexity:
Best: O(1)
Average/Worst: O(log n)
Linear Search, on the other hand, checks each element one by one.
Comparison:
Binary search is preferred when dealing with sorted data due to its superior performance.
3/51
Q4. What is a Binary Search Tree (BST)? Explain insertion and deletion
operations in BST.
Answer:
A Binary Search Tree (BST) is a type of binary tree where each node has a key, and:
Keys in the left subtree are less than the node's key.
Keys in the right subtree are greater than the node's key.
This property makes search operations efficient, usually taking O(log n) time in balanced
trees.
Insertion in BST:
1. Start at the root.
2. If the key is less than the current node, move to the left child.
4. Repeat until a NULL spot is found, and insert the new node there.
Example:
Insert 30 into BST:
markdown
20
\
40
Deletion in BST:
Three cases:
3. Two children: Find in-order successor (smallest in right subtree), copy its value, and
delete it recursively.
4/51
BSTs ensure ordered data storage, supporting efficient search, insert, and delete. However,
unbalanced BSTs can degrade to linked lists (O(n) operations), which is why self-balancing
BSTs like AVL or Red-Black Trees are preferred for critical systems.
Here is Set 2 of solved 10-mark questions for Data Structures and Algorithms. Each answer
is detailed and contains at least 200 words to match the academic requirements.
Q1. What is recursion? Explain tail recursion and how recursion can be
removed using a stack.
Answer:
Example:
5/51
int factorial(int n) {
if(n == 0) return 1;
return n * factorial(n - 1);
}
Tail Recursion:
A tail recursive function is one where the recursive call is the last operation before returning
a result.
Example:
Tail recursion can be optimized by compilers into iteration, saving stack space.
This approach is often used in tree traversals, DFS, and expression evaluation. By
managing your own stack, you avoid system-level call stack overflow and gain control over
execution.
6/51
Q2. Differentiate between array and linked list. Explain the array and
pointer representation of linked list in C.
Answer:
Both arrays and linked lists are linear data structures but differ significantly in structure and
memory behavior.
Array:
Stores elements in contiguous memory locations.
Linked List:
Composed of nodes where each node contains data and a pointer to the next node.
struct Node {
int data;
int next; // index of next element
};
7/51
This is often used in memory-constrained or embedded environments.
Pointer Representation in C:
c
struct Node {
int data;
struct Node* next;
};
In conclusion, arrays are ideal for static and random-access-heavy tasks, while linked lists are
preferred for dynamic scenarios involving frequent insertions/deletions.
Q3. What is hashing? Explain collision and any two collision resolution
techniques.
Answer:
Hashing is a technique used to map data (keys) to a fixed-size table (hash table) using a
hash function. It enables fast insertion, deletion, and lookup in O(1) time on average.
Hash Function:
Converts key to an index within table bounds.
Collision:
Occurs when two keys produce the same hash index.
8/51
Example:
For table size 10:
Key 12 → 12 % 10 = 2
Key 22 → 22 % 10 = 2 → collision!
Collisions are unavoidable due to the pigeonhole principle. Therefore, we use collision
resolution techniques.
1. Chaining:
Use linked lists at each index.
Advantages:
Drawback:
Example:
If index 5 is taken, try 6, 7, 8...
Advantages:
Drawbacks:
9/51
In conclusion, hashing is a powerful way to implement associative data structures, and
collision resolution is key to maintaining performance.
An AVL Tree is a self-balancing Binary Search Tree (BST) where the height difference
(balance factor) between the left and right subtree of any node is at most 1.
Balance Factor:
BalanceFactor = height(left subtree) – height(right subtree)
If the balance factor goes outside this range, rotations are performed to restore
balance.
Types of Rotations:
Occurs when a node is inserted into the left subtree of the left child.
markdown
z y
/ /\
y → x z
/
x
Occurs when a node is inserted into the right subtree of the right child.
10/51
markdown
z y
\ /\
y → z x
\
x
Occurs when a node is inserted into the right subtree of the left child.
javascript
z z x
/ / /\
y → x → y z
\ /
x y
Occurs when a node is inserted into the left subtree of the right child.
AVL Trees maintain O(log n) time for search, insert, and delete by rebalancing the tree after
operations. This ensures that the performance never degrades like in unbalanced BSTs.
Here is Set 3 of solved 10-mark questions for Data Structures and Algorithms, with detailed
answers (minimum 200 words each) for thorough understanding.
11/51
✅ Set 3: Solved Questions (10 Marks
Each)
A graph is a non-linear data structure made up of a set of vertices (nodes) and edges
(connections) between them. Graphs are used to represent networks like social networks,
transportation systems, and communication models.
Graph Representations:
1. Adjacency Matrix:
If there’s an edge from vertex i to j, matrix[i][j] = 1 (or the weight of the edge).
Pros:
Cons:
12/51
2. Adjacency List:
Pros:
Cons:
3. Incidence Matrix:
Graphs provide powerful tools for modeling complex relationships. The choice of
representation depends on the size and nature of the graph (dense vs. sparse).
Q2. Explain Breadth First Search (BFS) and Depth First Search (DFS)
traversal of a graph with examples.
Answer:
BFS and DFS are fundamental algorithms used for traversing or searching graph data
structures.
13/51
Explores all vertices at the current depth before moving to the next level.
Steps:
Example:
For graph:
A—B—C
||
D—E
BFS from A: A, B, D, C, E
Use Cases:
Steps:
Use Cases:
14/51
Cycle detection
Topological sort
Connected components
Both BFS and DFS are core techniques in graph theory with widespread applications in AI,
networking, and compilers.
A circular queue is a linear data structure in which the last position is connected back to the
first to make a circle. It overcomes the limitation of the linear queue’s wasted space once rear
reaches the end.
Insertion (Enqueue):
c
Deletion (Dequeue):
c
15/51
if (front == -1)
print("Queue is Empty");
else {
value = queue[front];
if (front == rear)
front = rear = -1;
else
front = (front + 1) % size;
}
Wrap-around behavior: Elements are inserted from the front when there’s space,
reducing wastage.
Circular queues are highly useful in real-time systems where memory is constrained and
cyclic usage is optimal.
Kruskal’s Algorithm is a greedy algorithm used to find a Minimum Spanning Tree (MST) in
a connected, weighted graph. It works by sorting all edges and selecting the smallest edge
that doesn’t form a cycle.
16/51
1. Sort all edges in ascending order of weights.
Example:
Graph:
css
A — B (4)
A — C (2)
B — C (5)
B — D (10)
C — D (3)
Time Complexity:
O(E log E) for sorting
Kruskal’s algorithm is best suited for sparse graphs and is widely used in networking and
design problems.
17/51
✅ Ready for Set 4 of solved questions?
Create Word Docs Create PDF Docs
Here is Set 4 of solved 10-mark questions for Data Structures and Algorithms, with each
answer being at least 200 words long for depth and clarity.
Q1. Explain the working of Merge Sort with an example. Also, write its
time and space complexity.
Answer:
Merge Sort is a classic Divide and Conquer algorithm that divides the input array into
smaller subarrays, sorts them individually, and merges them to produce the final sorted
array. It is particularly efficient for large datasets.
Example:
Given array: [38, 27, 43, 3, 9, 82, 10]
18/51
Divide: [38, 27, 43] and [3, 9, 82, 10]
Recursively divide until single elements: [38] [27] [43] [3] [9] [82] [10]
Merge step-by-step:
Time Complexity:
Best, Average, Worst: O(n log n)
(Each division halves the array ⇒ log n divisions; merging takes O(n) at each level)
Space Complexity:
O(n): Extra space needed for temporary arrays during merge.
Advantages:
Stable sort (preserves order of equal elements)
Use Cases:
Q2. Differentiate between BFS and DFS. Write use cases for both.
Answer:
19/51
Both BFS (Breadth First Search) and DFS (Depth First Search) are graph traversal
algorithms. While they serve the same goal — visiting all nodes in a graph — their behavior,
use cases, and implementations differ significantly.
Example:
In graph: A — B — C — D
BFS starting from A: A → B → C → D
Example:
DFS from A might go: A → B → D → C
Comparison Table:
Feature BFS DFS
20/51
Feature BFS DFS
BFS and DFS are fundamental for solving a wide range of problems in computer science,
from networking to game development.
A sparse matrix is a matrix in which most of the elements are zero. They frequently arise in
applications such as scientific computing, image processing, and machine learning (e.g.,
adjacency matrices of large graphs).
Example:
csharp
[0 0 3]
[0 0 0]
[4 0 0]
21/51
Efficient Representations:
Store only non-zero values along with their row and column indices.
Format:
plaintext
Example:
csharp
[0, 2, 3]
[2, 0, 4]
Three arrays:
Each node holds value, row, column, and pointer to next node.
Benefits:
Saves space
22/51
Allows efficient storage in memory-limited environments
Dijkstra’s Algorithm finds the shortest path from a source vertex to all other vertices in a
weighted graph with non-negative edges. It’s widely used in networking (e.g., routing
protocols), navigation systems, and AI.
Steps:
1. Set all distances to ∞, source distance = 0.
Example:
Graph:
css
A --5--> B
A --2--> C
B --1--> C
C --3--> D
23/51
Start from A:
A: 0
C: 2 (via A)
D: 5 (A→C→D)
A: 0
B: 3
C: 2
D: 5
Time Complexity:
Using simple array: O(V²)
Limitations:
Doesn’t work with negative weights (use Bellman-Ford instead)
Dijkstra’s algorithm is efficient, widely implemented, and essential for optimal routing and
decision-making tasks.
24/51
Create Word Docs Create PDF Docs
Great! Below is Set 5 of solved 10-mark questions for Data Structures and Algorithms. Each
answer is detailed and contains at least 200 words. I will follow up with Sets 6, 7, and 8 after
this one.
Q1. What are Abstract Data Types (ADT)? Explain with examples.
Answer:
An Abstract Data Type (ADT) is a theoretical concept in computer science used to define a
data structure logically rather than physically. It defines the behavior (operations) of the
data type and hides the implementation details from the user.
Characteristics of ADT:
Emphasis is on what operations are performed, not how.
1. Stack ADT:
25/51
2. Queue ADT:
3. List ADT:
4. Graph ADT:
Advantages of ADTs:
Abstraction: Users need not worry about internal structure.
In short, ADTs form the backbone of algorithm design and data structure usage. They allow
programmers to focus on problem-solving without worrying about implementation
complexities.
Q2. Explain the difference between selection sort and bubble sort.
Write their algorithm and time complexity.
Answer:
Selection Sort and Bubble Sort are simple comparison-based sorting algorithms, suitable
for small datasets. Though easy to implement, they are inefficient for large data due to their
O(n²) time complexity.
Selection Sort:
Finds the minimum element in the unsorted part and places it at the beginning.
26/51
Repeats for the remaining array.
Algorithm:
for i = 0 to n-1:
min = i
for j = i+1 to n:
if arr[j] < arr[min]:
min = j
swap(arr[i], arr[min])
Bubble Sort:
Repeatedly swaps adjacent elements if they are in the wrong order.
Algorithm:
for i = 0 to n-1:
for j = 0 to n-i-1:
if arr[j] > arr[j+1]:
swap(arr[j], arr[j+1])
Time Complexity:
Differences:
27/51
Feature Selection Sort Bubble Sort
Stable No Yes
Use Case Fewer writes needed Better for nearly sorted arrays
While both are educational, they are rarely used in production compared to efficient
algorithms like Merge Sort or Quick Sort.
Polynomials can be represented and manipulated using linked lists, which provide dynamic
memory allocation and easy insertion/deletion of terms. Each node of the list represents a
term with a coefficient and exponent.
Node Structure:
c
struct Node {
int coeff;
int exp;
struct Node* next;
};
Polynomial Representation:
For polynomial: 5x^3 + 4x^2 + 2
28/51
Linked list:
css
Polynomial Addition:
Traverse both lists.
Compare exponents:
Polynomial Multiplication:
For each term in the first list:
Insert result into result list using insertOrUpdate() to combine like terms.
Advantages:
Dynamic size — no need to declare array size.
Cleaner representation compared to array (which wastes space for zero coefficients).
Linked lists are ideal for polynomial manipulation in symbolic computations and algebraic
expression handling.
29/51
Q4. Explain the concept of priority queue. How does it differ from a
normal queue? Give applications.
Answer:
A priority queue is an abstract data type in which each element is associated with a priority,
and the element with the highest priority is served before others.
Unlike a normal queue (FIFO), the priority queue does not necessarily process elements in
the order they arrive.
Types:
Ascending Priority Queue: Lower numbers have higher priority.
Implementations:
1. Array/Linked List (unsorted or sorted)
Operations:
insert(element, priority)
extractMin() or extractMax()
30/51
Feature Queue Priority Queue
Applications:
CPU scheduling (highest priority job runs first)
Priority queues offer more control in situations where urgency or importance determines
processing order.
Here is Set 6 of solved 10-mark questions for Data Structures and Algorithms, with each
answer being 200+ words and written for conceptual clarity.
31/51
Q1. What is a threaded binary tree? Explain its types and advantages.
Answer:
A Threaded Binary Tree is a variant of the binary tree where NULL pointers in left or right
child references are replaced with pointers (threads) to the in-order predecessor or
successor, improving the traversal efficiency without using stacks or recursion.
In a normal binary tree, approximately half of the child pointers are NULL . These unused
pointers can be used to link nodes in a specific traversal order.
Can be:
2. Double Threaded:
Both left and right NULL pointers are replaced with threads.
Advantages:
Faster traversal (especially in-order) without stacks or recursion.
32/51
Node* current = leftmost(root);
while (current) {
print(current->data);
if (current->rthread)
current = current->right;
else
current = leftmost(current->right);
}
Threaded binary trees are useful in scenarios where memory efficiency and fast traversal are
required, such as expression trees and symbolic computations.
Q2. Explain Quick Sort algorithm with an example. Mention its time
and space complexity.
Answer:
Quick Sort is a highly efficient divide and conquer algorithm used for sorting. It is widely
used because of its superior performance in the average case and its in-place sorting
property (i.e., it requires no extra space like Merge Sort).
Algorithm:
1. Choose a pivot element.
Example:
Array: [29, 10, 14, 37, 13]
33/51
Pivot = 29
Time Complexity:
Best & Average: O(n log n)
Worst: O(n²) (when array is already sorted and worst pivot is chosen)
Advantages:
Very fast for large datasets
Despite the worst-case complexity, quick sort is one of the fastest sorting techniques in
practice when implemented with optimizations like random or median-of-three pivot
selection.
34/51
Conventional Matrix Multiplication:
Time Complexity: O(n³)
Each element of the result matrix is computed by taking dot product of rows and
columns.
Strassen’s Approach:
Reduces the number of multiplications using mathematical rearrangement.
P2 = (A21 + A22)B11
...
Time Complexity:
T(n) = 7T(n/2) + O(n²)
Advantages:
Faster than standard O(n³) for large matrices.
35/51
Limitations:
Overhead for small matrices.
Example:
Let X = “AGGTAB” and Y = “GXTXAYB”
m = length of X
n = length of Y
Recurrence Relation:
if (X[i] == Y[j])
dp[i][j] = 1 + dp[i-1][j-1];
36/51
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
Algorithm:
for i = 0 to m:
for j = 0 to n:
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (X[i-1] == Y[j-1])
dp[i][j] = 1 + dp[i-1][j-1];
else
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
Space: O(m × n)
Applications:
Diff tools (e.g., Git)
Spell checkers
LCS is a key problem for understanding dynamic programming, and its efficient solution has
real-world applications in bioinformatics and version control.
37/51
Here is Set 7 of solved 10-mark questions for Data Structures and Algorithms, each with a
detailed explanation of at least 200 words.
A B-Tree is a self-balancing multi-way search tree used primarily in databases and file
systems. Unlike binary trees, where each node has at most two children, B-Trees allow nodes
to have multiple keys and children, making them ideal for systems that read/write large
blocks of data.
3. Each internal node can contain at most m–1 keys and m children.
Insertion Process:
1. Insert the key in the correct leaf node.
38/51
Middle key moves up to parent.
4. If the parent is full, repeat the splitting process recursively up to the root.
Example:
Inserting keys 10, 20, 5, 6, 12, 30 into a B-Tree of order 3 results in balanced nodes where
each node can hold 2 keys max, and splits occur as needed.
Use Cases:
File systems (e.g., NTFS, HFS+)
B-Trees minimize disk I/O operations and are optimized for systems with large data sets and
block storage.
Both Prim’s and Kruskal’s algorithms are used to find the Minimum Spanning Tree (MST) of
a connected, weighted, undirected graph, but they differ in approach.
Prim’s Algorithm:
Start from a vertex.
Grow the MST by adding the cheapest edge from the tree to a non-tree vertex.
39/51
Uses priority queue (min-heap) for efficient edge selection.
Time Complexity:
Kruskal’s Algorithm:
Sort all edges by weight.
Pick the smallest edge and add it to MST if it doesn’t form a cycle.
Time Complexity:
Comparison Table:
Feature Prim’s Algorithm Kruskal’s Algorithm
Use Cases:
Prim’s: Network design (like LAN cables)
40/51
Both algorithms are foundational in graph theory and real-world network optimization
problems.
Q3. Write the algorithm for binary search. Compare it with linear
search in terms of time complexity.
Answer:
Linear Search:
Scans each element sequentially until the key is found.
41/51
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++)
if (arr[i] == key)
return i;
return -1;
}
Comparison Table:
Feature Binary Search Linear Search
Binary Search is significantly faster than Linear Search for large sorted datasets, but it
cannot be used on unsorted arrays.
Q4. What are asymptotic notations? Explain Big O, Omega, and Theta
with examples.
Answer:
Asymptotic Notations are mathematical tools used to describe the time or space
complexity of an algorithm in terms of input size n , as n grows large. They provide upper,
lower, and tight bounds for performance estimation.
42/51
Describes the worst-case scenario.
Example:
For f(n) = 3n² + 2n + 1 ,
O(f(n)) = O(n²)
Used to guarantee that an algorithm will not take longer than a certain time.
Example:
In Linear Search,
Ω(1) when the key is at the first position.
Used to state that the algorithm will take at least a certain amount of time.
Example:
For f(n) = 5n + 3 ,
Θ(n) as both upper and lower bounds are linear.
Comparison Table:
Notation Represents Scenario
43/51
Asymptotic notations are essential for analyzing algorithm efficiency, comparing solutions,
and understanding performance scalability.
✅ Shall I continue with Set 8 (final set) of your requested solved questions?
Create Word Docs Create PDF Docs
Here is Set 8 – the final set of solved 10-mark questions for Data Structures and Algorithms,
with detailed answers (each 200+ words).
A hash table is a data structure that provides fast O(1) average time complexity for
insertion, deletion, and search operations. It uses a hash function to map keys to specific
indices (buckets) in an array.
Hash Function:
It computes an index from the key.
Example:
44/51
But multiple keys may produce the same index — this is known as a collision.
Collision:
Occurs when two or more keys map to the same index.
1. Open Addressing:
All elements are stored in the table. If a collision occurs, find the next available slot using
probing.
Linear Probing:
index = (hash + i) % table_size
Quadratic Probing:
index = (hash + i²) % table_size
Double Hashing:
index = (hash1 + i * hash2) % table_size
Each table index holds a linked list of elements. If multiple keys hash to the same index, they
are stored in the list.
Advantages:
Fast average-case performance
45/51
Applications:
Symbol tables in compilers
Caching
Hash tables are the backbone of many high-performance applications and are widely used in
both software and system-level design.
An AVL Tree is a self-balancing Binary Search Tree (BST) where the difference in heights of
left and right subtrees (balance factor) of any node is at most 1.
Balance Factor:
c
Why AVL?
Normal BST can become skewed → time complexity degrades to O(n)
46/51
1. Left-Left (LL) Rotation:
Occurs when a node is inserted into the left subtree of the left child.
plaintext
z
/
y
/
x
plaintext
z
\
y
\
x
Node inserted into the right subtree of left child. First left rotate, then right rotate.
Node inserted into left subtree of right child. First right rotate, then left rotate.
47/51
Applications:
Databases and search engines
AVL Trees guarantee logarithmic height, making search, insert, and delete operations
efficient and predictable.
Recursion is a programming technique where a function calls itself to solve smaller sub-
problems of a larger problem. It is based on the divide and conquer strategy.
Basic Structure:
c
void recursiveFunc() {
if (base_condition)
return;
else
recursiveFunc(); // recursive call
}
Example – Factorial:
c
int factorial(int n) {
if (n <= 1)
return 1;
else
48/51
return n * factorial(n - 1);
}
Iteration vs Recursion:
Feature Recursion Iteration
Tree traversal
Tower of Hanoi
Fibonacci series
Drawbacks:
More memory (stack frames)
Understanding recursion is critical for writing elegant and effective solutions in algorithm
design.
49/51
Q4. Explain the working of the Bellman-Ford algorithm with an
example. How is it different from Dijkstra’s?
Answer:
Bellman-Ford is a graph algorithm used to find shortest paths from a single source vertex
to all other vertices in a weighted graph, including graphs with negative edge weights.
Algorithm Steps:
1. Initialize distance of all vertices as ∞; source = 0.
2. Repeat (V – 1) times:
Example:
Graph edges:
css
Iteratively update:
A→B=4
A→C=5
B → C = 1 (4 – 3)
C→D=3
B = 4, C = 1, D = 3
50/51
Time Complexity: O(V × E)
Bellman-Ford is suitable when the graph has negative weights, and Dijkstra’s is faster for
non-negative weighted graphs.
✅ This concludes all 8 sets of 10-mark questions (32 questions in total). Let me know if you'd
like:
51/51