0% found this document useful (0 votes)
168 views15 pages

Data Structure 5 Mark's

MAC - SEM 1 - KSOU
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)
168 views15 pages

Data Structure 5 Mark's

MAC - SEM 1 - KSOU
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/ 15

Data structure and Algorithms

5 Marks

) Discuss Stacks and Queues.


-A stack is a last-in, first-out (LIFO) data structure, where the last element added is the
first one to be removed. It follows the principle of adding elements to the "top" and
removing them from the same "top" position.
Operations:
Push: Add an element to the top of the stack.
Pop: Remove the element from the top of the stack.
Peck (or Top): View the clement at the top without removing it.
isEmpty: Check if the stack is empty.

Applications:
Function call management (call stack in programming).
Expression evaluation (postfix. prefix, and infix notations).
Undo mechanisms in applications.
Backtracking algorithms.
Implementation:
Can be implemented using arrays or linked lists.

Queues:
Aqueue is a first-in, first-out (FIFO) data structure, where the first element added is the
first one to be removed. It follows the principle of adding elements to the "rear" and
removing them from the "front."
Operations:
Engueue: Add an element to the rear of the queue.
Dequeue: Remove the element from the front of the queue.
Front: View the element at the front without removing it.
isEmpty: Check if the queue is empty.
Applications:
Task scheduling in operating systems.
Print job management.
Breadth-tirst search in graph algorithms,
Handling requests in netvworking.

Implementation:
Can be implemented using arrays. linked lists. or specialized data structures like a
circular queue.
Differences:
Order of Removal
Stack: Last In, First Out (LIFO).
Queue: First In, First Out (FIFO).
Operations:
Stack: Push, Pop. Peek.
Queue: Enqueue, Dequeue, Front.
Implementation:
Stacks can be casily implemented using arrays or linked lists.
Queues can be implemented using arravs, linked lists, or circular buffers.
Applications:
Stacks are used in sccenarios where the last operation nceds to be undone or revisited.
Qucues arc used when tasks are processed in the order they arive.

Both stacks and queues are fundamental data structures, and their simplicity makes thenm
Iseful in various applications. Choosing between them depends on the specific
requirements of a problem.

2) Define tree and binary tree.


*A tree is detined as a finite sct of one or more nodes such that
(i) there is a specially designated node called the root and
(i) the rest of thenodes could be partitioned in to t disjoint sets (120) cach set
representing a tree Ti, i= 1,2. 3, ... t known as subtree ofthe tree.
Anode in the definition of the tree represents an item of information and the links
between the nodes termed as branches, represent an association between the items of
information. Figure 5.2,1 shows a tree.
Rool Node Levd0

Intemediute node
Level l
3

Intemedinte node
Leved 2

Leaf Node
Level 3
10 11 12) ---+

Figure 5.2.1 An example tree


In the above figure. node I represents the root of the tree, nodes 2, 3, 4 and 9 are all
intermediate nodes and nodes 5, 6. 7, 8, 10, |1 and 12 are the leaf nodes of the trec.
The definition ofthe tree emphasizes on the aspect of (i) connectedness and (iü)
absence of loops or cycles. Beginning tYrom the root node. the structure of the tree
permits connectivity of theroot to every other node in the tree. In general, any node is
reachable from any where in the tree. Also, with branches providing links between the
nodes, the structure cnsures that no set of nodes link together to form a closed loop or
Cce.
Some Perties of lee
1 There is one al onlk ote Dath Ieween Cvery pait o setices in a tree, I
A tre with n vertices has 1-l edges
1 Ans connccted eraph sitlh n veitices and n- l cdges is a tree
4.A grph is a tree if and only if it is nmininmally conaected.
Theretor, a graplh with n xetices is called a tree ir
1.Gis connected and is cinvuit less, o
2.Gisconnected and has n-l cdges, o
3.Gis circuit less and has -lcdges, 0r
4. There Is Cxacly One path betw cen every pair of vertices in G, o
$.Gisaminimally connected grap.
There are several basic terminologies associated with trees. 1here is a specially
designated node called the root node. The nunber of subtrees of a node is known as
the degree of the node. Nodes that have zero degree are called leal nodes or terminal
nodes. The rest of them are called internediate nodes, The nodes, which hang lrom
branches emanating trom a node,are called as children and the node trom which the
branches emanate is known as the parent node. Children of the sanne parent node
are
reterred to as siblings, The ancestors of agiven node are those nodes that occur on the
path from the root to the given node. The degree of' a tree is the masimum degrec of
the node in the tree. The level of the node is detincd by letting the root node to
occupy
level 0. The rest of the nodes occupy various levels depending on their association.
Thus, if parent node occupies level i then, its children should occupy level it1. This
renders a tree to have a hierarchical structure vith root
oceupying the top most
level of 0. The height or depth ofa tree is detined to be the masimum level of any
node in the tree. A forest is a set of zero or more disioint trees, The removal of the
root node from a tree result in a forest

*A binary tree has the characteristic of all nodes having at most two branclhes, that is,
all nodes have a degree of at most 2. Therefore, a binary tree can be enmpty or consist
of a root node and two disjointed binary trees termed left subtree and right subtree.
Figure 5,4 shows an example binarv tree.

level 0
root node

level terme diate node


G level2leaf node
igure 5.4 An example binary tree
The number of levels in the tree is called the depth" of the tree. A "complete" binary
tree is one which allows sequencing of the nodes and all the previous levels are
maximally accommodated before the next level is accommodated. ie. the siblings are
first accommodated belore the children of any one of them. And abinary tree, which
is masimally accommodated with all leaves at the same level is called "full'" binary
tree. Afull binary tree is always complete but acomplete binary trec necd not be full
Fig 5.4 is an cxample for afull binary tree and Figure 5.4.1 illustrates acomplete
binary tree

Figure 5.4.1 Acomplete binary tree


The maNimum number of vertices at cach level in a binary trec can be found out as
follows:
At level 0: 20 number of vertices
At level 1:21 number of vertices
At level 2: 22 number of vertices
At level i 2i number of vertices
Therefore, maximum number of vertices in a binary tree of depth T is:
20+ 21 +22+...+21
ie.. S2k =2 +|-1 for k =0 to I
Binary Tree can be represented using sequential as well as linked data structures. In
scquential data structures, we have two wavs of representing the binarv tree. One is
through the use of Adjacency matrices and the other is through the use of Single
dimensional array representation.

3) Define graph and directed graph.


Graph Data Structure is a collection of nodes connected by edges. It's used to represent
relationships between different entities. Graph algorithms are methods used to
manipulate and analyze graphs, solving various problems like finding the shortest
path or detecting cycles.

Components of a Graph:
Vertices
Edges

Basic Operations on Graphs:


Relow are the basic operations on the graph:
Insertion of Nodes/Edges in the graph
Deletion of Nodes/Edges in the graph
Searching on Graphs
Traversal of Graphs

Applications of Graph:
Following are the real-life applications
*Graph data structures can be used to represent the interactions between players on a
team, such as passes, shots, and tackles. Analyzing these interactions can provide insights
into team dynamics and areas for
improvement
"Commonly used to represent social networks, such as networks of friends on social media
Graphs can be used to represent the topology of computer networks, such as the
connections between routers and switches.
*Graphs are used to represent the connections between different places in a transportation
network, such as roads and airports
*Graphs are used in Neural Networks where vertices represent neurons and edges represent
the synapses between them, Neural networks are used to understand how our brain works
and how cOnnections change when we learn. The human brain has about 10^11 neurons
and close to 10^15 synapses.

A directed graph is defined as a type of graph where the edges have a direction associated
with them.

Example of Directed Graph


Characteristics of Directed Graph
Directed graphs have several characteristics that make them different from undirected
graphs. Here are some key characteristics of directed graphs:
Directed edges:
Indegree and Outdegree:
Cycles
Paths and reachability:

Applications of Directed Graph


Directed graphs have many applications across a wIde range of fields. Here are some
examples:
Social networks:
Transportation networks
Computer networks:
Project management
Advantages of Directed Graph
Can model complex relationships
Can be Used for analysis
Can represent dependencies

Disadvantages of Directed Graph


May be more complex:
May require more processing power
Maybe less intuitive

4) Mention the applications of searching algorithms?


Applications of Searehing
Searching algorithms have numerous applications across various fields. Here are
some common applications:

Information Retrieval: Search engines like Google, Bing, and Yahoo use
sophisticated searching algorithms to retrieve relevant information from vast amounts
of data on the web.
Database Svstems: Searching is fundamental in database sYstems for retrieving
specific data records based on user queries, improving efficiency in data retrieval.
E-commere: Searching is crucial in ecommerce platforms for users to find products
quickly based on their preterences, specitications, or keywords.
Networking: In networking., searching algorith1s are used for routing packets
efticiently through networks. finding optimal paths, and managing network resources.
Artificial Intelligenee: Searching algorithms play a vital role in Al applications, such
as problem-solving. game playing (e.g. chess), and decision-making processes
Pattern Recognition: Searching algorithms are used in pattern matching tasks, such
as image recognition. speech recognition, and handwriting recognition.

5) Define hashing

Hashing refers to the process of generating a tixed-size output fiom an input of


variable size using the mathematical formulas known as hash functions. This
technique determines an index or kocation for the storage of an item in a data
structure.

Hashing is an important data structure designed to solve the problem of etticicnthy


finding and storing data in an array

There are majorly three components of hashing:


1. Key
2. Hash Function
3. Hash Table

Hashing in the data structure is a technique of mapping a large chunk of data into
small tables using a hashing function. It is also known as thec message digest function,
It is a technique that uniquely identifies aspecific item from a collection of similar
items.

Types of hashing in data structure is a tvwo-step prOcess.


I. The hash function converts the item into a small integer or hash value. This integer
is used as an index to store the original data.
2. It stores the data in a hash table. You can use a hash key to locate data quickly

Examples of Hashing in Data Structure


The follow ing are real-life examples of hashing in the data structure -
In schools, the teacher assigns a unique roll number to cach student. Later, the
teacher uses that roll number to retrieve information about that student.
Alibrary has an infinite number of books. The librarian assigns aunique number to
cach book. This unique number helps in identify ing the position of the books on the
booksheltf.

6) Explain bellman ford's algorithm.


Bellman Ford's algorithm is used to find the shortest paths from the source vertex to al
other vertices in a weighted graph. It depends on the following concept: shortest path
contains at most n-l edges. because the shortest path couldn't have a cycle
So why shortest path shouldn't have a cycle There is no need to pass a vertex again, because
the shortest path to all other vertices could be found without the need for a second visit for
any vertices.
Algorithm Steps:
DThe outer loop traverses from 0: n-1
DLoop over all edges, check if the next node distance > current node distance +edge weight,
in this case update the next node distance to "current node distance +edge weight".
This algorithm depends on the relaxation principle where the shortest distance for all
vertices is gradually replaced by more accurate values until eventually reaching the optimum
solution. In the beginnig all vertices have a distance of "Infinity", but only the d1stance of
the source vertex =0, then update all the connected vertices with the new distances (source
vertex distance +edge weights), then apply the same concept for the new vertices with new
distances and so on.
Implementation:
Assume the source node has a number (0):
vector <int> v (2000+ 101:
int dis [1000 + 10):

forint i=0; i<m + 2; i++)

vli].clear():
dislo) =2e9;
for(int i 0; < m, i++)

scanf("%d%d%d", &from, &next, &weight).


vl] push back(from),
vlil push_back(next).
vlil, push_back(weight).

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

int j =0,
while(vu].size() != 0)

if(disl vbl[0|] +vý|[2) <disl výll1|) )

disl vyl[1] 1 =disl vll[o) ]+vill2):

++:

A very important application of Bellman Ford is to check if there is a negative cycie in the
graph, Time Complexity of Bellman Ford algorithm is relatively high O(VE), in case

Let's discuss an optimized algorithm.

7) Define liner probing

Hashing in data structure results in an array index that is already occupied to store a
value. In such a case. hashing pertorms a scarch operation and probes linearly for the
next empty cell.
Lincar probing in hash techniques is known to be the easiest way to resolve any
collisions in hash tables. Asequential search can be performed to find any collision
that occurred.
Linear Probing Example
Imagine you have been asked to store some items inside a hash table of size 30, The
items are already sorted in a key-value pair format. The values given are: (3,21)0.72)
(63,36) (5,30) (11,44) (15,33) (18.12) (16.80) (46.99).
The hash(n) is the index computed using a hash function and T is the table size. If slot
index = (hash(n) %T) is full. then we look for the next slot index by adding 1
((hash(n) + ) %T). If (hashin) + |) %T is also full. then we try (hash(n) -2) %T. If
(hashín) +2) %T is also full. then we try (hashin) +3) %T.
The hash table will look like the following:
The idea of lincar probing is sinmple, we take a fixed sized hash table and every time
we face a hash collision, we lincarly traverse the table in a cyclic manner to find the
next empty slot.
Assume a scenario where we intend to store the following set of numbers
0.1,2.4.5,7) into a hash table of size 5 with the heip of the following hash function
H. such that H(x) = N%5.
So, if we were to map the given data vith the given hash function we'll get the
corresponding values
H(01-> 0%5 =0
H(l)-> 1%5 = 1
H(2)-> 2°%5 =2
H(4)-> 4%5 = 4
H(S)-> 59%5 = 0
in this case we see a collision of two terms (0 & Z). In this situation we move
linearly down the table to find the first empty slot. Note that this linear traversal is
cyelic in nature, i.e. in the event we exhaust the last element during the search we start
again from the beginning until the initial kev is reached.

In this case our hash function can be considered as this: H(x. i) =(H() +iloN
where Nis the size of the table and irepresents the linearly increasing variable which
starts from l(until empty bucket is found).

Despite being easy to compute, implement and deliver best cache pertormance, this
suflers from the problem of clustering (many consecutive clements get grouped
together. which eventually reduces the efficiency of finding clements or empty
buckets).
8) Explain types of heaps in data structure
we have some general understanding of heap data structure, therc are two types of
heap which can be classified as:.
1. Min Heap :- The smallest element is present at the root of the trece in the nin heap
such that it is casier to extract the smallest clement when heap pop is performed.
2. Max Heap :- The greatest element is present at the root of the tree in the max heap
such that it is casier to extract the largest element when heap pop is
pertormed.
The illustration stating the both is represented below:

Min Heap Max Heap

9) Differentiate complete and full binary trees


Full Binary Tree:
Afull binary tree is a binary tree in which all of the nodes have either 0 or 2 offspring. In
other terms, a fuil binary tree is a binary tree in which all nodes, except the leaf nodes, have
two offspring.

Let, i be the number of internal nodes


n be the total number of nodes
I be number of leaves
Abe number of levels

Then,

The number of leaves is (i + 1)


The total number of nodes is (2i+ 1).
The number of internal nodes is (n - 1)/2.
The number of leaves is (n + 1)/2.
The total number of nodes is (21-1).
The number of internal nodes is (|- 1),
The number of leaves is at most (2 - 1).
Complete Binary Tree:

Abinary tree is said to be a complete binary tree if all its levels, except possitbly the last level,
have the maximum number of possible nodes, and all the nodes in the last level appear as
far left as possible

There are 2 points that you can recognize from here,


1. The leftmost side of the leaf node must always be filed first.
2. It isn't necessory for the last leaf node to have o right sibling.
Full Binary tree Complete Binary tree
In a full binary tree every node has
In a complete binary tree, all levels are
either 0 or 2 child nodes. completely filled except possibly the last
level.

There is no particular sequence tor All nodes should be on the left. This
filling in nodes. means that there is no node that
has a right child but not a left child.

There is no necessity for all leaf


nodes to be at the same level. All leaf nodes must be at the same
level.

10) Explain hash function.


The hash function in a data structure maps the arbitrary size of data to fived-sized
data. It returns the following values: a small integer value (also known as hash value).
hash codes, and hash sums. The hashing techniques in the data structure are very
interesting, such as:
hash =hashfunc(key
index = hash % array size

The hash function must satisfy the following requirements:


Agood hash function is easy to compute.
Agood hash function never gets stuck in clustering and distributes keys evenly
across the hash table.
A good hash function avoids collision when two elenments or items get assigned to
the same hash value.

One of the hashing techniques of using a hash function is uscd for data integrity. If
using a hash function one change in a message will create a different hash.
The three characteristics of the hash function in the data structure are:
LCollision free
2. Property to be hidden
3. Puzzle friendly

TD Discuss Dijkstra's algorithm


Dijkstra's algorithm has nany variants but thc most common onc is to find the
shortest paths from the source vertex to all other vertices in the graph.

Algorithm Steps:
Set all vertices distances infinity except for the source vertex, set the source
distance0.
Push the source vertex in a min-priority queue in the form (distance, vertex), as the
comparison in the min-priority queue will be according to vertices distances
Pop the vertex with the minimum distance from the priority queue (at first the
popped vertex =source).
Update the distances of the connected vertices to the popped vertex in case of
"current vertex distance +edge weight < next vertex distance", then push the vertex
with the new distance to the priority queue.
If thepopped vertex is visited before, just continue without using it.
Apply the same algorithm again until the priority queue is empty.

Implementation:
Assume the source vertex =I

#detine SIZE 100000 + 1

Vector <pair < int , int>>v(SIZE): /each vertex has all the connected vertices
with the edges weights

int dist [SIZEJ:


bool vis (SIZEJ:

void dijkstra)1
/set the vertices distances as infinity
memset(vis, false, sizeof vis): set all vertes as unvisited
dist[ 1] =0:
multiset< pair < int. int > >s: multiset do the job as a min-priority queue

s.insert( (0. 1}): insert the source node with distance = 0

while(!s.empty0)
pair <int , int> p="s.begin): //pop the vertex with the minimum distance
S.erase(s.begin).

int x p.s: int wei =p.f.


if( vislx] )continue: lcheck if the popped vertex is visited before
vislx] =true:

for(int i =0: i<v[x],size(): it+)

int e =v]|i].f. int w = v|[il.s:


ifldist[x] + w< dist[e| ){ check if the next vertex distance could be minimized

dist[el =dist[x] + w:
s.insert((dist(e]. e} ): insert the next vertex with the updated distance

Time Complexity of Dijkstra's Algorithm is but with min-priority queue it drops down to
D(V+ Elog V)

12)What are singly linked lists?


Asingly linked list is a data structure in which each element (node) contains a data part and a link
to the next node in the sequence.
Asingly lnked list is a fundamental data structure consisting of a sequence of elements called
nodes.

Each node contains two parts:


1. Data Part: This part stores the actual data or payload associated with the node. It could be of any
data type depending on the application.
2. Link (or Pointer) Part: This part contains a reference (or pointer) to the next node in the sequence.
It establishes the logical connection between nodes and allows traversal through the list.

Here's a simple visual representation of a singly linked list:

| Node | -> Node 2 -> Node 3 ->>Node 4| -> NULL

this example:
Each rectangular box represents a node.
The arrow symbol(->) represents the link from one node to the next.

The last node points to NULL, indicating the end of the list.
Key characteristics of singly linked lists include
Dynamic Size
Sequential Access

Efficient Insertion and Deletion

No Random Access

Singly linked lists are widely used in various applications, such as

*Implementing other data structures like stacks, queues, and trees


Managing memory dynamically, especially in situations where the size of data is not known
beforehand

Representing sequences of data that can be easily modified without the need for
shifting elements (unlike arrays).
* Performing operations like insertion and deletion efficiently, particularly when
dealing with large datasets

12)What is a header?
Aheader node is a special node that is found at the beginning of the list. Alist that contains
this type of node, is called the header-linked list. This type of list is useful when information
other than that found in each node is needed.
For example, suppose there is an application in which the number of items in a list is often
calculated. Usually, a list is always traversed to find the length of the list. However, if the
Current length is maintained in an additional header node that information can be easily
obtained.

Types of Header Linked List

1.Grounded Header Linked List


It is a list whose last node contains the NULL pointer. In the header inked list the start
pointer always points to the header node. start -> next = NULL indicates that the grounded
header linked list is empty. The operations that are possible on this type of linked list are
Insertion, Deletion, and Traversing.
2 Circula Header Linked List
A list in
which last node points linked list The
poinor last
backnodes
to theInheader is called circular
nodeexternal
chains do not indicate first this ecase, pointers provide afrane of

reference because last node of fa circular linked list does not contain the NULL pointer. The
possible operations on this type of linked ist are Insertion, Deletion and Traversing.

You might also like