DS Training in Python
DS Training in Python
NOIDA
DATA STRUCTURES
Megha Gupta
Assistant Professor 1
Computer Science and Engineering
NIET, Gr. Noida
▪ Data types: Primitive and non-primitive, Types of Data Structures- Linear & Non-Linear Data
Structures. Arrays: Definition, Single and Multidimensional Arrays, Representation of Arrays: Row
Major Order, and Column Major Order, Derivation of Index Formulae for 1-D,2-D,3-D and n-D
Stacks: Primitive Stack operations: Push & Pop, Array and Linked Implementation of Stack,
Application of stack
Queues: Array and linked implementation of queues, Operations on Queue: Create, Insert, Delete,
Module-3
Advantages of linked list over array, Self-referential structure, Singly Linked List, Doubly
Linked List, Circular Linked List. Operations on a Linked List: Insertion, Deletion, Traversal,
Reversal, Searching.
Basic terminology used with Tree, Binary Trees, Binary Tree Representation: Array
Representation and Pointer (Linked List) Representation, Binary Search Tree, Strictly Binary
Tree, Complete Binary Tree, An Extended Binary Trees. Tree Traversal algorithms: In-order,
Pre-order and Post-order. Constructing Binary Tree from given Tree Traversal, Operation of
Insertion, Deletion, Searching & Modification of data in Binary Search tree, Threaded Binary
Graphs: Terminology used with Graph, Data Structure for Graph Representations: Adjacency
matrices, Adjacency List. Graph Traversal: Depth First Search and Breadth First Search.
Connected Component, Spanning Trees, Minimum Cost Spanning Trees: Prim’ s and Kruskal’s
▪ Data Structure ..
▪ These data structures are specific to python language and they give greater
flexibility in storing different types of data and faster processing in python
environment.
▪ List − It is similar to array with the exception that the data elements can be of
different data types.You can have both numeric and string data in a python list.
▪ Tuple − Tuples are similar to lists but they are immutable which means the
values in a tuple cannot be modified they can only be read.
▪ Sets - Sets are again a collection of elements. But the difference from the above
two is that sets do not hold duplicate values and the elements are not ordered.
1. Accounting: Arrays can be used to store financial data, such as a company's revenue and
expenses for each month of the year.
2. Scheduling: Arrays can be used to schedule tasks or appointments. For example, a doctor's
office might use an array to schedule appointments for each day of the week.
3. Weather data: Arrays can be used to store and analyze weather data, such as the
temperature, humidity, and wind speed for each hour of the day.
4. Survey data: Arrays can be used to store and analyze survey data, such as the responses to
each question for each participant.
5. Gaming: Arrays are often used in video game development to store and manipulate game
data, such as player health, inventory items, and enemy positions.
6. Image processing: Arrays can be used to store and manipulate image data, such as the color
values for each pixel in a photograph.
▪ Stack
Stack is a linear data structure in which
the insertion and deletion operations
are performed at only one end. In a
stack, adding and removing of elements
are performed at a single position
which is known as "top". That means, a
new element is added at top of the
stack and an element is removed from
the top of the stack. In stack, the
insertion and deletion operations are
performed based on LIFO(Last In First
Out) principle.
▪ LINKED LIST
When we want to work with an unknown number of data
values, we use a linked list data structure to organize that
data.
The linked list is a linear data structure that contains a
sequence of elements such that each element links to its
next element in the sequence. Each element in a linked list
is called "Node".
▪ Tree is a non-linear
data structure which
organizes data in
hierarchical structure.
▪ Generally, a graph G is
represented as G = ( V , E ),
where V is set of vertices and E is
set of edges.
▪ Given the base address of an array B[1300…..1900] as 1020 and size of each
element is 2 bytes in the memory. Find the address of B[1700].
▪ Solution:
Create an array:
An array can be created by using list declaration syntax. We can provide
the list of items inside the square brackets by separating them with
commas.
Countries=[“India", “USA", “Pakistan"]
Marks = [50,92,89,75]
Weights = [25.6,57.8,96.3,102.3]
Array Length:
The len() function can be used to get array length. The array is provided to
the len() function as a parameter.
Marks = [50,92,89,75]
print("Array length is ",len(Marks))
Marks = [50,92,89,75]
for i in Marks:
print(i)
Python Sorting:
cars.sort()
cars.sort(reverse=True)
# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr, n)
print("Largest in given array ", Ans)
Megha Gupta Data Structure
4/24/2023 38
Introduction to Array(CO1)
▪ def remove_duplicates(arr):
arr_set = set(arr)
return list(arr_set)
▪ arr = [1, 2, 3, 2, 4, 5, 1, 6, 7, 5]
▪ arr = remove_duplicates(arr)
▪ print(arr)
▪ # Output: [1, 2, 3, 4, 5, 6, 7]
1. 2. 3. 4.
arr = [1, 2, 3, 4, 5] arr1 = [1, 2, 3] arr1 = [1, 2, 3]
arr = [1, 2, 3] arr2 = arr1.copy()
arr.extend([4, 5]) arr2 = [4, 5, 6]
print(arr[2:4]) arr2[1] = [4, 5]
print(arr) arr1 += arr2
print(arr1) print(arr1)
a) [1, 2, 3, [4, 5]]
a) [1, 2] a) [1, 2, 3, [4, 5, 6]] a) [1, 2, 3]
b) [1, 2, 3, 4, 5]
b) [2, 3] b) [1, 2, 3, 4, 5, 6] b) [1, [4, 5], 3]
c) [3, 4] c) [1, 2, 3, (4, 5)] c) [1, 2, 3, (4, 5, 6)] c) [1, 4, 5, 3]
d) [1, 2, 3, '4', '5'] d) [1, 2, 3, '4', '5', '6'] d) Error
d) [3, 4, 5]
Answer:
Answer: c) [3, 4] Answer: b) [1, 2, 3, 4, 5] Answer: a) [1, 2, 3]
b) [1, 2, 3, 4, 5, 6]
Linear Search
> Check each element of an array.
> If the match found – element exists, else does not exist.
> Suitable for small lists since time consuming
> Suitable for unsorted Lists.
Binary Search:
> Most Important preconditions is that the list should be
sorted.
> Suitable for arrays with long list of elements
Advantages
▪ The linear search is simple - It is very easy to understand and
implement.
▪ It does not require the data in the array to be stored in any
particular order.
Disadvantages
▪ It has very poor efficiency because it takes lots of comparisons to
find a particular record in big files.
▪ The performance of the algorithm scales linearly with the size of
the input .
▪ Linear search is slower then other searching algorithms.
Step 1: First, read the search element (Target element) in the array.
Step 2: In the second step compare the search element with the first element in
the array.
Step 3: If both are matched, display "Target element is found" and terminate the
Linear Search function.
Step 4: If both are not matched, compare the search element with the next
element in the array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target) element is
compared with the last element of the array.
Step 6 - If the last element in the list does not match, the Linear Search Function
will be terminated, and the message "Element is not found" will be displayed.
Megha Gupta Data Structure
4/24/2023 54
Introduction to Array (CO1)
Step 4: Set i to i + 1
Step 8: Exit
Megha Gupta Data Structure
4/24/2023 55
Introduction to Array (CO1)
▪ In the best case, the target value is in the first element of the array.
So the search takes some tiny, and constant, amount of time.
▪ In the worst case, the target value is in the last element of the array.
The general term for a smart search through sorted data is a binary
search.
1. The initial search region is the whole array.
2. Look at the data value in the middle of the search region.
3. If you’ve found your target, stop.
4. If your target is less than the middle data value, the new search
region is the lower half of the data.
5. If your target is greater than the middle data value, the new
search region is the higher half of the data.
6. Continue from Step 2.
Megha Gupta Data Structure
4/24/2023 59
Introduction to Array (CO1)
Where,
B = Base address
I1 = Row subscript of element whose address is to be found
I2 = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
L1 = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
L2 = Lower limit of column/start column index of matrix, if not given assume 0
(zero)
N1 = Number of row of the given matrix
N2 = Number of column of the given matrix
Megha Gupta Data Structure
4/24/2023 70
Introduction to Array(CO1)
# Adding a sublist
2. extend(): Add the elements of a list (or any iterable), to the end of the current
list.
# Reversing a sublist
▪ Answer: b
▪ Answer: d
▪ Answer a.
▪ Ans C.
L= [4,21,13,14,52]
for i in L:
if(i%2==0):
print(i)
O/p: 4,14,52
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)
Insertion Sort
Algorithm
1. Set a marker for the sorted section, after the first
element.
Megha Gupta
c)ACSE0301
Advance the DS
marker
Unit 1
to the right one element.
Sorting Using Array CO1)
Selection sort
The selection sort algorithm sorts an array by repeatedly
finding the minimum element (considering ascending
order) from unsorted part and putting it at the beginning.
Selection sort
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
▪ Divide the unsorted list into n sub-lists, each containing one element (a list of one
element is considered sorted).
▪ Repeatedly merge sub-lists to produce new sorted sub-lists until there is only one
sub-list remaining. This will be the sorted list.
▪ The key step in the merge sort algorithm is the merge operation, which takes two sorted sub-
lists and merges them into a single sorted list. This is done by repeatedly comparing the first
elements of each sub-list and selecting the smaller one to be added to the output list, until
one sub-list is completely merged. Then, the remaining elements in the other sub-list are
added to the output list.
▪ Overall, merge sort has a time complexity of O(n log n), which makes it efficient for sorting
large arrays or lists.
def merge(arr, l, m, r): # Merge the temp arrays back into # Copy the remaining elements of
n1 = m - l + 1 arr[l..r] L[], if there
i = 0 # Initial index of first # are any
n2 = r - m subarray while i < n1:
# create temp arrays j = 0 # Initial index of second arr[k] = L[i]
subarray i += 1
L = [0] * (n1) k = l # Initial index of merged k += 1
R = [0] * (n2) subarray
# Copy the remaining elements
# Copy data to temp arrays while i < n1 and j < n2: of R[], if there
L[] and R[]
if L[i] <= R[j]: # are any
for i in range(0, n1): arr[k] = L[i] while j < n2:
i += 1 arr[k] = R[j]
L[i] = arr[l + i]
else: j += 1
for j in range(0, n2): arr[k] = R[j] k += 1
R[j] = arr[m + 1 + j] j += 1
k += 1
Space
Algorithm Best Case Average Case Worst Case Complexity
Bubble Sort O(n^2) O(n^2) O(n^2) O(1)
Insertion Sort O(n) O(n^2) O(n^2) O(1)
Selection Sort O(n^2) O(n^2) O(n^2) O(1)
Merge Sort O(n log n) O(n log n) O(n log n) O(n)
Quick Sort O(n log n) O(n log n) O(n^2) O(1)
Heap Sort O(n log n) O(n log n) O(n log n) O(1)
1. What is the time complexity of bubble sort, and how does it compare to other sorting algorithms?
2. Can you explain how quicksort works, and what its worst-case time complexity is?
3. What is a stable sorting algorithm, and why might it be important in certain applications?
4. Can you describe the differences between merge sort and quicksort, and explain when you might choose one over
the other?
5. How does the insertion sort algorithm work, and what is its time complexity in best, average, and worst cases?
6. Can you explain the differences between in-place and not-in-place sorting algorithms, and give examples of each?
7. What is the heap sort algorithm, and how does it use a binary heap data structure to sort an array?
8. Can you describe a situation where you might choose a quadratic-time sorting algorithm over a faster algorithm
like merge sort or quicksort?
9. How can you modify a sorting algorithm like merge sort to sort data that is too large to fit into memory?
10.Which sorting algorithm works well to sort the array with duplicate numbers?
Top: Open end of the stack is called Top, From this end item can
be inserted.
POP: To put-off, get or remove some item from top of the stack is
the pop operation, We can POP only only from top of the stack.
ADT Stack {
Data/Attributes/Values:
int size; Top
Type items;
Functions/Operations:
CreateStack (int size); --create stack of size
Void Push(int n); - - if stack is not full
Type Pop(); - - if stack is not empty return top item Int
isEmpty(); - - return true if empty otherwise false Int
isFull(); - - return true if full otherwise false }
Megha Gupta Data Structure 4/24/2023 103
Introduction to Stack
• Using Array
print('Initial stack')
print(stack)
Answer. a
Answer : c
Answer c.
What is an Expression?
In any programming language, if we want to perform any calculation or to frame a condition etc.,
we use a set of symbols to perform the task. These set of symbols makes an expression.
An expression can be defined as follows...
In above definition, operator is a symbol which performs a particular task like arithmetic
operation or logical operation or conditional operation etc.,
Operands are the values on which the operators can perform the task. Here operand can be a direct
value or variable or address of memory location
+AB
Postfix Expression: An expression in which
operator follows its two operands is called a postfix expression.
AB+
Megha Gupta ACSE0301: DS Unit 2 4/24/2023 118
Introduction to Stack
a. 2*3/(2-1)+5*(4-1)
b. (2*3)/(2-1)+5*(4-1)
c. ((2*3)/(2-1))+(5*(4-1))
d. ((2*3)/(2-1))+(5*(4-1))
e. ((2*3)/(2-1))+(5*(4-1))
f. (((2*3)/(2-1))+(5*(4-1)))
Ans. 23*21-/541-*+
H.W
1. A+B*C-D^E^F
*AB+C/D A*(B+/CD)
*AB+/CD A*(+B/CD)
Exercise:
1. Infix ( (A * B) + (C / D) ) to Prefix
2.Infix ((A * (B + C) ) / D) to Prefix
3.Infix (A * (B + (C / D) ) ) to Prefix
Megha Gupta ACSE0301:
4/24/2023
DS Unit 2
125
Introduction to Stack
Step 1: Reverse the infix expression i.e A+B*C will become C*B+A.
Note while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘.
-+/abc+d*ef
Megha Gupta ACSE0301: DS Unit 2 4/24/2023 133
Introduction to Stack
Infix – A*(B+D)/E-F*(G+H/K) --- > )K/H+G(*F-E/)D+B(*A
PostFix Expression 2 3 4 + * 5 *
Move Token Stack
1 2 2
2 3 23
3 4 234
4 + 2 7 (3+4=7)
5 * 14 (2*7=14)
6 5 14 5
7 * 70 (14*5=70)
RECURSIONS
Fun1() Fun2()
{ {
Fun2() Fun1()
} }
Fun() Fun()
{ {
Fun(); …….
……. ……
…… …….
……. Fun();
Head &Tail Recursion()
}
}
Fun()
{
Fun()
...….
……
…….
Fun();
}
Megha Gupta ACSE0301: DS Unit 2 4/24/2023
Introduction to Stack
def recur_factorial(n):
if n == 1:
return n Factorial(5)=
else:
return n*recur_factorial(n-1) 5*Factorial(4)=
num = int(input("Enter the number: ")) 5*(4*Factorial(3))=
5*(4*(3*Factorial(2)=
# check if the number is negative 5*(4*(3*(2*Factorial(1))))=
if num < 0: 5*(4*(3*(2*(1*Factorial(0)))))=
print("Sorry, factorial does not exist for 5*(4*(3*(2*(1*1))))=
negative numbers") 5*(4*(3*(2*1)))=
elif num == 0:
print("The factorial of 0 is 1") 5*(4*(3*2))= 5*(4*6)= 5*24=
else:
print("The factorial of", num, "is", 120
recur_factorial(num))
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
• Pros
• The code may be much easier to write.
• To solve some problems which are naturally recursive
such as tower of Hanoi.
• Cons
• Recursive functions are generally slower than non-
recursive functions.
• May require a lot of memory to hold intermediate
results on the system stack.
• It is difficult to think recursively so one must be very
careful when writing
recursive functions.
Megha Gupta ACSE0301: DS Unit 2 4/24/2023
Recursion
my_result = binary_search(my_list,0,len(my_list)-
1,elem_to_search)
if my_result != -1:
print("Element found at index ", str(my_result))
else:
print("Element not found!")
Megha Gupta ACSE0301: DS Unit 2
4/24/2023 150
Introduction to Stack
The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:
2) Each move consists of taking the upper disk from one of the stacks
and placing it on top of another stack i.e. a disk can only be moved if
it is the uppermost disk on a stack.
# Driver code
n=3
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods
BASIS FOR
RECURSION ITERATION
COMPARISON
Basic The statement in a body of Allows the set of
function calls the function instructions to be
itself. repeatedly executed.
Format In recursive function, only Iteration includes
termination condition initialization, condition,
(base case) is specified. execution of statement
within loop and update
(increments and
decrements) the control
variable.
Termination A conditional statement is The iteration statement is
included in the body of the repeatedly executed until
function to force the a certain condition is
function to return without reached.
4/24/2023 159
recursion
Megha Gupta call being DS Unit 2
ACSE0301:
Recursion
▪ Difference Between Recursion and Iteration
BASIS FOR
RECURSION ITERATION
COMPARISON
Condition If the function does not If the control condition in
converge to some condition the iteration statement
called (base case), it leads never become false, it
to infinite recursion. leads to infinite iteration.
Infinite Repetition Infinite recursion can crash Infinite loop uses CPU
the system. cycles repeatedly.
Applied Recursion is always applied Iteration is applied to
to functions. iteration statements or
"loops".
Stack The stack is used to store Does not uses stack.
the set of new local
variables and parameters
each time the function is
called.
4/24/2023 160
Overhead Recursion
Megha Gupta possesses the
ACSE0301: DS Unit 2 No overhead of repeated
Recursion
▪ Difference Between Recursion and Iteration
BASIS FOR
RECURSION ITERATION
COMPARISON
Speed Slow in execution. Fast in execution.
Size of Code Recursion reduces the Iteration makes the code
size of the code. longer.
1. Using Array
2. Using Link List
Application of Queue
•Queue is used to implement many algorithms like Breadth First Search (BFS), etc.
•It can be also used by an operating system when it has to schedule jobs with equal priority
•Customers calling a call center are kept in queues when they wait for someone to pick up the calls
10
A[0] A[1] A[2] A[3] A[4]
F=R=0
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
Megha Gupta Data Structure 4/24/2023 164
Queue
Insertion:
Algorithm:
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
20
A[0] A[1] A[2] A[3] A[4]
F=R=1
10 20
A[0] A[1] A[2] A[3] A[4]
F=0 R=1
20
A[0] A[1] A[2] A[3] A[4]
F=R=1
Deletion:
Algorithm:
1. Circular Queue
2. Priority Queue
3. Deque
4. Multiple Queue
• Problem:
– Wastage of memory in standard queue in DEQUEUE
operation
Traffic light functioning is the best example for circular queues. The colors in
the traffic light follow a circular pattern.
We can use the following steps to display the elements of a circular queue...
def dequeue(self):
if self.front== -1:
print("Queue is Empty")
elif self.front == self.rear:
self.front = -1
self.rear = -1
print("Element is Successfully Removed")
else:
self.front=(self.front+1)%self.size
print("Element is Successfully Removed")
def display(self):
if self.front== -1:
print("Queue is Empty")
elif self.rear >= self.front:
print("Elements in the circular Queue are:")
for i in range(self.front,self.rear+1):
print(self.queue[i])
else:
print("Elements in the circular queue are:")
for i in range(self.front,self.size):
print(self.queue[i])
for i in range(0,self.rear+1):
print(selff.queue[i])
if(self.rear+1)%self.size==self.front:
print("Queue is Full")
Priority Queue
DATA PRIORTY
NUMBER
A 5
B 1
D 3
E 2
F 8
G 6
Insertion Operation:
• While inserting elements in priority queue we will add it at
the appropriate position depending on its priority
Deletion Operation:
• While deletion, the element at the front is
always deleted.
DATA PRIORTY
NUMBER
B 1
E 2
D 3
A 5
G 6
F 8
Megha Gupta Data Structure 4/24/2023 188
Queue
Here we set-
Lower is the number
higher is the
priority.
This method is costly. Its not a best way to implement priority queue.
Best way to implement it is using priority queue class in python.
Here we set-
Lower is the
number higher is
the priority.
5. Priority queues are used in operating system for load balancing and
interrupt handling.
7. In traffic light, depending upon the traffic, the colors will be given priority.
Megha Gupta Data Structure 4/24/2023 192
Queue
# using appendleft() to insert element at left end inserts 6 at the beginning of deque
de.appendleft(6)
Application of Deque –
Deque is a Double Ended Queue where operations(Add/Remove) can be made on
both ends of the queue.
1.A web browser's history. Recently visited URLs are added to the front of the deque,
and the URL at the back of the deque is removed after some specified number of
insertions at the front.
3.Have you see moneyControl App, it will show the stocks you last visited, it will
remove the stocks after some time and will add the latest ones.
MCQ
Q 1. A queue follows __________
a) FIFO (First In First Out) principle
b) LIFO (Last In First Out) principle
c) Ordered array
d) Linear tree
Answer: a
MCQ
Q2. If the elements “A”, “B”, “C” and “D” are placed in a queue and are deleted one at a time, in
what order will they be removed?
a) ABCD
b) DCBA
c) DCAB
d) ABDC
Answer a
MCQ
Q3. A normal queue, if implemented using an array of size MAX_SIZE, gets full when?
a) Rear = MAX_SIZE – 1
b) Front = (rear + 1)mod MAX_SIZE
c) Front = rear + 1
d) Rear = front
Answer a)
4/24/2023 204
Megha Gupta Data Structure
Linked List
4/24/2023 205
Megha Gupta Data Structure
Introduction to Linked List
Linked List
4/24/2023 206
Megha Gupta Data Structure
Continued….
Linked List
• In a linear or single-linked list, a node is connected to the next node by a
single link.
• The nodes in a linked list are not stored contiguously in the memory
• Memory for each node can be allocated dynamically whenever the need
arises.
4/24/2023 210
Megha Gupta Data Structure
Arrays & Linked list
Insertions and Deletions are inefficient: Insertions and Deletions are efficient: No
Elements are usually shifted shifting
No memory waste if the array is full or almost Since memory is allocated dynamically(acc. to
full; otherwise may result in much memory our need) there is no waste of memory.
waste.
Sequential access is faster [Reason: Elements in Sequential access is slow [Reason: Elements not
contiguous memory locations] in contiguous memory locations]
4/24/2023 211
Megha Gupta Data Structure
Types of Link List
4/24/2023 212
Megha Gupta Data Structure
Singly Linked list
• In this type of linked list each node contains two fields one is data field
which is used to store the data items and another is next field that is
used to point the next node in the list.
5 3 8 null
4/24/2023 213
Megha Gupta Data Structure
Creating a node of linked list
# Node class (Creating a node of linked list)
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
Node1=Node(5)
print(Node1) Output
print(Node1.data)
print(Node1.next)
5 None
0x00000209F4195000
Node1
4/24/2023 214
Megha Gupta Data Structure
Creating an empty linked list
# Node class (Creating a node of linked list)
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
4/24/2023 215
Megha Gupta Data Structure
Creating a linked list with single node
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
LL = LinkedList()
LL.head = Node(3)
print(LL.head.data)
4/24/2023 216
Megha Gupta Data Structure
Creation and Traversal of single linked list
# A single node of a singly # insertion method for the
linked list linked list
class Node: def insert(self, data):
def __init__(self, data): newnode = node(data)
self.data = data if(self.head==None):
self.next = None self.head = newnode
else:
curr = self.head
# A Linked List class with a while(curr.next!=None):
single head node curr = curr.next
class LinkedList: curr.next=newnode
def __init__(self):
self.head = None
4/24/2023 218
Megha Gupta Data Structure
Insertion in a Single Linked List
4/24/2023 219
Megha Gupta Data Structure
Insertion in a Single Linked List (at
beginning)
▪ Insertion at beginning
4/24/2023 220
Megha Gupta Data Structure
Insertion in single linked list (at
beginning)
# A single node of a singly # insertion method for the linked
linked list list at beginning
class Node:
def __init__(self, data): def insert_beg(self, data):
self.data = data newNode = Node(data)
self.next = None if(self.head==None):
self.head = newNode
else:
# A Linked List class with a newNode.next=self.head
single head node self.head=newNode
class LinkedList:
def __init__(self):
self.head = None
4/24/2023 222
Megha Gupta Data Structure
Insertion in a Single Linked List (at end)
▪ Insertion at end
Temp
4/24/2023 223
Megha Gupta Data Structure
Insertion in single linked list (at end)
# A single node of a singly # insertion method for the
linked list linked list at end
class Node: def insert_end(self, data):
def __init__(self, data): newNode = Node(data)
self.data = data if(self.head==None):
self.next = None self.head = newNode
else:
current = self.head
# A Linked List class with a while(current.next!=None):
single head node current = current.next
class LinkedList: current.next = newNode
def __init__(self):
self.head = None
4/24/2023 226
Megha Gupta Data Structure
Insertion in single linked list (at position)
# A single node of a singly # creation method for the linked
linked list list
class Node: def create(self, data):
def __init__(self, data): newNode = Node(data)
self.data = data if(self.head==None):
self.next = None self.head = newNode
else:
current = self.head
# A Linked List class with a while(current.next):
single head node current = current.next
class LinkedList: current.next = newNode
def __init__(self):
self.head = None
4/24/2023 230
Megha Gupta Data Structure
Deletion in Single Linked List (from beginning)
4/24/2023 231
Megha Gupta Data Structure
Deletion in Single Linked List (from beginning)
# A single node of a singly # create method for the linked
linked list list
class Node: def create(self, data):
def __init__(self, data): newNode = Node(data)
self.data = data if(self.head):
self.next = None current = self.head
while(current.next):
current = current.next
# A Linked List class with a current.next = newNode
single head node else:
class LinkedList: self.head = newNode
def __init__(self):
self.head = None
4/24/2023 235
Megha Gupta Data Structure
Deletion in Single Linked List (from end)
# A single node of a singly # create method for the linked
linked list list
class Node: def create(self, data):
def __init__(self, data): newNode = Node(data)
self.data = data if(self.head):
self.next = None current = self.head
while(current.next):
current = current.next
# A Linked List class with a current.next = newNode
single head node else:
class LinkedList: self.head = newNode
def __init__(self):
self.head = None
4/24/2023 239
Megha Gupta Data Structure
Deletion in Single Linked List (from position)
# A single node of a singly # create method for the linked
linked list list
class Node: def create(self, data):
def __init__(self, data): newNode = Node(data)
self.data = data if(self.head):
self.next = None current = self.head
while(current.next):
current = current.next
# A Linked List class with a current.next = newNode
single head node else:
class LinkedList: self.head = newNode
def __init__(self):
self.head = None
elif(pos==1): if(temp!=None):
prev.next=temp.next
temp = self.head
print("the deleted element
self.head = self.head.next is", temp.data)
print("the deleted element is", temp=None
temp.data) else:
temp = None print("\nThe position does
not exist in link list.")
Megha Gupta Data Structure 4/24/2023 241
Deletion in Single Linked List (from position)
# print method for the linked list # Singly Linked List with deletion
def printLL(self): and print methods
current = self.head LL = LinkedList()
if(current!=None): LL.create(3)
print("The List LL.create(4)
Contains:",end="\n") LL.create(5)
while(current): LL.create(6)
print(current.data) LL.create(7)
current = current.next LL.create(8)
else: LL.printLL()
print("List is Empty.") LL.del_position(4)
LL.printLL()
If the linked list has two or more elements, we can use three
pointers to implement an iterative solution..
4/24/2023 243
Megha Gupta Data Structure
Reverse of a Single Linked List
• 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.
4/24/2023 245
Megha Gupta Data Structure
Creation and Traversal of single
Circular linked list
# A single node of a singly # insertion method for the linked list
linked list
def insert(self, data):
class Node: new_node = Node(data)
def __init__(self, data): if self.head is None:
self.data = data self.head = new_node
self.next = None self.head.next = self.head
else:
current_node = self.head
# A Linked List class with a while (current_node.next !=
single head node self.head):
class SinglyCircularLinkedList: current_node = current_node.next
def __init__(self): current_node.next = new_node
self.head = None new_node.next = self.head
4/24/2023 247
Megha Gupta Data Structure
Insertion in a Single Circular Linked List
4/24/2023 248
Megha Gupta Data Structure
Insertion in single circular linked list (at beginning)
# A single node of a singly
linked list
# insertion method for the linked list at
class Node: beginning
def __init__(self, data):
self.data = data def insert_beg(self, data):
self.next = None new_node = Node(data)
current_node = self.head
new_node.next = self.head
if (self.head==None):
# A Linked List class with a new_node.next = new_node
single head node else:
class LinkedList: while current_node.next != self.head:
def __init__(self): current_node = current_node.next
current_node.next = new_node
self.head = None self.head = new_node
4/24/2023 252
Megha Gupta Data Structure
Deletion in Single Circular Linked List (by value)
else:
temp = self.head
print("the deleted element is", temp.data)
if(self.head == self.head.next):
self.head = None
else:
self.head = self.head.next
temp = None
else:
temp = self.head
while(temp.next!=self.head):
prev=temp
temp=temp.next
prev.next=self.head
print("The deleted element is", temp.data)
temp = None
elif(pos==1): if(temp!=None):
prev.next=temp.next
temp = self.head
print("the deleted element
self.head = self.head.next is", temp.data)
print("the deleted element is", temp=None
temp.data) else:
temp = None print("\nThe position does
not exist in link list.")
Megha Gupta Data Structure 4/24/2023 256
Doubly Linked List
4/24/2023 257
Megha Gupta Data Structure
Doubly Linked List
4/24/2023 258
Megha Gupta Data Structure
Creating a Node of Doubly Linked List
class Node:
def __init__(self, data):
self.prev = None
self.item = data
self.next = None
4/24/2023 259
Megha Gupta Data Structure
Creating a Doubly linked list with single node
class Node:
def __init__(self, data):
self.prev=None
self.data = data
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
LL = DoublyLinkedList()
LL.head = Node(3)
print(LL.head.data)
4/24/2023 260
Megha Gupta Data Structure
Creation and Traversal of Doubly linked list
# A single node of a doubly # creation method for the doubly
linked list linked list
class Node: def create(self, data):
def __init__(self, data): newNode = Node(data)
self.prev = None if(self.head==None):
self.head = newNode
self.data = data
self.next = None else:
temp=self.head
# A Linked List class with a single while(temp.next!=None):
head node temp=temp.next
class DoublyLinkedList:
def __init__(self): temp.next=newNode
self.head = None newNode.prev=temp
4/24/2023 262
Megha Gupta Data Structure
Insertion at the Beginning Linked List
4/24/2023 263
Megha Gupta Data Structure
Insertion at Beginning in Doubly linked list
# A single node of a doubly # Insertion method for the doubly
linked list linked list at beginning
class Node: def insert_beg(self, data):
def __init__(self, data): newNode = Node(data)
self.prev = None if(self.head==None):
self.head = newNode
self.data = data
self.next = None else:
newNode.next=self.head
# A Linked List class with a single self.head.prev=newNode
head node self.head=newNode
class DoublyLinkedList:
def __init__(self):
self.head = None
4/24/2023 265
Megha Gupta Data Structure
Insertion at the end of Doubly Linked List
4/24/2023 266
Megha Gupta Data Structure
Insertion at end in Doubly linked list
# A single node of a doubly # Insertion method for the doubly
linked list linked list at end
class Node: def insert_end(self, data):
def __init__(self, data): newNode = Node(data)
self.prev = None if(self.head==None):
self.head = newNode
self.data = data
self.next = None else:
temp=self.head
# A Linked List class with a single while(temp.next!=None):
head node temp=temp.next
class DoublyLinkedList:
def __init__(self): newNode.prev=temp
self.head = None temp.next=newNode
4/24/2023 268
Megha Gupta Data Structure
Insertion in Doubly Linked List (at position)
4/24/2023 269
Megha Gupta Data Structure
Insertion in Doubly Linked List (at position)
# A single node of a doubly # creation method for the doubly
linked list linked list
class Node: def create(self, data):
newNode = Node(data)
def __init__(self, data):
if(self.head==None):
self.prev = None
self.head = newNode
self.data = data
self.next = None else:
temp=self.head
# A Linked List class with a single while(temp.next!=None):
head node temp=temp.next
class DoublyLinkedList:
def __init__(self): temp.next=newNode
newNode.prev=temp
self.head = None
newNode.next=self.head
else:
self.head=newNode print("\nThe previous node is
null.")
Megha Gupta Data Structure 4/24/2023 271
Insertion in Doubly Linked List (at position) (contd..)
# print method for the linked list # Doubly Linked List with creation
def printLL(self): and print methods
current = self.head LL = DoublyLinkedList()
LL.create(3)
if(current!=None):
LL.create(4)
print("The List LL.create(5)
Contains:",end="\n")
LL.create(6)
while(current!=None):
LL.create(7)
print(current.data) LL.printLL()
current = current.next LL.insert_position(4, 9)
else: LL.printLL()
print("List is Empty.")
4/24/2023 272
Megha Gupta Data Structure
Deletion in a Doubly Linked List
4/24/2023 273
Megha Gupta Data Structure
Deletion in Doubly Linked List (from beginning)
4/24/2023 274
Megha Gupta Data Structure
Deletion in Doubly Linked List (from beginning)
# A single node of a doubly # creation method for the doubly
linked list linked list
class Node: def create(self, data):
def __init__(self, data): newNode = Node(data)
self.prev = None if(self.head==None):
self.head = newNode
self.data = data
self.next = None else:
temp=self.head
# A Linked List class with a single while(temp.next!=None):
head node temp=temp.next
class DoublyLinkedList:
def __init__(self): temp.next=newNode
self.head = None newNode.prev=temp
4/24/2023 276
Megha Gupta Data Structure
Deletion in Doubly Linked List (from beginning) (contd..)
4/24/2023 277
Megha Gupta Data Structure
Deletion in Doubly Linked List (from end)
4/24/2023 278
Megha Gupta Data Structure
Deletion in Doubly Linked List (from end)
# A single node of a doubly # creation method for the doubly
linked list linked list
class Node: def create(self, data):
def __init__(self, data): newNode = Node(data)
self.prev = None if(self.head==None):
self.head = newNode
self.data = data
self.next = None else:
temp=self.head
# A Linked List class with a single while(temp.next!=None):
head node temp=temp.next
class DoublyLinkedList:
def __init__(self): temp.next=newNode
self.head = None newNode.prev=temp
4/24/2023 280
Megha Gupta Data Structure
Deletion in Doubly Linked List (from end) (contd..)
4/24/2023 281
Megha Gupta Data Structure
Deletion in Doubly Linked List (from position)
4/24/2023 282
Megha Gupta Data Structure
Deletion in Doubly Linked List (from position)
# A single node of a doubly # creation method for the doubly
linked list linked list
class Node: def create(self, data):
def __init__(self, data): newNode = Node(data)
self.prev = None if(self.head==None):
self.head = newNode
self.data = data
self.next = None else:
temp=self.head
# A Linked List class with a single while(temp.next!=None):
head node temp=temp.next
class DoublyLinkedList:
def __init__(self): temp.next=newNode
self.head = None newNode.prev=temp
4/24/2023 284
Megha Gupta Data Structure
Deletion in Doubly Linked List (from position) (contd..)
4/24/2023 285
Megha Gupta Data Structure
Deletion in Doubly Linked List (from position) (contd..)
11. How would you find the middle node of a singly linked list with only one pass
through the list?
12. Can you explain how to detect if a linked list has a loop in it? What is the time
complexity of your solution?
13. Can you explain how to remove duplicates from an unsorted linked list? What is
the time complexity of your solution?
14. How would you swap the kth node from the beginning with the kth node from the
end in a singly linked list?
15. Can you explain how to detect if two linked lists intersect? What is the time
complexity of your solution?
16. Can you explain how to delete a node from a singly linked list, given only a
pointer to that node?
17. Can you explain how to check if a linked list is palindrome or not?
▪ Root
▪ In a tree data structure, the first node is called as Root
Node.
▪ Every tree must have a root node.
▪ Root node is the origin of the tree data structure.
▪ In any tree, there must be only one root node.
▪ Edge
▪ In a tree data structure, the connecting link between any
two nodes is called as EDGE.
▪ In a tree with 'N' number of nodes there will be a maximum
of 'N-1' number of edges.
▪ Parent
▪ In a tree data structure, the node which is a predecessor of
any node is called as PARENT NODE.
▪ In simple words, the node which has a branch from it to any
other node is called a parent node.
▪ Parent node can also be defined as "The node which has
child / children".
▪ Child
▪ In a tree data structure, the node which is descendant of
any node is called as CHILD Node.
▪ In simple words, the node which has a link from its parent
node is called as child node.
▪ In a tree, any parent node can have any number of child
nodes.
▪ In a tree, all the nodes except root are child nodes.
▪ Siblings
▪ In a tree data structure, nodes which belong to same Parent
are called as SIBLINGS.
▪ In simple words, the nodes with the same parent are called
Sibling nodes
▪ Leaf
▪ In a tree data structure, the node which does not have a
child is called as LEAF Node.
▪ In simple words, a leaf is a node with no child.
▪ In a tree data structure, the leaf nodes are also called
as External Nodes.
▪ In a tree, leaf node is also called as 'Terminal' node.
▪ Internal Nodes
▪ In a tree data structure, the node which has atleast one
child is called as INTERNAL Node.
▪ In a tree data structure, nodes other than leaf nodes are
called as Internal Nodes.
▪ The root node is also said to be Internal Node if the tree
has more than one node.
▪ Internal nodes are also called as 'Non-Terminal' nodes.
▪ Degree
▪ In a tree data structure, the total number of children of a
node is called as DEGREE of that Node.
▪ The highest degree of a node among all the nodes in a tree
is called as 'Degree of Tree'
▪ Level
▪ In a tree data structure, the root node is said to be at Level 0
and the children of root node are at Level 1 and the
children of the nodes which are at Level 1 will be at Level 2
and so on...
▪ In simple words, in a tree each step from top to bottom is
called as a Level and the Level count starts with '0' and
incremented by one at each level (Step).
▪ Height
▪ In a tree data structure, the total number of edges from leaf
node to a particular node in the longest path is called
as HEIGHT of that Node.
▪ In a tree, height of the root node is said to be height of the
tree.
▪ In a tree, height of all leaf nodes is '0'.
▪ Depth
▪ In a tree data structure, the total number of egdes from root
node to a particular node is called as DEPTH of that Node.
▪ In a tree, the total number of edges from root node to a leaf
node in the longest path is said to be Depth of the tree.
▪ In a tree, depth of the root node is '0'.
▪ Path
▪ In a tree data structure, the sequence of Nodes and Edges
from one node to another node is called as PATH between
that two Nodes.
▪ Length of a Path is total number of nodes in that path.
▪ In below example the path A - B - E - J has length 4.
▪ Sub Tree
▪ In a tree data structure, each child from a node forms a
subtree recursively.
▪ Every child node will form a subtree on its parent node.
▪ Preorder (Node,Left,Right)
▪ Postorder (Left, Right, Node)
▪ Inorder(Left, Node, Right)
PreOrder : (NLR)
Ans – 1 7 2 6 3 8 5 9 4
InOrder: (LNR)
Ans – 2 7 3 6 8 1 5 4 9
PostOrder: (LRN)
Ans - 2 3 8 6 7 4 9 5 1
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
1. Pickup last key of post order sequence and create node of each.
Inorder: 1 2 3 4 5 7 8
Postorder: 1 3 4 2 7 8 5
1. Pickup first key of pre order sequence and create node of each.
2. Create left subtree of root node recursively by selecting keys which are
preceding the root node in Inorder.
Inorder: 1 2 3 4 5 7 8
Preorder: 5 2 1 4 3 8 7
Inorder: 1 2 3 4 5 6 7 8
Preorder: 5 3 1 2 4 6 8 7
10, 20,30
SN Operation Description
Min Heap
▪ The value of the parent node should be less than or equal to either of
its children.
▪ Suppose we want to create the max heap tree. To create the max heap
tree, we need to consider the following two cases:
➢ First, we have to insert the element in such a way that the property of the
complete binary tree must be maintained.
➢ Secondly, the value of the parent node should be greater than the either of
its child.
▪ Where node A is the node whose balance Factor is other than -1, 0, 1.
▪ The first two rotations LL and RR are single rotations and the next two
rotations LR and RL are double rotations.
1. Insert H, I, J
3. Insert E
On inserting E,
4. Insert C, F, D
On inserting C, F, D, BST
becomes unbalanced as the
Balance Factor of B and H is -2,
since if we travel from D to B we
find that it is inserted in the right
subtree of left subtree of B,
5. Insert G
LR = RR + LL rotation.
6. Insert K
7. Insert L
On inserting the L tree is still balanced as the Balance Factor of each
node is now either, -1, 0, +1. Hence the tree is a Balanced AVL tree
• Let us consider that, A is the critical node and B is the root node of
its left sub-tree.
• If node X, present in the right sub-tree of A, is to be deleted, then
there can be three different situations:
If the node B has 0 balance factor, and the balance factor of node A
disturbed upon deleting the node X, then the tree will be rebalanced
by rotating tree using R0 rotation.
The critical node A is moved to its right and the node B becomes the
root of the tree with T1 as its left sub-tree. The sub-trees T2 and T3
becomes the left and right sub-tree of the node A. the process
involved in R0 rotation is shown in the following image.
Solution
In this case, the node B has balance factor 0, therefore the tree will be
rotated by using R0 rotation as shown in the following image. The node
B(10) becomes the root, while the node A is moved to its right. The right
child of node B will now become the left child of node A.
Example
Delete Node 55 from the AVL tree shown in the following image.
Deleting 55 from the AVL Tree disturbs the balance factor of the node
50 i.e. node A which becomes the critical node. This is the condition of
R1 rotation in which, the node A will be moved to its right (shown in the
image below). The right of B is now become the left of A (i.e. 45).
The process involved in the solution is shown in the following image.
Solution:
in this case, node B has balance factor -1. Deleting the node
60, disturbs the balance factor of the node 50 therefore, it
needs to be R-1 rotated. The node C i.e. 45 becomes the
root of the tree with the node B(40) and A(50) as its left and
right child.
Case 1. When leaf element is not full then insert element into it.
Example
key :- P,A,Q,S,B,X,C,L,Z,Y,T,G,J,I,D,H,R,V,E,U,F,R.
Order = 5
1. Insert P
2. Insert P
Example
key :- P,A,Q,S,B,X,C,L,Z,Y,T,G,J,I,D,H,R,V,E,U,F,R,O.
1. Insert Q
2. Insert S
3. Insert B
4. Insert X
5. Insert C
6. Insert L
8. Insert Y
9. Insert T
11 Insert J
12 Insert I
13. Insert D
14. Insert H
16. Insert V
17. Insert E
18. Insert U
19. Insert F
20. Insert O
Deletion in B-Tree
For deletion in B-Tree we wish to remove from a leaf. There are
three possible case for deletion in b tree.
Let k be the key to be deleted, x the node containing the key. Then
the cases are:
Case-I
If the key is already in a leaf node, and removing it doesn’t cause that leaf node to have
too few keys, then simply remove the key to be deleted. key k is in node x and x is a
leaf, simply delete k from x.
Delete 6
6 deleted
Case-II
If key k is in node x and x is an internal node, there are three cases to consider:
Case-II-a
If the child y that precedes k in node x has at least t keys (more than the
minimum), then find the predecessor key k' in the subtree rooted at y. Recursively
delete k' and replace k with k' in x
Case-II-b
Symmetrically, if the child z that follows k in node x has at least t keys, find the successor
k' and delete and replace as before. Note that finding k' and deleting it can be performed
in a single downward pass.
13 deleted
Case-II-c
Otherwise, if both y and z have only t−1 (minimum number) keys, merge k and all of z into y,
so that both k and the pointer to z are removed from x. y now contains 2t − 1 keys, and
subsequently k is deleted.
7 deleted
After deleting 2
1. What is a binary tree? Can you explain the properties of a binary tree?
2. Can you explain the difference between a binary tree and a binary search tree? What are the
advantages of using a binary search tree?
3. Can you explain the different types of binary tree traversals? What is the time complexity of
each traversal?
4. How would you find the height of a binary tree? Can you explain the time complexity of your
solution?
5. Can you explain how to implement a binary search tree in code? Can you provide an example
implementation?
6. Can you explain how to delete a node from a binary search tree? What are the different
cases you need to handle while deleting a node?
7. Can you explain how to find the lowest common ancestor of two nodes in a binary tree?
What is the time complexity of your solution?
9. Can you explain how to check if a binary tree is balanced? What is the time complexity
of your solution?
10. Can you explain how to implement a heap data structure using a binary tree? What are
the advantages of using a heap over a binary search tree?
B-Tree:
1. What is a B-tree?
2. What is the difference between a B-tree and a binary tree?
3. How do you search for a key in a B-tree?
4. How do you insert a key in a B-tree?
5. What is the minimum number of children that a non-root node can have in a B-tree of degree k?
6. What is the maximum number of keys that a node can have in a B-tree of degree k?
Introduction to Graphs
Graph is a non-linear data structure. It contains a set of points
known as nodes (or vertices) and a set of links known as edges (or
Arcs). Here edges are used to connect the vertices. A graph is
defined as follows...
Graph Terminology
We use the following terms in graph data structure...
Vertex
Individual data element of a graph is called as Vertex. Vertex is
also known as node. In above example graph, A, B, C, D & E are
known as vertices.
Edge
An edge is a connecting link between two vertices. Edge is also
known as Arc. An edge is represented as (startingVertex,
endingVertex). For example, in above graph the link between
vertices A and B is represented as (A,B). In above example graph,
there are 7 edges (i.e., (A,B), (A,C), (A,D), (B,D), (B,E), (C,D),
(D,E)).
Undirected Graph
A graph with only undirected edges is said to be undirected graph.
Directed Graph
A graph with only directed edges is said to be directed graph.
Mixed Graph
A graph with both undirected and directed edges is said to be mixed
graph.
End vertices or Endpoints
The two vertices joined by edge are called end vertices (or endpoints)
of that edge.
Origin
If a edge is directed, its first endpoint is said to be the origin of it.
Destination
If a edge is directed, its first endpoint is said to be the origin of it
and the other endpoint is said to be the destination of that edge.
Adjacent
If there is an edge between vertices A and B then both A and B are
said to be adjacent. In other words, vertices A and B are said to be
adjacent if there is an edge between them.
Incident
Edge is said to be incident on a vertex if the vertex is one of the
endpoints of that edge.
Outgoing Edge
A directed edge is said to be outgoing edge on its origin vertex.
Incoming Edge
A directed edge is said to be incoming edge on its destination
vertex.
Degree
Total number of edges connected to a vertex is said to be degree of
that vertex.
Indegree
Total number of incoming edges connected to a vertex is said to be
indegree of that vertex.
Outdegree
Total number of outgoing edges connected to a vertex is said to be
outdegree of that vertex.
Parallel edges or Multiple edges
If there are two undirected edges with same end vertices and two
directed edges with same origin and destination, such edges are
called parallel edges or multiple edges.
Self-loop
Edge (undirected or directed) is a self-loop if its two endpoints
coincide with each other.
Simple Graph
A graph is said to be simple if there are no parallel and self-loop
edges.
Path
A path is a sequence of alternate vertices and edges that starts at a
vertex and ends at other vertex such that each edge is incident to its
predecessor and successor vertex.
Graph Representations
1.Adjacency Matrix
2.Incidence Matrix
3.Adjacency List
Adjacency Matrix
In this representation, the graph is represented using a matrix of size
total number of vertices by a total number of vertices.
Incidence Matrix
Adjacency List
In this representation, every vertex of a graph contains list of its
adjacent vertices.
There are two graph traversal techniques and they are as follows...
1.DFS (Depth First Search)
2.BFS (Breadth First Search)
• Step 4 - When there is no new vertex to be visited from the vertex which
is at front of the Queue then delete that vertex.
• Step 6 - When queue becomes empty, then produce final spanning tree by
removing unused edges from the graph.
1Stands for BFS stands for Breadth First Search. DFS stands for Depth First Search.
Conceptual
5 Difference BFS builds the tree level by level. DFS builds the tree sub-tree by sub-tree.
It works on the concept of FIFO (First In It works on the concept of LIFO (Last In First
6Approach used First Out). Out).
Megha Gupta Data Structure 4/24/2023 437
S. No. Parameters BFS DFS
BFS is more suitable for searching DFS is more suitable when there are solutions
7Suitable for vertices closer to the given source. away from source.
The Time complexity of BFS is O(V +
E) when Adjacency List is used and The Time complexity of DFS is also O(V + E)
O(V^2) when Adjacency Matrix is when Adjacency List is used and O(V^2) when
used, where V stands for vertices and Adjacency Matrix is used, where V stands for
9Time Complexity E stands for edges. vertices and E stands for edges.
Here, siblings are visited before the
10Visiting of Siblings/ Children children. Here, children are visited before the siblings.
Prim's Algorithm
Prim's algorithm starts with the single node and explore all the adjacent
nodes with all the connecting edges at every step. The edges with the
minimal weights causing no cycles in the graph got selected.
Prim's Algorithm
The algorithm is given as follows.
Algorithm
Solution
o Step 1 : Choose a starting vertex B.
o Step 2: Add the vertices that are adjacent to A. the edges that
connecting the vertices are shown by dotted lines.
o Step 3: Choose the edge with the minimum weight among all. i.e.
BD and add it to MST. Add the adjacent vertices of D i.e. C and E.
o Step 3: Choose the edge with the minimum weight among all. In this
case, the edges DE and CD are such edges. Add them to MST and
explore the adjacent of C i.e. E and A.
o Step 4: Choose the edge with the minimum weight i.e. CA. We
can't choose CE as it would cause cycle in the graph.
The graph produces in the step 4 is the minimum spanning tree of the
graph shown in the above figure.
The cost of MST will be calculated as;
cost(MST) = 4 + 2 + 1 + 3 = 10 units.
Algorithm
o Step 1: Create a forest in such a way that each graph
is a separate tree.
ELSE
Discard the edge
Step 6: END
Example :
Apply the Kruskal's algorithm on the graph given as
follows.
Solution:
the weight of the edges given as:
Edge AE AD AC AB BC CD DE
Weight 5 10 7 1 3 4 2
Megha Gupta Data Structure 4/24/2023 451
Graphs
Edge AB DE BC CD AE AC AD
Weight 1 2 3 4 5 7 10
The next step is to add AE, but we can't add that as it will cause a
cycle.
The next edge to be added is AC, but it can't be added as it will
cause a cycle.
The next edge to be added is AD, but it can't be added as it
will contain a cycle.
Hence, the final MST is the one which is shown in
the step 4. the cost of MST = 1 + 2 + 3 + 4 = 10.
B 210 B
A A
450
60 190
C unweighted C weighted
graph graph
200 130
D D
E E
Megha Gupta Data Structure 4/24/2023 455
Shortest Path Problems
▪ How can we find the shortest route between two points on a map?
vertices = cities
edges = road segments between cities
edge weights = road distances
▪ Goal: find a shortest path between two vertices (cities)
4/24/2023 456
Shortest Path Problems
▪ Input: t x
6
3 9
▪ Directed graph G = (V, E) 3
4
2 1
▪ Weight function w : E → R s 0
2 7
5 3
▪ Weight of path p = v0, v1, . . . , vk
5 11
k 6
w( p ) = w( vi −1 , vi ) y z
i =1
∞ otherwise
▪ All-pairs shortest-paths
▪ Find a shortest path from u to v for every pair of vertices u
Megha Gupta and v
Data Structure 4/24/2023 458
Shortest Path Algorithm
Find the single source shortest path from the vertex A.
Priority queue → A B C D E F
0∞ ∞ ∞ ∞∞
Solution set (S)= ϕ
Extract min(Queue) = A
S = S U {A}
= {A}
Priority queue → B C D E F
2 ∞ 8 ∞∞
Solution set (S)= {A}
Extract min(Queue) = B
S = S U {B}
= {A,B}
Priority queue → C D E F
5 7 ∞∞
Solution set (S)= {A,B}
Extract min(Queue) = C
S = S U {C}
= {A,B,C}
Priority queue → E F
12 11
Solution set (S)= {A,B,C,D}
Extract min(Queue) = F
S = S U {F}
= {A,B,C,D,F}
Priority queue → E
12
Solution set (S)= {A,B,C,D,F}
Extract min(Queue) = E
S = S U {E}
= {A,B,C,D,F,E}
5 7
2
y z
24
2 3
9
s
18
14
2 6
6
30 4 19
11
15 5
5
6
20 16
t
7 44
•It computes the shortest path between every pair of vertices of the given graph.
Advantages-
Floyd Warshall Algorithm has the following main advantages-
Time Complexity-
•Floyd Warshall Algorithm consists of three loops over all the nodes.
•This is because its complexity depends only on the number of vertices in the given
graph.
Problem-
Using Floyd Warshall Algorithm, find the shortest path distance between every pair of
vertices.
Step-01:
•Remove all the self loops and parallel edges (keeping the lowest weight edge) from the
graph.
•In the given graph, there are neither self edges nor parallel edges.
Step-02:
Step-02: (Continue)
Step-03:
Step-03:
Remember-
•In the above problem, there are 4 vertices in the given graph.
•So, there will be total 4 matrices of order 4 x 4 in the solution excluding the initial
distance matrix.
•Diagonal elements of each matrix will always be 0.
Given a directed graph, find out if a vertex j is reachable from another vertex i for all vertex pairs (i, j) in the
given graph. Here reachable mean that there is a path from vertex i to j.
1111
1111
1111
0001
Interview Questions
Interview Questions
What is a spanning tree of a graph? Can you explain the difference between a minimum
Can you explain the difference between a connected graph and a disconnected graph?
How can you represent a weighted graph in memory? Can you show an example?
Can you explain the difference between a complete graph and a sparse graph?
Can you explain the concept of a bipartite graph? How can you check if a given graph is
bipartite?
Interview Questions
What is a graph traversal algorithm that uses a priority queue? Can you explain how it works?
Can you explain the concept of a strongly connected component in a directed graph?
Can you explain the difference between an adjacency list and an adjacency matrix? Which
Can you explain Kruskal's algorithm for finding the minimum spanning tree in a graph? Can
What is the difference between a stack and a queue? Can you give an example of a
situation where you would prefer one over the other?
What is the difference between an array and a linked list? Can you explain the
advantages and disadvantages of each data structure?
What is the difference between a binary search tree and a red-black tree? Can you
explain the advantages and disadvantages of each data structure?
Interview Questions
What is the difference between a B-tree and a B+ tree? Can you explain the advantages
and disadvantages of each data structure?
What is the difference between a hash table and a binary search tree? Can you explain
the advantages and disadvantages of each data structure for searching and inserting
elements?
What is the difference between a linear search and a binary search? Can you explain
the time complexity of each algorithm and the conditions under which you would
prefer one over the other?
What is the difference between a singly linked list and a doubly linked list? Can you
explain the advantages and disadvantages of each data structure for traversing and
modifying elements?
What is the difference between a stack and a heap? Can you explain the advantages
and disadvantages of each data structure for allocating and deallocating memory?
Megha Gupta Data Structure 4/24/2023 490