0% found this document useful (0 votes)
10 views

Ronak Data Structures Paper 2022-23 QnA 01

The document discusses various concepts related to data structures and algorithms, including features of efficient algorithms, primitive data structures, asymptotic notations, and operations on data structures. It also covers linked lists, stacks, queues, binary trees, searching techniques, and graph representations. Additionally, it provides algorithms for operations like insertion and deletion in linked lists, as well as examples of tree and graph structures.

Uploaded by

abhay72003
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)
10 views

Ronak Data Structures Paper 2022-23 QnA 01

The document discusses various concepts related to data structures and algorithms, including features of efficient algorithms, primitive data structures, asymptotic notations, and operations on data structures. It also covers linked lists, stacks, queues, binary trees, searching techniques, and graph representations. Additionally, it provides algorithms for operations like insertion and deletion in linked lists, as well as examples of tree and graph structures.

Uploaded by

abhay72003
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/ 26

2022

Part A
### (a) What are the features of an efficient algorithm?

1. **Correctness**: The algorithm should produce the correct output for all possible valid
inputs.
2. **Time Complexity**: The amount of me taken by the algorithm to complete should be
as low as possible.
3. **Space Complexity**: The amount of memory space required by the algorithm should
be minimized.
4. **Readability and Simplicity**: The algorithm should be easy to understand and
implement.
5. **Scalability**: The algorithm should perform well even as the size of the input data
increases.
6. **Robustness**: The algorithm should handle edge cases and unexpected inputs
gracefully.

### (b) What do you mean by Primi ve Data Structure?

Primi ve data structures are the most basic forms of data structures directly supported by
the system or programming language. These include:
- **Integer**: Whole numbers
- **Float**: Floa ng-point numbers or real numbers
- **Character**: Single characters or le ers
- **Boolean**: True or false values

### (c) What are Asympto c Nota ons?

Asympto c nota ons are mathema cal tools to represent the me complexity and space
complexity of algorithms. They describe the behavior of an algorithm in terms of input size
as the input size grows. Common asympto c nota ons include:
- **Big O Nota on (O)**: Upper bound, worst-case complexity.
- **Omega Nota on (Ω)**: Lower bound, best-case complexity.

- **Theta Nota on (Θ)**: Tight bound, average-case complexity.


- **Li le o Nota on (o)**: Upper bound that is not asympto cally ght.
- **Li le omega Nota on (ω)**: Lower bound that is not asympto cally ght.

### (d) List the various opera ons that can be performed on data structure.

1. **Inser on**: Adding an element to the data structure.


2. **Dele on**: Removing an element from the data structure.
3. **Traversal**: Accessing each element of the data structure exactly once.
4. **Searching**: Finding the loca on of an element in the data structure.
5. **Sor ng**: Arranging the elements in a par cular order (ascending or descending).
6. **Merging**: Combining two or more data structures into one.

### (e) What are the pi alls encountered in Singly linked list?

1. **Traversal Time**: Traversing a singly linked list can take more me compared to arrays
since you must follow the links.
2. **Memory Usage**: Each element requires addi onal memory for storing a
pointer/reference to the next element.
3. **Inser on/Dele on at End**: Inser on and dele on at the end of the list require
traversal from the head to the last node.
4. **No Backward Traversal**: Only forward traversal is possible, making some opera ons
more complex or inefficient.

### (f) Difference between Arrays and Lists.

- **Arrays**:
- Fixed size.
- Homogeneous elements (same data type).
- Con nuous memory alloca on.
- Faster access (O(1) me complexity for indexing).

- Inser on and dele on can be costly due to shi ing elements.

- **Lists (Linked Lists)**:


- Dynamic size.
- Heterogeneous elements (can be different data types).
- Non-con nuous memory alloca on.
- Slower access (O(n) me complexity for indexing).
- Easier inser on and dele on without shi ing elements.

### (g) How do you test for an empty queue?

To test for an empty queue, you typically check if the front pointer or the size of the queue is
zero. For example:
- If using an array-based queue: `if (front == -1 || front > rear)`.
- If using a linked list-based queue: `if (head == NULL)`.

### (h) List any four applica ons of stack.

1. **Expression Evalua on and Syntax Parsing**: Used in compilers for evalua ng


expressions and parsing syntax.
2. **Backtracking**: Algorithms like maze solving and puzzle solving use stacks for
backtracking.
3. **Func on Call Management**: Used in func on call management and recursion,
maintaining the call stack.
4. **Undo Mechanism**: Applica ons like text editors use stacks to implement undo
func onality.

### (i) Define threaded binary tree.


A threaded binary tree is a binary tree variant where null pointers are replaced with pointers
to the in-order predecessor or successor. This structure allows for in-order traversal of the
tree without the use of a stack or recursion.

### (j) Define Searching technique. Which searching technique is faster?

Searching techniques are methods to find an element within a data structure. Common
searching techniques include:
- **Linear Search**: Sequen ally checking each element un l the target is found.
- **Binary Search**: Repeatedly dividing the search interval in half, used on sorted arrays.

**Binary Search** is generally faster than linear search for large, sorted datasets, with a
me complexity of O(log n) compared to O(n) for linear search.

PART - B
## UNIT - I
### 2. (a) What are Data Structures? Explain the classifica on of data structures with neat
diagram.

**Data Structures** are organized ways to store, manage, and manipulate data in a
computer system, enabling efficient access and modifica on. They are essen al for various
compu ng tasks and algorithms.

**Classifica on of Data Structures:**


1. **Primi ve Data Structures:**

- Integer
- Float
- Character
- Boolean

2. **Non-Primi ve Data Structures:**


- **Linear Data Structures:**
- Arrays
- Linked Lists
- Stacks
- Queues
- **Non-Linear Data Structures:**
- Trees
- Graphs
- Heaps
- Hash Tables

**Diagram:**

```plaintext
Data Structures
|
|-- Primi ve
| |-- Integer
| |-- Float

| |-- Character
| |-- Boolean
|
|-- Non-Primi ve
|
|-- Linear
| |-- Array
| |-- Linked List
| |-- Stack
| |-- Queue
|
|-- Non-Linear
|-- Tree
|-- Graph
|-- Heap
|-- Hash Table
```

### (b) Define Prefix and Pos ix Expression. Write a program to convert infix to pos ix
expression.

- **Prefix Expression:** An expression in which the operator precedes its operands.


Example: `+AB` (equivalent to `A + B`).
- **Pos ix Expression:** An expression in which the operator follows its operands. Example:
`AB+` (equivalent to `A + B`).

**Program to Convert Infix to Pos ix in C#:**


```csharp
using System;

using System.Collec ons.Generic;

class Program
{
sta c int Precedence(char op)
{
switch (op)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}

sta c string InfixToPos ix(string expression)


{
Stack<char> stack = new Stack<char>();
string result = "";

foreach (char c in expression)


{
if (char.IsLe erOrDigit(c))
{
result += c;

}
else if (c == '(')
{
stack.Push(c);
}
else if (c == ')')
{
while (stack.Count > 0 && stack.Peek() != '(')
{
result += stack.Pop();
}
stack.Pop();
}
else
{
while (stack.Count > 0 && Precedence(stack.Peek()) >= Precedence(c))
{
result += stack.Pop();
}
stack.Push(c);
}
}

while (stack.Count > 0)


{
result += stack.Pop();
}
return result;

sta c void Main()


{
string expression = "A+B*(C-D)";
Console.WriteLine("Infix Expression: " + expression);
Console.WriteLine("Pos ix Expression: " + InfixToPos ix(expression));
}
}
```

## OR

### 2. (a) What is Analysis of Algorithm? Explain the Asympto c Nota on (Big O, Ω, Θ)
used while analyzing an algorithm.

**Analysis of Algorithm:** The process of determining the computa onal complexity of


algorithms - the amount of me, storage, or other resources needed to execute them. It
helps in understanding the efficiency and performance of an algorithm.

**Asympto c Nota ons:**

1. **Big O Nota on (O):** Describes the upper bound of the me complexity. It gives the
worst-case scenario.
- Example: O(n^2) indicates the algorithm's me complexity grows at most propor onal to
the square of the input size.

2. **Omega Nota on (Ω):** Describes the lower bound of the me complexity. It gives the
best-case scenario.
- Example: Ω(n) indicates the algorithm's me complexity grows at least propor onal to
the input size.

3. **Theta Nota on (Θ):** Describes the exact bound of the me complexity. It provides
both the upper and lower bounds.
- Example: Θ(n log n) indicates the algorithm's me complexity grows exactly propor onal
to n log n.

### (b) Describe about pseudo code.

**Pseudo code:** A high-level descrip on of an algorithm using the structural conven ons
of programming languages but in a simplified form. It focuses on the logic rather than syntax
and helps in understanding the algorithm without ge ng into programming details.

Example:
```plaintext
Algorithm: Find the maximum number in a list
Input: List of numbers
Output: Maximum number

Procedure findMax(list):
max = list[0]
for each number in list:

if number > max:


max = number
return max
```

### (c) Describe space and me complexity of algorithm.


**Space Complexity:** The amount of memory space required by an algorithm to execute,
including input size and auxiliary space.
- Example: An algorithm with O(1) space complexity uses constant space regardless of
input size.

**Time Complexity:** The amount of me required by an algorithm to execute, usually


represented as a func on of the input size.
- Example: An algorithm with O(n) me complexity runs linearly with the input size.

## UNIT - II

### 3. (a) What is linked-list? Give the data structure and write algorithm to-
(i) Delete an element
(ii) Count the number of elements.

**Linked List:** A data structure consis ng of nodes, where each node contains a data value
and a reference (or link) to the next node in the sequence.

**Data Structure of Linked List Node in C#:**

```csharp
public class Node
{

public int data;


public Node next;

public Node(int d)
{
data = d;
next = null;
}
}
```

**Algorithm to Delete an Element in C#:**

```csharp
public Node DeleteNode(Node head, int key)
{
Node temp = head, prev = null;

if (temp != null && temp.data == key)


{
head = temp.next;
return head;
}

while (temp != null && temp.data != key)


{
prev = temp;
temp = temp.next;
}

if (temp == null) return head;

prev.next = temp.next;
return head;
}
```
**Algorithm to Count Number of Elements in C#:**

```csharp
public int CountNodes(Node head)
{
int count = 0;
Node current = head;

while (current != null)


{
count++;
current = current.next;
}

return count;
}
```

### (b) When doubly linked list can be represented as Circular Linked List?

A doubly linked list can be represented as a circular linked list when the `next` pointer of the
last node points to the first node, and the `prev` pointer of the first node points to the last
node, forming a circular chain.

### (c) Write the rou ne for inser on opera on of singly linked list.

**Inser on in Singly Linked List in C#:**

```csharp
public Node InsertNode(Node head, int data)
{
Node newNode = new Node(data);

if (head == null)
{
head = newNode;
return head;
}

Node last = head;


while (last.next != null)
{
last = last.next;
}

last.next = newNode;
return head;
}
```

## OR

### 3. (a) List out the steps involved in dele ng a node from a Binary Search Tree.

1. **Find the Node to be Deleted**: Traverse the tree to locate the node.
2. **Node has No Children (Leaf Node)**: Simply remove the node.
3. **Node has One Child**: Remove the node and replace it with its child.
4. **Node has Two Children**: Find the in-order successor (smallest node in the right
subtree) or in-order predecessor (largest node in the le subtree), replace the node's value
with it, and delete the successor or predecessor node.
### (b) Define tree-traversal and men on the types of traversals.

**Tree Traversal:** The process of visi ng all the nodes in a tree data structure in a specific
order.

**Types of Traversals:**
1. **In-Order Traversal (Le , Root, Right):** Visits the le subtree, root, and then the right
subtree.
2. **Pre-Order Traversal (Root, Le , Right):** Visits the root, le subtree, and then the right
subtree.
3. **Post-Order Traversal (Le , Right, Root):** Visits the le subtree, right subtree, and then
the root.

4. **Level-Order Traversal:** Visits nodes level by level, from top to bo om.

### (c) List out the applica ons of Tree Data Structure.

1. **Hierarchical Data Representa on:** File systems, organiza onal structures.


2. **Searching Algorithms:** Binary search trees, AVL trees.
3. **Network Rou ng Algorithms:** Spanning trees.
4. **Expression Evalua on:** Parse trees for mathema cal expressions.
5. **Database Indexing:** B-trees, B+ trees.
6. **Priority Queues:** Binary heaps.

## UNIT - III

### 4. Explain the various representa on of graph with example in detail.

**Graph Representa ons:**

1. **Adjacency Matrix:**
- A 2D array where each cell `[i][j]` is `1` if there is an edge between vertex `i` and vertex `j`,
otherwise `0`.

**Example:**

```plaintext
010
101
010
```

2. **Adjacency List:**
- An array of lists. The index represents the vertex, and the list at each index contains the
adjacent ver ces.

**Example:**

```plaintext
0: 1
1: 0, 2
2: 1

```

3. **Incidence Matrix:**
- A 2D array where rows represent ver ces and columns represent edges. The entry `(i, j)`
is `1` if vertex `i` is connected by edge `j`.
**Example:**

```plaintext
e1 e2 e3
1 1 0
1 0 1
0 1 1
```

## OR

### Write about the followings:

**(i) Biconnected Graph:**


- A graph is biconnected if there are no ver ces whose removal would disconnect the
graph. In such graphs, there are at least two dis nct paths between any two ver ces.

**(ii) Adjacent Graph:**


- Refers to the presence of an edge connec ng two ver ces. If ver ces `u` and `v` are
connected by an edge, they are adjacent.

**(iii) Levels in Graph:**


- In a graph, levels refer to the distance from a chosen root vertex in terms of edges. The
root is level 0, its neighbors are level 1, and so on.

**(iv) Undirected Acyclic Graph:**


- A graph with no cycles and where the edges have no direc on. This is also known as a
forest, and if connected, it's called a tree.

**(v) Weighted Graph:**


- A graph in which each edge has an associated numerical value (weight), represen ng
costs, lengths, or capaci es of the edges.

### 5. (a) What do you mean by Internal and External Sor ng?

- **Internal Sor ng:** Sor ng algorithms that assume the en re dataset fits into the main
memory. Examples: Quick sort, Merge sort.
- **External Sor ng:** Sor ng algorithms designed for datasets that are too large to fit into
main memory and must be stored on external storage. Examples: External merge sort, Mul -
way merge sort.

### (b) List out the different types of Hashing func ons.

1. **Division Method:** Uses the remainder of division as the hash value.


2. **Mul plica on Method:** Mul plies the key by a constant and extracts the frac onal
part.
3. **Mid-Square Method:** Squares the key and uses the middle part of the result as the
hash value.
4. **Folding Method:** Breaks the key into parts, adds them together, and then uses the
result.
5. **Universal Hashing:** Uses a family of hash func ons to minimize collisions.

### (c) Write an algorithm to implement bubble sort with suitable example.

**Bubble Sort Algorithm in C#:**

```csharp
using System;

class Program
{
sta c void BubbleSort(int[] arr)
{
int n = arr.Length;

for (int i = 0; i < n - 1; i++)


{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

sta c void Main()


{
int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
BubbleSort(arr);
Console.WriteLine("Sorted array is:");
foreach (int item in arr)
{
Console.Write(item + " ");
}
}
}
```
## OR

### 5. (a) Define Hashing. What is the need for hashing?

**Hashing:** A technique to convert a given key into a unique hash value (index) in an array
or table. It provides a way to quickly access data based on the generated index.

**Need for Hashing:**


- To provide fast data retrieval.
- To reduce the me complexity of search, insert, and delete opera ons, o en to O(1).

### (b) What is Extendible Hashing?

**Extendible Hashing:** A type of dynamic hashing that allows the hash table to expand
and contract as keys are added and removed. It uses a directory of pointers to buckets and
allows the table to grow by spli ng buckets when they become full.

### (c) Compare Quick Sort and Merge Sort.

- **Quick Sort:**
- Average and Best Case Time Complexity: O(n log n)
- Worst Case Time Complexity: O(n^2) (can be improved with randomiza on)
- In-place sor ng (no extra space required)
- Faster in prac ce due to good cache performance

- **Merge Sort:**
- Time Complexity: O(n log n) for all cases
- Requires addi onal space for merging (not in-place)
- Stable sor ng algorithm
- Preferred for sor ng linked lists and external sor ng
### (d) How does inser on sort algorithm work?

**Inser on Sort Algorithm in C#:**

```csharp
using System;

class Program
{
sta c void Inser onSort(int[] arr)
{
int n = arr.Length;
for (int i = 1; i < n; ++i)
{
int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key)


{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

sta c void Main()


{
int[] arr = { 12, 11, 13, 5, 6 };
Inser onSort(arr);

Console.WriteLine("Sorted array is:");


foreach (int item in arr)
{
Console.Write(item + " ");
}
}
}
```

2023
Here are the answers to the ques ons from the extracted content of the "Ronak Data
Structures Paper 2023":
---
### PART - A:

1. (a) **What is pseudocode?**


- **Answer:** Pseudocode is a high-level descrip on of a computer program or algorithm.
It uses the structural conven ons of programming languages but is intended for human
reading rather than machine reading. It helps programmers plan and communicate their
code logic.

(b) **What are abstract data types?**


- **Answer:** Abstract Data Types (ADTs) are a model for data structures that specify the
type of data stored, the opera ons that can be performed on them, and the types of
parameters of the opera ons. ADTs provide a theore cal framework for data structures and
separate the interface from the implementa on.

(c) **Dis nguish between prefix and pos ix expressions.**


- **Answer:** Prefix (Polish) nota on is a way of wri ng mathema cal expressions where
the operator precedes their operands. For example, the prefix form of `(A + B)` is `+ AB`.
Pos ix (Reverse Polish) nota on, on the other hand, places the operator a er the operands,
such as `AB +` for `(A + B)`.

(d) **What is a linked list?**


- **Answer:** A linked list is a linear data structure where each element, called a node,
contains a data part and a reference (or link) to the next node in the sequence. Linked lists
can be singly linked, doubly linked, or circularly linked.

(e) **Explain the following terms in tree:**


- **(i) Internal Node:**
- **Answer:** An internal node is any node of a tree that has at least one child. It is not a
leaf node and is also known as an inner node.
- **(ii) Level:**
- **Answer:** The level of a node in a tree is the number of edges on the path from the
root node to the node. The root node is at level 0, and its children are at level 1, and so on.
- **(iii) Path:**
- **Answer:** A path in a tree is a sequence of nodes and edges connec ng a node with
a descendant.

(f) **What is a graph?**


- **Answer:** A graph is a data structure consis ng of a finite set of ver ces (or nodes)
and a set of edges connec ng these ver ces. Graphs can be directed or undirected.

(g) **What is an undirected graph?**


- **Answer:** An undirected graph is a graph in which edges have no direc on. The edge
`(u, v)` is iden cal to the edge `(v, u)`.

(h) **What do you know by Weighted Graph? Explain.**


- **Answer:** A weighted graph is a graph in which each edge has an associated numerical
value, called a weight. These weights could represent distances, costs, or any other
quan ta ve measure.

(i) **What is a binary tree?**


- **Answer:** A binary tree is a tree data structure in which each node has at most two
children, referred to as the le child and the right child.

(j) **What is traversal in linked list?**


- **Answer:** Traversal in a linked list refers to the process of visi ng each node in the list
sequen ally from the first node (head) to the last node (tail).

### PART - B:

2. **Explain the concept of a stack and provide an example of its opera on.**
- **Answer:** A stack is a linear data structure that follows the Last In, First Out (LIFO)
principle. Elements are added (pushed) and removed (popped) from the top of the stack. For
example, if we push elements `1, 2, 3` onto the stack, and then pop an element, we get `3`.

OR

**What is the concept of a priority queue? How is it different from a regular queue?**
- **Answer:** A priority queue is an abstract data type similar to a regular queue or stack
data structure in which each element addi onally has a priority associated with it. In a
priority queue, an element with high priority is served before an element with low priority.
This is different from a regular queue where elements are served in the order they were
added (FIFO).

3. **Write an algorithm to insert a node between two nodes in a doubly linked list.**
- **Answer:**
```python
def insert_between(node_before, node_a er, new_node):
new_node.prev = node_before

new_node.next = node_a er
node_before.next = new_node
node_a er.prev = new_node
```

OR

**Describe the process of tree traversal. What are the different types of tree traversal
algorithms?**
- **Answer:** Tree traversal is the process of visi ng all the nodes of a tree in a specific
order. The different types of tree traversal algorithms are:
- **Preorder Traversal:** Visit the root node, then recursively visit the le subtree, and
finally the right subtree.
- **Inorder Traversal:** Recursively visit the le subtree, visit the root node, and then the
right subtree.
- **Postorder Traversal:** Recursively visit the le subtree, then the right subtree, and
finally the root node.
- **Level Order Traversal:** Visit the nodes level by level star ng from the root.

4. **What is the difference between Breadth-First Search (BFS) and Depth-First Search
(DFS)? When would you use each algorithm?**
- **Answer:**
- **BFS:** BFS explores the neighbor nodes level by level star ng from the root. It uses a
queue to keep track of the next node to visit.
- **DFS:** DFS explores as far down a branch as possible before backtracking. It uses a
stack (or recursion) to keep track of nodes to visit.
- **Use cases:** BFS is used when the shortest path is sought, like in finding the shortest
path in an unweighted graph. DFS is used for traversing or searching tree or graph data
structures, o en in scenarios like topological sor ng or detec ng cycles.

OR
**Describe the concept of graph traversal. What are the different graph traversal
algorithms?**
- **Answer:** Graph traversal is the process of visi ng all the ver ces and edges of a
graph. The different graph traversal algorithms are:
- **Breadth-First Search (BFS):** Traverses the graph level by level.
- **Depth-First Search (DFS):** Traverses the graph by exploring as deep as possible along
each branch before backtracking.

5. **What is the difference between a linear search and a binary search algorithm? In
what scenarios would you choose one over the other?**
- **Answer:**
- **Linear Search:** This algorithm checks each element of the list sequen ally un l the
desired element is found or the list ends. It is simple and works on both sorted and unsorted
lists.
- **Binary Search:** This algorithm finds the posi on of a target value within a sorted
array. It compares the target value to the middle element and eliminates half of the
remaining elements at each step.
- **Use cases:** Use linear search for small or unsorted lists and binary search for large,
sorted lists for faster search opera ons.

OR

**Explain the concept of a hash func on and its role in hash tables.**
- **Answer:** A hash func on is a func on that takes input (or 'key') and returns a fixed-
size string of bytes. The output is typically a 'hash code' used to index a hash table. The role
of a hash func on in hash tables is to efficiently distribute keys into buckets to allow for fast
data retrieval.

---

If you need further elabora on or have any specific ques ons on these topics, feel free to
ask!

You might also like