DS Unit 1 IQ
DS Unit 1 IQ
DS UNIT-1
1.1-Define the term Data Structure. List some linear and non-linear data
structures stating the application area where they will be used
Data structure?
A data structure is a technique of storing and organizing the data in such a way that the
data can be utilized in an efficient manner.. A data structure is classified into two
categories:
A linear data structure is a structure in which the elements are stored sequentially, and
the elements are connected to the previous and the next element. As the elements are
stored sequentially, so they can be traversed or accessed in a single run. The types of
linear data structures are Array, Queue, Stack, Linked List.
A non-linear data structure is also another type of data structure in which the data
elements are not arranged in a contiguous manner. As the arrangement is nonsequential,
so the data elements cannot be traversed or accessed in a single run. in the non-linear
data structure, an element can be connected to more than two elements.
Its examples are: array, stack, queue, While its examples are: trees
5. linked list, etc. and graphs.
Ans:
Theta notation
Ans:
Time Complexity: The time complexity of an algorithm quantifies the amount of time
taken by an algorithm to run as a function of the length of the input. Note that the time
to run is a function of the length of the input and not the actual execution time of the
machine on which the algorithm is running on.
Que 1.6. Write difference between array and linked list. AKTU 2014-15, Marks 05
Ans:
Ans:
Array is a linear data structure that is a collection of similar data types. Arrays are
stored in contiguous memory locations. It is a static data structure with a fixed size. It
combines data of similar types.
ARRAY
1. Multiple data items of same type can be declared using same name but
different indexes
2. Accessing an element becomes easy just by using index no.
3. Arrays allocate memory in contiguous memory locations . Hence no extra
memory is allocated.
Disadvantages:
Que 1.8. What is Row and Colom major order ? Explain with an example.
Ans:
Calculation of address of element of 1-D, 2-D, and 3-D using row-major and
column-major order
A 1-dimensional array (or single-dimension array) is a type of linear array. Accessing its
elements involves a single subscript that can either represent a row or column index.
Example:
2-D array
Example: Given the base address of an array A[1300 ………… 1900] as 1020 and the
size of each element is 2 bytes in the memory, find the address of A[1700].
Solution:
Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700
Formula used:
Address of A[I] = B + W * (I – LB)
Solution:
Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820
The 2-dimensional array can be defined as an array of arrays. The 2-Dimensional arrays
are organized as matrices which can be represented as the collection of rows and
columns as array[M][N] where M is the number of rows and N is the number of
columns.
Example:
2-D array
To find the address of any element in a 2-Dimensional array there are the following
two ways-
1. Row Major Order
2. Column Major Order
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as
zero),
N = Number of column given in the matrix.
Example: Given an array, arr[1………10][1………15] with base value 100 and the size of
each element is 1 Byte in memory. Find the address of arr[8][6] with the help of row-
major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
Example: Given an array arr[1………10][1………15] with a base value of 100 and the
size of each element is 1 Byte in memory find the address of arr[8][6] with the help of
column-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
From the above examples, it can be observed that for the same position two different
address locations are obtained that’s because in row-major order movement is done
across the rows and then down to the next row, and in column-major order, first move
down to the first column and then next column. So both the answers are right.
So it’s all based on the position of the element whose address is to be found for some
cases the same answers is also obtained with row-major order and column-major order
and for some cases, different answers are obtained.
Calculate the address of any element in the 3-D Array:
To find the address of any element in 3-Dimensional arrays there are the following two
ways-
Row Major Order
Column Major Order
Example: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of
each element is 2 Bytes in memory find the address of element arr[5][-1][8] with the
help of row-major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 5
Column Subset of an element whose address to be found J = -1
Block Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of row/start row index of matrix x = 1
Lower Limit of column/start column index of matrix y = -4
Lower Limit of blocks in matrix z = 5
M = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N = Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6
Formula used:
Address of[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))
Solution:
Address of arr[5][-1][8] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]
= 400 + 2 * ((4 * 6 + 3) * 6 + 3)
= 400 + 2 * (165)
= 730
Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of
each element is 4 Bytes in memory find the address of element arr[3][3][3] with the
help of column-major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3
Que 1.8. Consider the linear arrays AAA [5 : 50], BBB [– 5 : 10] and CCC [1 : 8].
a.Find the number of elements in each array.
b. Suppose base (AAA) = 300 and w = 4 words per memory cell for AAA.
Find the address of AAA [15], AAA [35] and AAA [55].
Que 1.9. Suppose multidimensional arrays P and Q are declared as P(– 2: 2, 2: 22)
and Q(1: 8, – 5: 5, – 10 : 5) stored in column major order
1.17- Explain how sparse matrices are represented in memory. Also explain
upper triangular and lower triangular sparse matrices
Ans:
If most of the elements of the matrix have 0 value, then it is called a sparse matrix.
Why to use Sparse Matrix instead of simple matrix ?
Storage: There are lesser non-zero elements than zeros and thus lesser memory
can be used to store only those elements.
Computing time: Computing time can be saved by logically designing a data
structure traversing only non-zero elements..
Example:
00304
00570
00000
02600
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as
zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes
with non-zero elements, we only store non-zero elements. This means storing non-
zero elements with triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common
representations:
1. Array representation
2. Linked list representation
Ans:
Linked List
o Linked List can be defined as collection of objects called nodes that are randomly
stored in the memory.
o A node contains two fields i.e. data stored at that particular address and the
pointer which contains the address of the next node in the memory.
o The last node of the list contains pointer to the null.
o The list is not required to be contiguously present in the memory. The node can
reside any where in the memory and linked together to make a list. This achieves
optimized utilization of space.
o list size is limited to the memory size and doesn't need to be declared in advance.
o Empty node can not be present in the linked list.
o We can store values of primitive types or objects in the singly linked list.
Till now, we were using array data structure to organize the group of elements that are
to be stored individually in the memory. However, Array has several advantages and
disadvantages which must be known in order to decide the data structure which will be
used throughout the program.
1. The size of array must be known in advance before using it in the program.
2. Increasing size of the array is a time taking process. It is almost impossible to
expand the size of the array at run time.
3. All the elements in the array need to be contiguously stored in the memory.
Inserting any element in the array needs shifting of all its predecessors.
Linked list is the data structure which can overcome all the limitations of an array. Using
linked list is useful because,
1. It allocates the memory dynamically. All the nodes of linked list are non-
contiguously stored in the memory and linked together with the help of pointers.
2. Sizing is no longer a problem since we do not need to define its size at the time of
declaration. List grows as per the program's demand and limited to the available
memory spa
Complexity
Data Time Complexity Space
Structure Compleity
The nodes are connected to each other in this form where the value of the next
variable of the last node is NULL i.e. next = NULL , which indicates the end of the
linked list.
The following is the structure of the node in the Doubly Linked List(DLL):
The nodes are connected to each other in this form where the first node has prev =
NULL and the last node has next = NULL .
It will require more space as each node has an extra memory to store the
address of the previous node.
The number of modification increase while doing various operations like
insertion, deletion, etc.
Circular lists are the required data structure when we want a list to be accessed
in a circle or loop.
We can easily traverse to its previous node in a circular linked list, which is not
possible in a singly linked list. ( Think!)
Disadvantages of Circular linked list
If not traversed carefully, then we could end up in an infinite loop because here
we don't have any NULL value to stop the traversal.
Operations in a circular linked list are complex as compared to a singly linked
list and doubly linked list like reversing a circular linked list, etc.
Start with the head of the list. Access the content of the head node if it is not
null.
Then go to the next node(if exists) and access the node information
Continue until no more nodes (that is, you have reached the null node)
Insertion at end
We will traverse the list until we find the last node. Then we insert the new node to
the end of the list. Note that we have to consider special cases such as list being empty.
In case of a list being empty, we will return the updated head of the linked list because
in this case, the inserted node is the first as well as the last node of the linked list.
We are given the reference to a node, and the new node is inserted after the given
node.
NOTE: If the address of the prevNode is not given, then you can traverse to that node
by finding the data value.
Ans:
Overflow condition:
This condition is associated with the basic operations on the liked list of inserting an
element in the list.
We initiate this condition before adding a node to the linked list.
In the system, this condition happens when there is no vacant memory cell.
Underflow condition:
This condition is associated with the basic operations on the liked list of deleting an
element in the list.
1.20-List the advantages of doubly linked list over single linked list
Ans:
Singly Linked List vs Doubly Linked List
Before looking at the differences between the singly linked list and doubly linked list, we
first understand what is singly linked list and doubly linked list separately.
A singly linked list can be simply called a linked list. A singly linked list is a list that
consists of a collection of nodes, and each node has two parts; one part is the data part,
and another part is the address. The singly linked can also be called a chain as each node
refers to another node through its address part. We can perform various operations on a
singly linked list like insertion, deletion, and traversing.
A doubly linked list is another type of the linked list. It is called a doubly linked list
because it contains two addresses while a singly linked list contains a single address. It is
a list that has total three parts, one is a data part, and others two are the pointers, i.e.,
previous and next. The previous pointer holds the address of the previous node, and the
next pointer holds the address of the next node. Therefore, we can say that list has two
references, i.e., forward and backward reference to traverse in either direction.
Que 1.21. What are doubly linked lists ? Write C program to create doubly linked
list. AKTU 2015-16, Marks 10
Ans:
A doubly linked list containing three nodes having numbers from 1 to 3 in their data
part, is shown in the following image.
1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. }
The prev part of the first node and the next part of the last node will always contain null
indicating end in each direction.
In a singly linked list, we could traverse only in one direction, because each node contains
address of the next node and it doesn't have any record of its previous nodes. However,
doubly linked list overcome this limitation of singly linked list. Due to the fact that, each
node of the list contains the address of its previous node, we can find all the details about
the previous node as well by using the previous address stored inside the previous part
of each node.
Node Creation
1. struct node
2. {
3. struct node *prev;
4. int data;
5. struct node *next;
6. };
7. struct node *head;
All the remaining operations regarding doubly linked list are described in the following
table.
SN Operation Description
1 Insertion at beginning Adding the node into the linked list at beginning.
2 Insertion at end Adding the node into the linked list to the end.
3 Insertion after specified Adding the node into the linked list after the specified node.
node
5 Deletion at the end Removing the node from end of the list.
6 Deletion of the node Removing the node which is present just after the node containing the given
having given data data.
7 Searching Comparing each node data with the item to be searched and return the
location of the item in the list if the item found else return null.
8 Traversing Visiting each node of the list at least once in order to perform some specific
operation like searching, sorting, display, etc.
Menu Driven Program in C to implement all the operations of doubly linked list
1. #include<stdio.h>
2. #include<stdlib.h>
3. struct node
4. {
5. struct node *prev;
6. struct node *next;
7. int data;
8. };
9. struct node *head;
10. void insertion_beginning();
11. void insertion_last();
12. void insertion_specified();
13. void deletion_beginning();
14. void deletion_last();
15. void deletion_specified();
16. void display();
17. void search();
18. void main ()
19. {
20. int choice =0;
21. while(choice != 9)
22. {
23. printf("\n*********Main Menu*********\n");
24. printf("\nChoose one option from the following list ...\n");
25. printf("\n===============================================\n");
26. printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4
.Delete from Beginning\n
27. 5.Delete from last\n6.Delete the node after the given data\n7.Search\n8.Show\n9.E
xit\n");
28. printf("\nEnter your choice?\n");
29. scanf("\n%d",&choice);
30. switch(choice)
31. {
32. case 1:
33. insertion_beginning();
34. break;
35. case 2:
36. insertion_last();
37. break;
38. case 3:
39. insertion_specified();
40. break;
41. case 4:
42. deletion_beginning();
43. break;
44. case 5:
45. deletion_last();
46. break;
47. case 6:
48. deletion_specified();
49. break;
50. case 7:
51. search();
52. break;
53. case 8:
54. display();
55. break;
56. case 9:
57. exit(0);
58. break;
59. default:
60. printf("Please enter valid choice..");
61. }
62. }
63. }
64. void insertion_beginning()
65. {
66. struct node *ptr;
67. int item;
68. ptr = (struct node *)malloc(sizeof(struct node));
69. if(ptr == NULL)
70. {
71. printf("\nOVERFLOW");
72. }
73. else
74. {
75. printf("\nEnter Item value");
76. scanf("%d",&item);
77.
78. if(head==NULL)
79. {
80. ptr->next = NULL;
81. ptr->prev=NULL;
82. ptr->data=item;
83. head=ptr;
84. }
85. else
86. {
87. ptr->data=item;
88. ptr->prev=NULL;
89. ptr->next = head;
90. head->prev=ptr;
91. head=ptr;
92. }
278. if(flag==1)
279. {
280. printf("\nItem not found\n");
281. }
282. }
283.
284. }
.
Que 1.22. What is meant by circular linked list ? Write circular linked list
operations.
Ans:
The circular linked list is a linked list where all nodes are connected to form a circle. In
a circular linked list, the first node and the last node are connected to each other which
forms a circle. There is no NULL at the end.
Circular singly linked list: In a circular Singly linked list, the last node of the list
contains a pointer to the first node of the list. We traverse the circular singly linked
list until we reach the same node where we started. The circular singly linked list
has no beginning or end. No null value is present in the next part of any of the
nodes.
Circular Doubly linked list: Circular Doubly Linked List has properties of both
doubly linked list and circular linked list in which two consecutive elements are
linked or connected by the previous and next pointer and the last node points to
the first node by the next pointer and also the first node points to the last node by
the previous pointer.
Note: We will be using the singly circular linked list to represent the working of the
circular linked list.
Representation of circular linked list:
Circular linked lists are similar to single Linked Lists with the exception of connecting
the last node to the first node.
We can do some operations on the circular linked list similar to the singly linked list
which are:
1. Insertion
2. Deletion
And then,
Time complexity: O(1) to insert a node at the beginning no need to traverse list it
takes constant time
2) Insertion at the end of the list: To insert a node at the end of the list, follow these
steps:
Create a node, say T.
Make T -> next = last -> next;
last -> next = T.
last = T.
Before insertion,
After insertion,
Time Complexity: O(1) to insert a node at the end of the list. No need to traverse the
list as we are utilizing the last pointer, hence it takes constant time.
3) Insertion in between the nodes: To insert a node in between the two nodes,
follow these steps:
Create a node, say T.
Search for the node after which T needs to be inserted, say that node is P.
Make T -> next = P -> next;
P -> next = T.
Suppose 12 needs to be inserted after the node has the value 10,
1) Delete the node only if it is the only node in the circular linked list:
Free the node’s memory
The last value should be NULL A node always points to another node, so NULL
assignment is not necessary.
Any node can be set as the starting point.
Nodes are traversed quickly from the first to the last.
2) Deletion of the last node:
Locate the node before the last node (let it be temp)
Keep the address of the node next to the last node in temp
Delete the last memory
Put temp at the end
3) Delete any node from the circular linked list: We will be given a node and our
task is to delete that node from the circular linked list.
Time Complexity: O(N), Worst case occurs when the element to be deleted is the last
element and we need to move through the whole list.
maintain a pointer to the last inserted node and the front can always be obtained
as next of last.
Circular lists are useful in applications to repeatedly go around the list. For
example, when multiple applications are running on a PC, it is common for the
operating system to put the running applications on a list and then cycle through
them, giving each of them a slice of time to execute, and then making them wait
while the CPU is given to another application. It is convenient for the operating
system to use a circular list so that when it reaches the end of the list it can cycle
around to the front of the list.
Circular Doubly Linked Lists are used for the implementation of advanced data
structures like the Fibonacci Heap.
48. break;
49. case 7:
50. exit(0);
51. break;
52. default:
53. printf("Please enter valid choice..");
54. }
55. }
56. }
57. void beginsert()
58. {
59. struct node *ptr,*temp;
60. int item;
61. ptr = (struct node *)malloc(sizeof(struct node));
62. if(ptr == NULL)
63. {
64. printf("\nOVERFLOW");
65. }
66. else
67. {
68. printf("\nEnter the node data?");
69. scanf("%d",&item);
70. ptr -> data = item;
71. if(head == NULL)
72. {
73. head = ptr;
74. ptr -> next = head;
75. }
76. else
77. {
78. temp = head;
79. while(temp->next != head)
80. temp = temp->next;
81. ptr->next = head;
82. temp -> next = ptr;
83. head = ptr;
84. }
122. }
123.
124. void begin_delete()
125. {
126. struct node *ptr;
127. if(head == NULL)
128. {
129. printf("\nUNDERFLOW");
130. }
131. else if(head->next == head)
132. {
133. head = NULL;
134. free(head);
135. printf("\nnode deleted\n");
136. }
137.
138. else
139. { ptr = head;
140. while(ptr -> next != head)
141. ptr = ptr -> next;
142. ptr->next = head->next;
143. free(head);
144. head = ptr->next;
145. printf("\nnode deleted\n");
146.
147. }
148. }
149. void last_delete()
150. {
151. struct node *ptr, *preptr;
152. if(head==NULL)
153. {
154. printf("\nUNDERFLOW");
155. }
156. else if (head ->next == head)
157. {
158. head = NULL;
159. free(head);
160. printf("\nnode deleted\n");
161.
162. }
163. else
164. {
165. ptr = head;
166. while(ptr ->next != head)
167. {
168. preptr=ptr;
169. ptr = ptr->next;
170. }
171. preptr->next = ptr -> next;
172. free(ptr);
173. printf("\nnode deleted\n");
174.
175. }
176. }
177.
178. void search()
179. {
180. struct node *ptr;
181. int item,i=0,flag=1;
182. ptr = head;
183. if(ptr == NULL)
184. {
185. printf("\nEmpty List\n");
186. }
187. else
188. {
189. printf("\nEnter item which you want to search?\n");
190. scanf("%d",&item);
191. if(head ->data == item)
192. {
193. printf("item found at location %d",i+1);
194. flag=0;
195. }
196. else
197. {
198. while (ptr->next != head)
199. {
200. if(ptr->data == item)
201. {
202. printf("item found at location %d ",i+1);
203. flag=0;
204. break;
205. }
206. else
207. {
208. flag=1;
209. }
210. i++;
211. ptr = ptr -> next;
212. }
213. }
214. if(flag != 0)
215. {
216. printf("Item not found\n");
217. }
218. }
219.
220. }
221.
222. void display()
223. {
224. struct node *ptr;
225. ptr=head;
226. if(head == NULL)
227. {
228. printf("\nnothing to print");
229. }
230. else
231. {
232. printf("\n printing values ... \n");
233.
234. while(ptr -> next != head)
235. {
236.
237. printf("%d\n", ptr -> data);
238. ptr = ptr -> next;
239. }
240. printf("%d\n", ptr -> data);
241. }
242.
243. }
Que 1.23. Write an algorithm to insert a node at the end in a circular linked list.
Ans:
C Function
1. void lastinsert(struct node*ptr, struct node *temp, int item)
2. {
3. ptr = (struct node *)malloc(sizeof(struct node));
4. if(ptr == NULL)
5. {
6. printf("\nOVERFLOW\n");
7. }
8. else
9. {
10. ptr->data = item;
11. if(head == NULL)
12. {
13. head = ptr;
14. ptr -> next = head;
15. }
16. else
17. {
18. temp = head;
Ans:
Ans:
o The first part contains the value of the coefficient of the term.
o The second part contains the value of the exponent.
o The third part, LINK points to the next term (next node).
The structure of a node of a linked list that represents a polynomial is shown below:
Example:
Input:
1st number = 5x2 + 4x1 + 2x0
2nd number = -5x1 - 5x0
Output:
5x2-1x1-3x0
Input:
1st number = 5x3 + 4x2 + 2x0
2nd number = 5x^1 - 5x^0
Output:
5x3 + 4x2 + 5x1 - 3x0
Polynomial Addition
Implementation:
#include <bits/stdc++.h>
// variable
struct Node {
int coeff;
int pow;
};
z = *temp;
if (z == NULL) {
r->coeff = x;
r->pow = y;
*temp = r;
r = r->next;
r->next = NULL;
else {
r->coeff = x;
r->pow = y;
r = r->next;
r->next = NULL;
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;
else {
poly->pow = poly1->pow;
poly1 = poly1->next;
poly2 = poly2->next;
poly->next
poly = poly->next;
poly->next = NULL;
if (poly1->next) {
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;
if (poly2->next) {
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;
poly->next
poly = poly->next;
poly->next = NULL;
node = node->next;
if (node->coeff >= 0) {
if (node->next != NULL)
printf("+");
// Driver code
int main()
create_node(5, 2, &poly1);
create_node(4, 1, &poly1);
create_node(2, 0, &poly1);
create_node(-5, 1, &poly2);
create_node(-5, 0, &poly2);
show(poly1);
show(poly2);
show(poly);
return 0;
Output
1st Number: 5x^2+4x^1+2x^0
2nd Number: -5x^1-5x^0
Added polynomial: 5x^2-1x^1-3x^0
Time Complexity: O(m + n) where m and n are number of nodes in first and second
lists respectively.
Space Complexity: O(m+n), since we create a new linked list of size m + n to store
the result of the addition of the two polynomials.