Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views49 pages

DSA QB-Answers

The document provides a comprehensive overview of data structures, algorithms, and their complexities, including definitions, types, and examples of sorting and searching algorithms like binary search, bubble sort, and insertion sort. It emphasizes the importance of writing answers in an original way during exams and includes detailed steps for various algorithms along with their time and space complexities. Additionally, it discusses the differences between linear and nonlinear data structures and the evaluation of algorithm efficiency.

Uploaded by

kishwaryarani
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)
24 views49 pages

DSA QB-Answers

The document provides a comprehensive overview of data structures, algorithms, and their complexities, including definitions, types, and examples of sorting and searching algorithms like binary search, bubble sort, and insertion sort. It emphasizes the importance of writing answers in an original way during exams and includes detailed steps for various algorithms along with their time and space complexities. Additionally, it discusses the differences between linear and nonlinear data structures and the evaluation of algorithm efficiency.

Uploaded by

kishwaryarani
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/ 49

Note:- Don’t write Answers in the EXAM from this

blindly, just learn it and write “ I am not responsible if I


suppose wrong”, the content is correct but you have to
write in the exam in a different way not for all question
but for sorting, searching, like a linked list, stack, queue
you have to represent with required diagrams like a
linked list, array, stack(refer from unit-3, 4Q)

Page No. 1
UNIT -1
1 Marks
1. Define data structure.
Ans:- "A data structure is a way to organize and store data in a computer so
that it can be efficiently accessed, modified, and manipulated."

2. What is worst-case analysis?


Ans:- Worst-case analysis: Finding the maximum time an algorithm takes to
complete, even with the most difficult input.

3. Define Time complexity


Ans:- Time complexity: The measure of how long an algorithm takes to
complete, usually expressed as a function of the size of the input (typically
denoted as 'n')

4. List the types of data structures.


Ans:- The types of data structures are:
1. Arrays
2. Linked Lists
3. Stacks
4. Queues

Page No. 2
5. Trees
6. Graphs

5. Differentiate linear and nonlinear data structures.


Ans:- "Linear data structures (e.g. Arrays, Linked Lists, Stacks, Queues)
have elements arranged in a sequential order, whereas Nonlinear data
structures (e.g. Trees, Graphs) have elements arranged in a hierarchical or
network-like structure."

6. How will you evaluate efficiency of an algorithm


Ans:- Efficiency of an algorithm is evaluated using Time Complexity (how
long it takes to complete) and Space Complexity (how much memory it
uses), typically measured in terms of the size of the input (n).

7. Discuss the Importance of Algorithm


Ans:- Algorithms are important because they provide a step-by-step
solution to a problem, ensuring efficiency, accuracy, and scalability, and are
essential for solving complex problems in various fields, such as computer
science, engineering, and data analysis.

8. State the insertion sort worst-case time complexity.


Ans:- The worst-case time complexity of Insertion Sort is O(n2).
9. Define Abstract data type.
Ans:- An Abstract Data Type (ADT) is a high-level description of a data type
that defines its behavior and operations without specifying its
implementation details.

10. Define space complexity.


Ans:- Space complexity: The amount of memory an algorithm uses,
typically measured in terms of the input size (n), to solve a problem.

Long Answers
1. Illustrate binary search with example

Page No. 3
Ans:- Binary search is a highly efficient algorithm for finding an element in a
sorted array. It works by repeatedly dividing the search interval in half and
comparing the target value to the middle element of the array. Here's a detailed
illustration of how binary search works with an example.

Algorithm:

1. Initialize low to 0 and high to n - 1 where n is the length of the


array.
2. Repeat until low is greater than high:
o Calculate mid = (low + high) / 2.
o If array[mid] equals the target value, return mid.
o If array[mid] is less than the target value, set low = mid +
1.
o If array[mid] is greater than the target value, set high =
mid - 1.
3. If the target value is not found, return an indication (like -1) that the
target is not in the array.

Example:

Suppose we have a sorted array and we want to find the position of element 23
in the following array:

2,5,8,12,16,23,38,45,56,72

Steps of Binary Search:

1. Initialization:
o Set two pointers: low at the beginning (index 0) and high at the
end (index 9) of the array.
o Calculate the middle index: mid = (low + high) / 2. For
integer division, mid = (0 + 9) / 2 = 4.
2. First Comparison:
o Compare the middle element array[4] = 16 with the target
value 23.
o Since 23 is greater than 16, narrow the search to the right half of
the array. Update low to mid + 1 = 5.
3. Second Comparison:
o Calculate the new middle index: mid = (5 + 9) / 2 = 7.
o Compare the middle element array[7] = 45 with 23.

Page No. 4
oSince 23 is less than 45, narrow the search to the left half of the
current subarray. Update high to mid - 1 = 6.
4. Third Comparison:
o Calculate the new middle index: mid = (5 + 6) / 2 = 5.
o Compare the middle element array[5] = 23 with 23.
o Since 23 equals 23, we have found the target value at index 5.

Time Complexity:

The time complexity of binary search is O(logn), where n is the number of


elements in the array. This efficiency is due to the halving of the search interval
with each iteration.

Advantages:

 Binary search is much faster than linear search for large datasets.
 It is straightforward to implement.

Disadvantages:

 Binary search requires the array to be sorted. If the array is not sorted, it
must be sorted first, which takes O(nlogn) time.

2. Explain the Bubble sort algorithm with an example

Ans:- Bubble sort is a simple sorting algorithm that repeatedly steps


through the list, compares adjacent elements, and swaps them if they are in
the wrong order. The process is repeated until the list is sorted. Here is a
detailed explanation of the Bubble Sort algorithm with an example.

Steps of the Bubble Sort Algorithm:

1. Starting from the first element, compare the current element with the next
element.
2. If the current element is greater than the next element, swap them.
3. Move to the next element and repeat the process for the rest of the list.
4. Repeat steps 1-3 for the entire list until no swaps are needed, which
means the list is sorted.

Example:

Let's sort the following array using Bubble Sort:

Page No. 5
5,1,4,2,8

Pass-by-Pass Explanation:

Initial Array:

5,1,4,2,8

First Pass:

 Compare 5 and 1. Since 5 > 1, swap them: 1,5,4,2,8


 Compare 5 and 4. Since 5 > 4, swap them: 1,4,5,2,8
 Compare 5 and 2. Since 5 > 2, swap them: 1,4,2,5,8
 Compare 5 and 8. Since 5 < 8, no swap is needed.

Array after the first pass: 1,4,2,5,8

Second Pass:

 Compare 1 and 4. Since 1 < 4, no swap is needed.


 Compare 4 and 2. Since 4 > 2, swap them: 1,2,4,5,8
 Compare 4 and 5. Since 4 < 5, no swap is needed.
 Compare 5 and 8. Since 5 < 8, no swap is needed.

Array after the second pass: 1,2,4,5,8

Third Pass:

 Compare 1 and 2. Since 1 < 2, no swap is needed.


 Compare 2 and 4. Since 2 < 4, no swap is needed.
 Compare 4 and 5. Since 4 < 5, no swap is needed.
 Compare 5 and 8. Since 5 < 8, no swap is needed.

Array after the third pass: 1,2,4,5,8

Since no swaps were made in the third pass, the algorithm stops, and the array is
sorted.

The final sorted list is: 1,2,4,5,8

Page No. 6
3. Explain Linear search with an example
Ans:-
It works by sequentially checking each element of a list until the
target value is found or the list ends. Here’s a detailed explanation of the linear
search algorithm with an example.

Steps of the Linear Search Algorithm:

1. Start from the first element of the array.


2. Compare the current element with the target value.
3. If the current element is equal to the target value, return the index of the
current element.
4. If the current element is not equal to the target value, move to the next
element and repeat step 2.
5. If the target value is not found after checking all elements, return an
indication that the target is not in the array (usually -1).

Example:

Suppose we have the following array and we want to find the index of element
7:

3,5,2,9,7,8

Step-by-Step Explanation:

1. Start with the first element:


o Compare 3 with 7.
o They are not equal, so move to the next element.
2. Second element:
o Compare 5 with 7.
o They are not equal, so move to the next element.
3. Third element:
o Compare 2 with 7.
o They are not equal, so move to the next element.
4. Fourth element:
o Compare 9 with 7.
o They are not equal, so move to the next element.
5. Fifth element:
o Compare 7 with 7.

Page No. 7
o They are equal, so return the index of this element, which is 4.

The target value 7 is found at index 4.

Time Complexity:

 Worst-case and Average-case: O(n), where n is the number of elements


in the array.
 Best-case: O(1) when the target value is the first element in the array.

Space Complexity:

 O(1), as Linear Search is an in-place algorithm that does not require


additional memory.

Advantages:

 Simple to understand and implement.


 Does not require the array to be sorted.
 Works well for small arrays or arrays where the target value is likely to
be near the beginning.

Disadvantages:

 Inefficient for large arrays, as the time complexity is O(n).


 More advanced searching algorithms like Binary Search (for sorted
arrays) or hashing techniques are generally preferred for larger datasets or
performance-critical applications.

4. Sort the following values using Selection Sort: 65, 70,75,80,


85, 60,55,50,45 Illustrate each step of the sorting process
Ans:- Selection Sort is a simple and intuitive sorting algorithm. It works
by repeatedly finding the minimum element from the unsorted part of the
list and swapping it with the first unsorted element. Here’s a step-by-step
illustration of how Selection Sort works with the given list of values:

Initial List:

65,70,75,80,85,60,55,50,45

Step-by-Step Sorting Process:

Page No. 8
Step 1: First Pass (Finding the minimum and swapping)

 Initial unsorted list: 65,70,75,80,85,60,55,50,45


 Find the minimum value in the unsorted list (45).
 Swap 45 with the first element (65).
 List after first pass: 45,70,75,80,85,60,55,50,65

Step 2: Second Pass

 Unsorted list: 70,75,80,85,60,55,50,65


 Find the minimum value in the unsorted list (50).
 Swap 50 with the first unsorted element (70).
 List after second pass: 45,50,75,80,85,60,55,70,65

Step 3: Third Pass

 Unsorted list: 75,80,85,60,55,70,65


 Find the minimum value in the unsorted list (55).
 Swap 55 with the first unsorted element (75).
 List after third pass: 45,50,55,80,85,60,75,70,65

Step 4: Fourth Pass

 Unsorted list: 80,85,60,75,70,65


 Find the minimum value in the unsorted list (60).
 Swap 60 with the first unsorted element (80).
 List after fourth pass: 45,50,55,60,85,80,75,70,65

Step 5: Fifth Pass

 Unsorted list: 85,80,75,70,65


 Find the minimum value in the unsorted list (65).
 Swap 65 with the first unsorted element (85).
 List after fifth pass: 45,50,55,60,65,80,75,70,85

Step 6: Sixth Pass

 Unsorted list: 80,75,70,85


 Find the minimum value in the unsorted list (70).
 Swap 70 with the first unsorted element (80).
 List after sixth pass: 45,50,55,60,65,70,75,80,85

Page No. 9
Step 7: Seventh Pass

 Unsorted list: 75,80,85


 Find the minimum value in the unsorted list (75).
 Swap 75 with the first unsorted element (75).
 List after seventh pass: 45,50,55,60,65,70,75,80,85

Step 8: Eighth Pass

 Unsorted list: 80,85


 Find the minimum value in the unsorted list (80).
 Swap 80 with the first unsorted element (80).
 List after eighth pass: 45,50,55,60,65,70,75,80,85

Step 9: Ninth Pass

 Unsorted list: 85
 The last element is already in place.

Sorted List:

45,50,55,60,65,70,75,80,85

5. Sort the sequences 3,10,4,2,8,6,5, 1 using insertion sort. Show


the content of the array after every iteration of the sort.

Ans:- Insertion sort is a simple and efficient comparison-based sorting


algorithm. It builds the final sorted array one item at a time. It is much less
efficient on large lists than more advanced algorithms such as quicksort,
heapsort, or merge sort. However, it has the advantage of being simple and
efficient for small data sets or mostly sorted data.

Here's a step-by-step explanation of how Insertion Sort works with the given list
of values:

Initial List:

3,10,4,2,8,6,5,1

Step-by-Step Sorting Process:

Page No. 10
Step 1: First Iteration

 The first element (3) is considered sorted.


 Array: 3,10,4,2,8,6,5,1

Step 2: Second Iteration

 Insert 10 into the sorted sublist.


 Since 10 > 3, it stays in place.
 Array: 3,10,4,2,8,6,5,1

Step 3: Third Iteration

 Insert 4 into the sorted sublist.


 4 < 10, so shift 10 to the right.
 4 > 3, so place 4 after 3.
 Array: 3,4,10,2,8,6,5,1

Step 4: Fourth Iteration

 Insert 2 into the sorted sublist.


 2 < 10, shift 10 to the right.
 2 < 4, shift 4 to the right.
 2 < 3, shift 3 to the right.
 Place 2 at the beginning.
 Array: 2,3,4,10,8,6,5,1

Step 5: Fifth Iteration

 Insert 8 into the sorted sublist.


 8 < 10, shift 10 to the right.
 8 > 4, place 8 after 4.
 Array: 2,3,4,8,10,6,5,1

Step 6: Sixth Iteration

 Insert 6 into the sorted sublist.


 6 < 10, shift 10 to the right.
 6 < 8, shift 8 to the right.
 6 > 4, place 6 after 4.
 Array: 2,3,4,6,8,10,5,1

Page No. 11
Step 7: Seventh Iteration

 Insert 5 into the sorted sublist.


 5 < 10, shift 10 to the right.
 5 < 8, shift 8 to the right.
 5 < 6, shift 6 to the right.
 5 > 4, place 5 after 4.
 Array: 2,3,4,5,6,8,10,1

Step 8: Eighth Iteration

 Insert 1 into the sorted sublist.


 1 < 10, shift 10 to the right.
 1 < 8, shift 8 to the right.
 1 < 6, shift 6 to the right.
 1 < 5, shift 5 to the right.
 1 < 4, shift 4 to the right.
 1 < 3, shift 3 to the right.
 1 < 2, shift 2 to the right.
 Place 1 at the beginning.
 Array: 1,2,3,4,5,6,8,10

Sorted List:

1,2,3,4,5,6,8,10

UNIT-2
1 Marks
1. Give the algorithm for the creation of node struct for a
single Linked list

Ans:- Algorithm:

1. Define a structure named Node.

Page No. 12
2. Include two members in the structure:
o An integer data to store the value of the node.
o A pointer next of type struct Node* to point to the next node
in the list

2. Define HEAD pointer and NULL pointer.

Ans:- - HEAD pointer: A pointer that points to the first node of a linked
list.

- NULL pointer: A special pointer that does not point to any valid memory
location, indicating the end of the linked list.

3. Give the syntax of malloc() and use it to create a node in a


Single Linked List.

Ans:- Syntax of malloc():


malloc(size_t size);

Example of using malloc() to create a node in a Single Linked List:

struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

This allocates memory for a new Node structure and returns a pointer to it,
which is then assigned to the newNode variable.

4. Data are pushed to stack and pop from stack in the following order
push(10), Push(20), Pop(), Push(10), Push(20), Pop(), Pop(),Pop(),
Push(20) pop() Show what are element will be in the stack at end of
all operation.

Ans:-

1. Push(10): Stack = [10]

2. Push(20): Stack = [10, 20]

3. Pop(): Stack = [10] (removed 20)

4. Push(10): Stack = [10, 10]

Page No. 13
5. Push(20): Stack = [10, 10, 20]

6. Pop(): Stack = [10, 10] (removed 20)

7. Pop(): Stack = [10] (removed 10)

8. Pop(): Stack = [] (removed 10, stack is now empty)

9. Push(20): Stack = [20]

10. Pop(): Stack = [] (removed 20, stack is now empty again)

So, at the end of all operations, the stack is empty: []

5. Write the algorithm for Stack full and Stack Empty


operation

Ans:- Algorithm for Stack Full:


1. Check if the top of the stack is equal to the maximum size minus one.

2. If true, return "Stack is Full".

3. Otherwise, proceed with pushing the element onto the stack.

Algorithm for Stack Empty:

1. Check if the top of the stack is equal to minus one.

2. If true, return "Stack is Empty".

3. Otherwise, proceed with popping the element from the stack.

6. Write the algorithm for PUSH operation

Ans:- Algorithm for PUSH:

1. Check if the stack is full.

2. If the stack is full, return "Stack is Full" and stop.

3. Increment the top index by 1.

4. Assign the new element to the top index of the stack.

Page No. 14
5. Return "Element pushed successfully".

7. List out three applications of Linked List

Ans:- Here are three applications of Linked Lists in one line each:
1. Dynamic memory allocation in systems like malloc() and free().

2. Database query optimization for efficient storage and management.

3. Browser history management for forward and backward navigation.

8. What are the advantages of using Linked List over an


Array?

Ans:- Linked Lists offer efficient insertion and deletion of elements at any
position, and dynamic memory allocation, making them more flexible and
memory-efficient than Arrays.

9. Define Circular list

Ans:- A Circular Linked List is a type of linked list where the last node
points back to the first node, forming a circular structure, and there is no
distinct beginning or end.

10. Write the output for stack using linked list :Push (10)
,Push (20) ,Push (30) ,display(),Peek() , Pop() , Peek() , Pop()
, Peek ()
Ans:-

i) Push(10):

Stack: 10

ii) Push(20):

Stack: 10, 20

iii) Push(30):

Stack: 10, 20, 30

iv) Display():

Page No. 15
10, 20, 30

v) Peek():

30

vi) Pop():

Stack: 10, 20

Returned: 30

vii) Peek():

20

viii) Pop():

Stack: 10

Returned: 20

ix) Peek():

10

LONG Answer

1. Write an algorithm for the insertion and deletion of an


element in single linked list. Difference between double and
circular linked list.
Ans:- Insertion Algorithm

1. Insert at the Beginning:


o Create a new node.
o Set the new node's next pointer to the current head.
o Update the head to point to the new node.
2. Insert at the End:
o Create a new node.
o If the list is empty, set the head to the new node.
o Otherwise, traverse to the last node.
o Set the last node's next pointer to the new node.
3. Insert After a Given Node:

Page No. 16
o Create a new node.
o Set the new node's next pointer to the next pointer of the given
node.
o Set the given node's next pointer to the new node.

Deletion Algorithm

a) Delete by Key:
o Start from the head node.
o If the head node itself holds the key, update the head to the next
node.
o Traverse the list to find the node before the node to be deleted.
o Update the next pointer of the previous node to skip the node to
be deleted.
b) Delete at a Given Position:
o If the position is 0, update the head to the next node.
o Traverse the list to find the node before the node to be deleted.
o Update the next pointer of the previous node to skip the node to
be deleted.

Difference Between Double and Circular Linked List

Double Linked List:

1. Structure: Each node contains a data field, a pointer to the next node,
and a pointer to the previous node.
2. Traversal: Can traverse in both forward and backward directions.
3. Memory: Requires more memory per node due to the extra previous
pointer.
4. Use Case: Suitable for applications requiring bidirectional traversal, like
undo-redo functionality in applications.

Circular Linked List:

1. Structure: Similar to a single linked list, but the last node points back to
the first node, forming a circle.
2. Traversal: Can traverse starting from any node and eventually return to
the same node, forming a loop.
3. Memory: Uses the same amount of memory as a single linked list.
4. Use Case: Useful for applications requiring circular traversal, like round-
robin scheduling and buffering applications.

Page No. 17
2. Write routines to pop and push onto a stack using array implementation

Ans:- A stack is a data structure that follows the Last In, First Out (LIFO)
principle. Using an array to implement a stack involves managing an array
and a top pointer that indicates the position of the top element of the stack.

Push Routine:

1. Check if the stack is full (top == MAX_SIZE - 1).

2. If full, return an error message or handle the overflow condition.

3. Increment the top index (top = top + 1).

4. Assign the new element to the top index of the array (arr[top] = element).

5. Return success.

Pop Routine:

1. Check if the stack is empty (top == -1).

2. If empty, return an error message or handle the underflow condition.

3. Store the top element in a temporary variable (element = arr[top]).

4. Decrement the top index (top = top - 1).

5. Return the popped element.

Here's implementation:

#define MAX_SIZE 10

int arr[MAX_SIZE];

int top = -1;

void push(int element) {

if (top == MAX_SIZE - 1) {

Page No. 18
printf("Stack is full\n");

return;

arr[++top] = element;

int pop() {

if (top == -1) {

printf("Stack is empty\n");

return -1;

return arr[top--];

These routines can be used to push and pop elements onto/from the stack
using an array implementation.

3. Write the difference between Array and Linked Lists


Ans:-

Arrays:

- Fixed size, determined at creation

- Elements are stored in contiguous memory locations

- Each element is accessed using an index (position)

- Fast access and search (O(1) time complexity)

- Slow insertion and deletion (O(n) time complexity)

- Memory is allocated statically.

Page No. 19
- Arrays are suitable for situations where data is fixed, and fast access is
crucial.

Linked Lists:

- Dynamic size, can grow or shrink as needed

- Elements are stored in nodes, each containing data and a reference (link)
to the next node

- Each element is accessed by traversing the list from the beginning

- Slow access and search (O(n) time complexity)

- Fast insertion and deletion (O(1) time complexity)

- Memory is allocated dynamically.

- Linked lists are suitable for situations where data is dynamic, and frequent
insertions/deletions are expected.

4) Develop the algorithms for (i) Insertion of a node at the beginning of


the Doubly Linked List. (ii) Deletion of a node in the end of Doubly Linked
List.

Ans:- Here are the algorithms:

(i) Insertion of a node at the beginning of the Doubly Linked List:

1. Create a new node (newNode) with the given data.

2. If the list is empty (head = NULL), set newNode as the head and tail.

3. Otherwise:

- Set newNode's next pointer to the current head (newNode->next = head).

- Set the current head's previous pointer to newNode (head->prev = newNode).

- Set newNode as the new head (head = newNode).

4. Return the updated list.

(ii) Deletion of a node at the end of the Doubly Linked List:

Page No. 20
1. If the list is empty (head = NULL), return an error.

2. Otherwise:

- Set a temporary pointer (temp) to the current tail (temp = tail).

- Set the tail's previous node as the new tail (tail = tail->prev).

- Set the new tail's next pointer to NULL (tail->next = NULL).

- Delete the node pointed to by temp (delete temp).

3. Return the updated list.

Note: In both algorithms, it's important to update the previous and next pointers of the
adjacent nodes to maintain the integrity of the doubly linked list

5) What is Stack? Develop the algorithms for implementing Stack (both


Push and Pop operations) using Linked List.

Ans:- A stack is a data structure that follows the Last-In-First-Out (LIFO) principle,
meaning the last element added to the stack is the first one to be removed. A stack can
be implemented using a linked list, where each node represents an element in the stack.

Push Operation (Adding an element to the stack):

1. Create a new node (newNode) with the given data.

2. Set newNode's next pointer to the current head (newNode->next = head).

3. Set the head to newNode (head = newNode).

4. Increment the stack size (size++).

5. Return the updated stack.

Pop Operation (Removing an element from the stack):

1. If the stack is empty (head = NULL), return an error.

2. Set a temporary pointer (temp) to the current head (temp = head).

3. Set the head to the next node in the list (head = head->next).

4. Delete the node pointed to by temp (delete temp).

5. Decrement the stack size (size--).

Page No. 21
6. Return the removed element.

UNIT -3
1 Marks
1) List the Queue operations.
Ans:- Here are the basic Queue operations:

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


2. Dequeue: Remove an element from the front of the queue.
3. Peek (or Front): Look at the element at the front of the queue without
removing it.
4. IsEmpty: Check if the queue is empty.
5. Size: Get the number of elements in the queue.
2) List the applications of stack.
Ans:- Stacks are useful when you need to process data in a Last-In-First-
Out (LIFO) order.
Here are some applications of stacks:
1. Evaluation of Postfix expressions
2. Implementing recursive algorithms
3. Managing memory (runtime stack)
4. Undo/Redo functionality
3) What is backtracking? List out the various applications.
Ans:- Backtracking is an algorithmic technique used to find a solution by
recursively exploring all possible solutions, and backtracking when a
dead end is reached.
Applications of Backtracking:
1. Sudoku
2. Traveling Salesman Problem

Page No. 22
3. Scheduling
4. Resource Allocation
5. Cryptography
4) What is input restricted deque?
Ans:-An input-restricted deque is a deque (double-ended queue) that
only allows insertions at one end, but allows deletions at both ends.
5) What causes the underflow of stack? How could it be avoided?

Ans:- Underflow of a stack occurs when:


- Trying to pop or delete an element from an empty stack.
- Trying to access or peek at an element from an empty stack.
To avoid underflow:
- Always check if the stack is empty before popping or accessing
elements.
- Ensure that elements are pushed onto the stack before popping.
- Use a try-catch block to handle underflow exceptions.
By following these practices, you can prevent stack underflow and
ensure safe and efficient stack operations.

LONG Answer
1) Discuss the Queue implementation using arrays
Ans:- A queue is a data structure that follows the First-In-First-Out (FIFO)
principle, meaning that the first element added to the queue is the first one
to be removed. A queue can be thought of as a line of people waiting for
something, where the person who arrives first is served first.
Queue implementation using arrays:
Array-based Queue

Page No. 23
- A queue can be implemented using a fixed-size array.
- The array size is fixed, and the queue can become full if the array is
completely utilized.
- Two indices, front, and rear, are used to keep track of the queue's state.
Operations:
1. Enqueue (add element):
- Check if the queue is full (rear == size - 1).
- If full, return the error or resize the array.
- Otherwise, add the element at the rear index and increment the rear.
2. Dequeue (remove element):
- Check if the queue is empty (front == rear).
- If empty, return error.
- Otherwise, remove the element at the front index and increment front.
3. Front (get front element):
- Return the element at the front index.
4. Rear (get rear element):
- Return the element at the rear index.
5. IsEmpty:
- Check if front == rear.
6. IsFull:
- Check if rear == size - 1.

Array Queue Example:


Suppose we have a queue with a size of 5:
int queue[5];
int front = 0;
int rear = 0;

Page No. 24
Enqueue operations:
1. Enqueue 5: queue[0] = 5; rear = 1;
2. Enqueue 8: queue[1] = 8; rear = 2;
3. Enqueue 2: queue[2] = 2; rear = 3;
Dequeue operations:
1. Dequeue: element = queue[0]; front = 1;
- The element 5 is removed, and the front index is incremented.
Array Queue Advantages:
- Efficient use of memory (fixed size).
- Fast enqueue and dequeue operations (O(1)).
Array Queue Disadvantages:
- Fixed-size limits the queue capacity.
- Resizing the array can be costly.
Overall, array-based queues are suitable for situations where the maximum
queue size is known and memory efficiency is important. However, they
may not be ideal for scenarios where the queue size needs to dynamically
grow or shrink.
2) Explain the algorithm for evaluating postfix expressions using a stack
for the below expression. 2 5 3 6 + * * 5 / 2 –
Ans:- The algorithm for evaluating postfix expressions using a stack is as
follows:
1. Create an empty stack.
2. Scan the expression from left to right.
3. For each token (operand or operator):
- If the token is an operand, push it onto the stack.
- If the token is an operator, pop the required number of operands from
the stack, perform the operation, and push the result back onto the stack.

Page No. 25
4. When the end of the expression is reached, the final result is the top
element on the stack.

Let's apply this algorithm to the given expression: 2 5 3 6 + * * 5 / 2 –


1. Create an empty stack: []
2. Scan the expression:
- 2: push onto stack [2]
- 5: push onto stack [2, 5]
- 3: push onto stack [2, 5, 3]
- 6: push onto stack [2, 5, 3, 6]
- +: pop 3 and 6, perform addition, push result [2, 5, 9]
- *: pop 5 and 9, perform multiplication, push result [2, 45]
- *: pop 2 and 45, perform multiplication, push result [90]
- 5: push onto stack [90, 5]
- /: pop 90 and 5, perform division, push result [18]
- 2: push onto stack [18, 2]
- -: pop 18 and 2, perform subtraction, push result [16]
3. The final result is the top element on the stack: [16]

Therefore, the evaluated result of the postfix expression 2 5 3 6 + * * 5 / 2 –


is 16.

3) Elaborate in detail about the double ended queue and their various
operations with suitable examples.
Ans:- A double-ended queue (deque) is a data structure that allows adding and
removing elements from both the beginning and the end of the queue. It is a versatile
data structure that combines the benefits of both stacks and queues.
Operations on a Deque:

Page No. 26
1. Add to the front (enque_front): Adds an element to the beginning of the deque.

Example:
Deque: []
Add 5 to the front: [5]
Add 3 to the front: [3, 5]
2. Add to the rear (enque_rear): Adds an element to the end of the deque.
Example:
Deque: []
Add 5 to the rear: [5]
Add 3 to the rear: [5, 3]
3. Remove from the front (deque_front): Removes the element from the beginning of
the deque.
Example:
Deque: [3, 5]
Remove from the front: [5]
4. Remove from the rear (deque_rear): Removes the element from the end of the deque.
Example:
Deque: [5, 3]
Remove from the rear: [5]
5. Peek at the front (front): Returns the element at the beginning of the deque without
removing it.
Example:
Deque: [3, 5]
Peek at the front: 3

6. Peek at the rear (rear): Returns the element at the end of the deque without removing
it.
Example:
Deque: [5, 3]
Peek at the rear: 3

Page No. 27
7. IsEmpty: Checks if the deque is empty.
Example:
Deque: []
IsEmpty: True
8. Size: Returns the number of elements in the deque.
Example:
Deque: [5, 3]
Size: 2
Implementing a Deque:

A deque can be implemented using a dynamic array or a linked list. The dynamic array
implementation is more efficient for small to medium-sized deques, while the linked list
implementation is more suitable for large deques.

4) Explain about the implementation of queue functions using arrays &


linked list
Ans:- Queues can be implemented using both arrays and linked lists. Here's a brief
overview of how:
Array Implementation:
1. Create an array of fixed size.
2. Use two indices, front and rear, to keep track of the first and last elements.
3. Enqueue: Add element to the end of the array (rear index) and increment rear.

4. Dequeue: Remove element from the front of the array (front index) and increment
front.
5. Check for overflow (array full) and underflow (array empty) conditions.
Front(f) rear(r)

Linked List Implementation:


1. Create a linked list with nodes having data and next pointers.
2. Use two pointers, front and rear, to point to the first and last nodes.
front(f) rear(r)
3. Enqueue: Add a new node at the end of the list (rear pointer) and update rear.

Page No. 28
4. Dequeue: Remove the node at the front of the list (front pointer) and update front.
5. No need to worry about overflow, as linked lists can dynamically grow.
Both implementations have their pros and cons:
Array Implementation:
- Efficient use of memory
- Fast indexing and access
- Limited size
Linked List Implementation:
- Dynamic size
- Efficient insertion and deletion
- Slower access and traversal
Choose the implementation based on your specific use case and requirements!

Unit-4
1 Marks
1) What is Traversal and its types?
Ans:- Traversal: Visiting each node in a data structure.
Types of Traversal:
1. Linear Traversal
2. Pre-Order Traversal
3. In-Order Traversal
4. Post-Order Traversal

2) Define a heap and show how it can be used to represent a priority


queue.
Ans:- Heap: A specialized tree-based data structure that satisfies the heap property.
Heap used to represent a priority queue:
- Highest (or lowest) priority element at the root.

Page No. 29
- Heap property ensures highest priority elements are at the top.
- Efficient insertion and extraction of highest (or lowest) priority element.

3) What is perfect binary tree?


Ans:- A perfect binary tree is a binary tree in which:
- All internal nodes have two children (left and right).
- All leaves are at the same level.
- All internal nodes have the same number of descendants.
(OR)
a perfect binary tree is a complete binary tree where every level is fully occupied,
with no missing nodes.
Example: 1
/ \
2 3
/ \ / \
4 5 6 7

4) What is Heapify?
Ans:- Heapify is a process of rearranging the elements of a heap to maintain the
heap property.
It involves:
- Comparing a node with its children
- Swapping the node with its largest (or smallest) child if necessary
- Repeating the process until the heap property is restored

5) Define height of the tree.


Ans:- The height of a tree is the number of edges on the longest path from the root
node to a leaf node.
For example, in the tree: 1
/ \
2 3
/ \
4 5

Page No. 30
The height is 3, since the longest path from the root (1) to a leaf (4 or 5) has 3 edges.

6) Summarize tree traversal and mention the type of traversals?


Ans:- Tree traversal is a process of visiting each node in a tree data structure, in a
specific order.
There are three main types of tree traversals:
1. In-Order Traversal: Visit left subtree, then the root node, and finally the right subtree.

2. Pre-Order Traversal: Visit the root node, then the left subtree, and finally the right
subtree.

3. Post-Order Traversal: Visit the left subtree, then the right subtree, and finally the root
node.

7) What is meant by bi-connected graph?


Ans:- A bi-connected graph is a graph that:
1. Is connected (has a path between every pair of vertices)
2. Remains connected even if any single vertex is removed (has no cut vertices or
articulation points)
Example: A graph with three or more vertices, where each vertex is connected to every
other vertex, is bi-connected.

LONG Answer
1) What is Heap? Illustrate the Min Heap and Max Heap with example
Ans:- A heap is a specialized tree-based data structure that satisfies the heap property. It
is a complete binary tree, meaning every level of the tree is fully filled except possibly
the last level, which is filled from left to right.
There are two types of heaps:

1. Min Heap: In a min heap, each parent node is less than or equal to its child nodes. The
smallest element is at the root.
Example of Min Heap:
4
/ \
6 2
/\ /\

Page No. 31
8 95 1
In this example, the smallest element (1) is at the root, and each parent node is less than
or equal to its child nodes.

2. Max Heap: In a max heap, each parent node is greater than or equal to its child nodes.
The largest element is at the root.
Example of Max Heap:
9
/ \
7 5
/\ /\
3 18 2
In this example, the largest element (9) is at the root, and each parent node is greater
than or equal to its child nodes.
Heaps are used in various algorithms, such as heap sort, priority queues, and graph
algorithms. They provide efficient insertion, deletion, and extraction of the minimum or
maximum element.

2) What is tree traversal? Explain in detail about various travels methods


with Examples.
Ans:- Tree traversal is the process of visiting each node in a tree data
structure, exactly once, in a specific order. It's a fundamental operation in
tree-based data structures, allowing you to perform various tasks such as
searching, inserting, deleting, and manipulating nodes.
There are several tree traversal methods, each with its own unique
approach and applications. Here are the most common tree traversal
methods, along with examples:

1. Inorder Traversal (Left-Root-Right):


- Visit the left subtree.
- Visit the root node.
- Visit the right subtree.

Page No. 32
Example:
4
/\
2 6
/\ \
1 3 5
Inorder traversal: 1, 2, 3, 4, 5, 6
2. Preorder Traversal (Root-Left-Right):
- Visit the root node.
- Visit the left subtree.
- Visit the right subtree.
Example: 4
/\
2 6
/\ \
1 3 5
Preorder traversal: 4, 2, 1, 3, 6, 5
3. Postorder Traversal (Left-Right-Root):
- Visit the left subtree.
- Visit the right subtree.
- Visit the root node.
Example:
4
/\
2 6
/\ \

Page No. 33
1 3 5
Postorder traversal: 1, 3, 2, 5, 6, 4
These tree traversal methods are essential in various applications, such as:
- Searching for a specific node or value.
- Inserting or deleting nodes while maintaining tree balance.
- Traversing trees in databases or file systems.
- Evaluating expressions in programming languages.
- Compiling code and generating syntax trees.
3) Illustrate the construction of heaps and its operations with a suitable
example.
Ans:- A heap is a specialized tree-based data structure that satisfies the heap
property:
- For a max heap, the parent node is greater than or equal to its child nodes.
- For a min heap, the parent node is less than or equal to its child nodes.
Let's consider a max heap example:
Suppose we have a list of numbers: [5, 3, 8, 2, 9, 1]
Construction:
1. Start with an empty heap.
2. Insert the first element (5) as the root node.
3. Insert the next element (3) as a child of the root node (5).
4. Insert the next element (8) as a child of the root node (5).
5. Continue inserting the remaining elements (2, 9, 1) in the same manner.
The resulting heap looks like this:
9
/ \
8 5
/ \ \
3 2 1
Operations:

Page No. 34
1. Insert: Insert a new element (6) into the heap.
a. Add the new element as a leaf node.
b. Compare the new element with its parent node. If it's greater, swap them.
c. Repeat step b until the heap property is satisfied.
9
/ \
8 6
/ \ / \
3 2 5 1

2. Delete: Remove the maximum element (9) from the heap.


a. Replace the root node with the last leaf node (5).
b. Compare the new root node with its child nodes. If it's smaller, swap them.
c. Repeat step b until the heap property is satisfied.
8
/ \
6 5
/ \ \
3 2 1
3. Extract Max: Return the maximum element (8) from the heap.
6
/ \
5 3
/ \ \
2 1
This example demonstrates the construction and operations of a max heap. Min heaps
follow a similar process, with the heap property reversed.

4) Illustrate in detail about Heap Sort with suitable examples.

Page No. 35
Ans:- Heap Sort is a popular sorting algorithm that uses a heap data structure to
sort an array of elements. Here's a step-by-step explanation of the Heap Sort algorithm
with examples:
Step 1: Build a Max Heap
- Start with an unsorted array: [5, 3, 8, 2, 9, 1]
- Build a max heap by repeatedly inserting elements into the heap:
9
/ \
8 5
/ \ \
3 2 1
Step 2: Heapify the Array
- Starting from the last non-leaf node (8), heapify the array by swapping elements to
maintain the max heap property:
9
/ \
5 8
/ \ \
3 2 1
Step 3: Extract Maximum Element
- Extract the maximum element (9) from the heap and place it at the end of the array:
8
/ \
5 3
/ \ \
2 1 9
Step 4: Repeat Heapify and Extract
- Repeat steps 2 and 3 until the heap is empty:
8
/ \

Page No. 36
5 3
/ \ \
2 1
5
/ \
3 2
/ \
1 8

3
/ \
2 1
/
5

2
/
1
/
3

1
/
2

1
Step 5: Sorted Array
- The final sorted array is: [1, 2, 3, 5, 8, 9]

Page No. 37
UNIT-5
1 Marks
1) Define Hash function.
Ans:- A hash function is a mathematical function that takes a variable-
length input (such as a string or an integer) and returns a fixed-length
output (known as a hash value or digest). The output of a hash function is
unique to the input and is designed to be collision-resistant, meaning that it
is unlikely to produce the same output for different inputs.
2) List any two applications of Hashing
Ans:- Two applications of hashing are:
1. Data Integrity: Ensuring data has not been tampered with or corrupted.
2. Password Storage: Storing passwords securely to prevent unauthorized access.

3) Create an undirected graph and its adjacency matrix for the following
specification of a graph G. V(G)=1,2,3,4 E(G)={
(1,2),(1,3),(3,3),(3,4),(4,1) }
Ans:- Here is the adjacency matrix for the graph G:

1 2 3 4
|--- | - | - | --| -- |
1 |0|1|1|1|
2 |1|0|0|0|
3 |1|0|2|1|
4 |1|0|1|0|

4) How to calculate the hash key? Give the example.


Ans:- To calculate the hash key for the string "1" using a simple hash function that
sums up the ASCII values:
1. Convert the character "1" to its ASCII value:
- "1" -> 49

Page No. 38
2. The hash key is the ASCII value:
- Hash key = 49
So, the hash key for the string "1" is 49.

5) What is the condition for complete directed graph?


Ans:- A complete directed graph has:
- Every vertex connected to every other vertex by a directed edge.
- n(n-1) edges, where n is the number of vertices.

6) Differentiate cyclic and acyclic graph.


Ans:- Here's the difference between cyclic and acyclic graphs:

Cyclic Graph:

- A graph that contains at least one cycle (a path that starts and ends at the same vertex, passing
through at least one edge more than once).

- A graph that has a closed path.

- Example: A -> B -> C -> A (this graph has a cycle ABCA)

Acyclic Graph:

- A graph that does not contain any cycles.

- A graph where every path is a simple path (no repeated edges or vertices).

- Example: A -> B -> C (this graph does not have any cycles)

In summary, if a graph has a cycle, it's cyclic. If it doesn't have any cycles, it's acyclic.

(OR)

Cyclic graph: Has a closed path (A → B → C → A).

Acyclic graph: No closed paths, only open paths (A → B → C).

7) What is meant by bi-connected graph?


Ans:- A bi-connected graph (also known as a 2-connected graph) is a graph that:
1. Is connected (has a path between every pair of vertices).
2. Remains connected even after removing any single vertex (and its incident edges).
In other words, a graph is bi-connected if it has no articulation points (vertices whose
removal would disconnect the graph).
Example: A graph with a cycle (A → B → C → A) is bi-connected because removing any
single vertex (and its edges) still leaves a path between the remaining vertices.

8) Define collision. give the two methods of handle collision

Page No. 39
Ans:-
Definition of Collision:

A collision occurs when two or more elements in a hash table hash to the same index
or slot.
Two methods to handle collision:
1. Separate Chaining
2. Open Addressing

Long Answers
1) Define Graph Data Structure. Discuss the most common
ways to represent a graph.
3_) Describe in detail about the following representations
of a graph. i) Adjacency Matrix ii) Adjacency List

Page No. 40
Ans:-

Page No. 41
Page No. 42
4_) Given input {4371, 1323, 6173, 4199,4344, 9679, 1989} and a hash function h(x) =x
mod 10. Prepare the resulting for the following:
1. Open hash table.
2. Open addressing hash table using linear probing.
3. Open addressing hah table using quadratic probing.

Page No. 43
Page No. 44
5_) Examine topological sorting of a graph G with suitable example

Page No. 45
Page No. 46
7_)

Page No. 47
Ans:-

Page No. 48
8_)

Ans:-

Page No. 49

You might also like