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

DS Training in Python

The document is a syllabus for a data structures course taught by Megha Gupta. It covers 5 modules: data types and linear/non-linear data structures including arrays, stacks, queues, linked lists, trees, graphs. Arrays are described as collections of variables of the same type indexed with a common name. Stacks and queues follow LIFO and FIFO principles respectively. Linear structures traverse elements sequentially while non-linear structures have non-sequential relationships.

Uploaded by

Manik Panwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

DS Training in Python

The document is a syllabus for a data structures course taught by Megha Gupta. It covers 5 modules: data types and linear/non-linear data structures including arrays, stacks, queues, linked lists, trees, graphs. Arrays are described as collections of variables of the same type indexed with a common name. Stacks and queues follow LIFO and FIFO principles respectively. Linear structures traverse elements sequentially while non-linear structures have non-sequential relationships.

Uploaded by

Manik Panwar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 490

NOIDA INSTITUTE OF ENGINEERING AND TECHNOLOGY, GREATER

NOIDA

DATA STRUCTURES
Megha Gupta
Assistant Professor 1
Computer Science and Engineering
NIET, Gr. Noida

Megha Gupta Data Structure 4/24/2023


Syllabus
Module-1

▪ 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

Array Application of Arrays.

Megha Gupta Data Structure 4/24/2023 2


Syllabus
Module-2

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,

Full and Empty, Circular queues, Dequeue and Priority Queue.

Megha Gupta Data Structure 4/24/2023 3


Syllabus

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.

Megha Gupta Data Structure 4/24/2023 4


Syllabus
Module-4

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

trees, AVL Tree, B-Tree.

Megha Gupta Data Structure 4/24/2023 5


Syllabus
Module-5

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

algorithm. Transitive Closure and Shortest Path algorithms: Dijkstra Algorithm.

Megha Gupta Data Structure 4/24/2023 6


Introduction (CO1)

▪ Data: are simply a value are set of values of different type


which is called data types like string, integer, char etc.

▪ Structure: Way of organizing information, so that it is


easier to use.

▪ In simple words we can define DATA STRUCTURES as


its a way organizing data in such a way so that data can
be easier to use.

Megha Gupta Data Structure


4/24/2023 7
Introduction (CO1)

▪ Data Structure ..

A data structure is a particular way of


organizing data in a computer so that it can be
used efficiently.

Megha Gupta Data Structure


4/24/2023 8
Introduction (CO1)

Megha Gupta Data Structure


4/24/2023 9
Introduction (CO1)

▪ Human requirement with computer are going to


complex day by day. To solve the complex requirements
in efficient way we need this study.

▪ Provide fastest solution of human requirements.

▪ Provide efficient solution of complex problem.


>Space
>Time
Megha Gupta Data Structure
4/24/2023 10
Introduction (CO1)

Megha Gupta Data Structure


4/24/2023 11
Introduction (CO1)

▪ Simple Data Structure /Primitive data structure: used


to represent the standard data types of any one of
the computer languages (integer, Character, float
etc.).

▪ Compound Data Structure / Non Primitive Data


Structure can be constructed with the help of any
one of the primitive data structure and it is having a
specific functionality. It can be designed by user. It
can be classified as Linear and Non-Linear Data
Structure.

Megha Gupta Data Structure


4/24/2023 12
Introduction (CO1)

▪ Linear Data Structures: A linear data structure


traverses the data elements sequentially, in which only
one data element can directly be reached. Ex: Arrays,
Linked Lists.

▪ Non-Linear Data Structures: Every data item is


attached to several other data items in a way that is
specific for reflecting relationships. The data items are
not arranged in a sequential structure. Ex: Trees, Graphs

Megha Gupta Data Structure


4/24/2023 13
Introduction (CO1)

Python Specific Data Structures

▪ 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.

▪ Dictionary − The dictionary contains Key-value pairs as its data elements.

▪ 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.

Megha Gupta Data Structure


4/24/2023 14
Introduction (CO1)

▪ Array : An array is the collection of the variables of the same data


type that are referenced by the common name.
▪ int A[10], char B[10]

Megha Gupta Data Structure


4/24/2023 15
Introduction (CO1)

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.

Megha Gupta Data Structure 4/24/2023 16


Introduction (CO1)

▪ 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.

Megha Gupta Data Structure


4/24/2023 17
Introduction (CO1)

• Storing web pages in a web browser's back button history.


• Evaluating arithmetic expressions.
• Undo/Redo functionality in a text editor.

Megha Gupta Data Structure


4/24/2023 18
Introduction (CO1)

▪ Queue is a linear data structure in which


the insertion and deletion operations are
performed at two different ends.
▪ The insertion is performed at one end and
deletion is performed at another end.
▪ In a queue data structure, the insertion
operation is performed at a position which
is known as 'rear' and the deletion
operation is performed at a position which
is known as 'front'.
▪ In queue data structure, the insertion and
deletion operations are performed based
on FIFO (First In First Out) principle.
4/24/2023 19
Megha Gupta Data Structure
Introduction (CO1)

• Managing customer service calls in a call center.


• Printing documents in a printer queue.
• Managing incoming requests to a server.

Megha Gupta Data Structure


4/24/2023 20
Introduction (CO1)

▪ 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".

200 300 250


100
Megha Gupta Data Structure
4/24/2023 21
Introduction (CO1)

• Implementing a music playlist.


• Implementing a browser history list.
• Implementing a spell checker.

Megha Gupta Data Structure


4/24/2023 22
Introduction (CO1)

▪ Tree is a non-linear
data structure which
organizes data in
hierarchical structure.

Megha Gupta Data Structure


4/24/2023 23
Introduction (CO1)

• Organizing files and folders on a computer.


• Representing the structure of a website.
• Representing a family tree.

Megha Gupta Data Structure


4/24/2023 24
Introduction (CO1)

▪ 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.

▪ Generally, a graph G is
represented as G = ( V , E ),
where V is set of vertices and E is
set of edges.

Megha Gupta Data Structure


4/24/2023 25
Introduction (CO1)

• Representing road networks in a city.


• Analyzing social networks.
• Solving optimization problems.

Megha Gupta Data Structure


4/24/2023 26
Introduction to Array (CO1)

▪ An array is the collection of the variable of the same type that


are referenced by the common name.
▪ An array is the derived data type.
▪ Consist of contiguous memory locations.
▪ Lowest address corresponds to first element while highest
address corresponds to last element.
▪ Can have data item of type int, float, char, double etc. also have
user derived data type like: structure, union.

Megha Gupta Data Structure


4/24/2023 27
Introduction to Array (CO1)

▪ To store large number of array of variables of same type under a


single variable.
▪ Eg.
To store Marks of 50 Students
Record of sales of 100 salesman

Megha Gupta Data Structure 4/24/2023 28


Introduction to Array (CO1)

▪ Arrays are classified into two types. They are as follows...


> Single Dimensional Array / One Dimensional Array
> Multi Dimensional Array

Single Dimensional Array


array1 = [0, 0, 0, 1, 2]
array2 = ["cap", "bat", "rat"]

Accessing Elements of Single Dimensional Array


A[2]=99;

Megha Gupta Data Structure 4/24/2023 29


Introduction to Array (CO1)

Megha Gupta Data Structure


4/24/2023 30
Introduction to Array (CO1)

▪ Array of an element of an array say “A[ I ]” is calculated using the following


formula:
▪ Address of A [ I ] = B + W * ( I – LB )
▪ Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)

Megha Gupta Data Structure


4/24/2023 31
Introduction to Array (CO1)

▪ 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:

The given values are: B = 1020, LB = 1300, W = 2, I = 1700


Address of A [ I ] = B + W * ( I – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]

Megha Gupta Data Structure


4/24/2023 32
Introduction to Array (CO1)

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]

Access Array Element:


We can use index numbers in order to access array elements. In the
following example, we get the 2nd element whose index number is 1.
Marks = [50,92,89,75]
print(Marks[1])
Megha Gupta Data Structure
4/24/2023 33
Introduction to Array (CO1)

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))

Loop (Iterate) Array:


We can iterate over array elements by using different loop mechanisms.
The for loop can be used to loop or iterate over array elements.

Marks = [50,92,89,75]
for i in Marks:
print(i)

Megha Gupta Data Structure


4/24/2023 34
Introduction to Array (CO1)

Add Array Element:


The list append() method is used to add a new array element. The
element we want to add is provided as a parameter to the append()
method.
Marks = [50,92,89,75]
Marks.append(80)
O/p: [50,92,89,75,80]

Remove Array Element:


The pop() method can be used to remove or delete elements from the
array. The elements index number is provided to the pop() method to
remove.
Marks = [50,92,89,75]
Marks.pop(2)
O/p: [50,92,75]

Megha Gupta Data Structure


4/24/2023 35
Introduction to Array (CO1)

Add no. of elements in an array:


Reverse Array Elements:
Add the elements of cars to the fruits list:
Array elements can be reversed by
fruits = ['apple', 'banana', 'cherry’]
using the reverse() method.
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
Marks = [50,92,89,75]
print(fruits)
Marks.reverse()
print(Marks)
o/p : [apple', 'banana', 'cherry’, 'Ford', 'BMW', 'Volvo’]
O/p: [75,89,92,50]
Insert an element at a given position in an Array:
Insert the value "orange" as the second element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")

o/p: ['apple', ‘orange', 'banana', 'cherry']

Megha Gupta Data Structure


4/24/2023 36
Introduction to Array (CO1)

Python Sorting:

Sort the list alphabetically:


cars = ['Ford', 'BMW', 'Volvo']

cars.sort()

Sort the list descending:


cars = ['Ford', 'BMW', 'Volvo']

cars.sort(reverse=True)

Megha Gupta Data Structure


4/24/2023 37
Introduction to Array (CO1)

def largest(arr, n):

# Initialize maximum element


max = arr[0]

# Traverse array elements from second


# and compare every element with
# current max
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max

# 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)

Pseudo Code to Delete Duplicate elements from the array

for(i=0; i<size; i++)


{
for(j=i+1; j<size; j++)
{ /* If any duplicate found */
if(arr[i] == arr[j])
{ /* Delete the current duplicate element */
for(k=j; k<size-1; k++)
{
arr[k] = arr[k + 1];
} /
• Decrement size after removing duplicate element */
size--;
/* If shifting of elements occur then don't increment j */
j--;
}
}
}
Megha Gupta ACSE0301 DS Unit 1
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]

Megha Gupta Data Structure 4/24/2023 40


Introduction to Array(CO1)
Program to remove the given number from all occurrence

def remove_element(arr, num):


i=0
n = len(arr)
while i < n:
if arr[i] == num:
# remove element from list
arr.pop(i)
# decrement n as list length is reduced
n -= 1
else:
# increment i to check next element
i += 1
return arr
# example usage
arr = [1, 2, 3, 4, 2, 5, 6, 2]
num = 2
new_arr = remove_element(arr, num)
print(new_arr)
Megha Gupta ACSE0301 DS Unit 1
Introduction to Array (CO1)

WHAT IS THE OUTPUT OF THE FOLLOWING PYTHON CODE?

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]

Megha Gupta Data Structure 4/24/2023 42


Introduction to Array (CO1)

1. What is an array in programming?


2. What is the difference between an array and a linked list?
3. What is the time complexity of accessing an element in an array?
4. How can you reverse an array?
5. What is a two-dimensional array?
6. How can you find the maximum and minimum values in an array?
7. What is the difference between a static and dynamic array?
8. How do you find duplicates in an array?
9. What is the time complexity of searching for an element in an unsorted array?
10.How do you implement a dynamic array in Python?
11.What is a sparse array?
12.What is the difference between an array and a stack?
13.How do you remove an element from an array in Python?
14.What is a jagged array?
15.What is the time complexity of sorting an array?
Megha Gupta Data Structure 4/24/2023 43
Introduction to Array (CO1)

1. Write a function to check if two arrays are equal.


2. Write a function to remove duplicates from an array.
3. Write a function to find the intersection of two arrays.
4. Write a function to find the kth largest element in an array.
5. Write a function to rotate an array by a given number of steps.
6. Write a function to sort an array in descending order.
7. Write a function to merge two sorted arrays.
8. Write a function to find the median of two sorted arrays.
9. Write a function to reverse the order of elements in an array.
10.Write a function to find the sum of all the elements in an array.
11.Write a function to find the subarray with the largest sum.
12.Write a function to find the first non-repeating element in an array.
13.Write a function to find the maximum product of two elements in an array.
14.Write a function to find the number of pairs of elements in an array that add up to a given sum.
15.Write a function to move all zeroes to the end of an array while maintaining the relative order of other
elements.
Megha Gupta Data Structure 4/24/2023 44
Introduction to Array (CO1)

▪ There are two ways to search an element:

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

Megha Gupta Data Structure


4/24/2023 45
Introduction to Array (CO1)

▪ The linear search is a sequential search, which uses a loop to


step through an array, starting with the first element.
▪ It compares each element with the value being searched for,
and stops when either the value is found or the end of the array
is encountered.
▪ If the value being searched is not in the array, the algorithm will
unsuccessfully search to the end of the array.

Megha Gupta Data Structure


4/24/2023 46
Introduction to Array (CO1)

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.

Megha Gupta Data Structure


4/24/2023 47
Introduction to Array (CO1)

Megha Gupta Data Structure


4/24/2023 48
Introduction to Array(CO1)

Megha Gupta Data Structure 4/24/2023 49


Introduction to Array(CO1)

Megha Gupta Data Structure


4/24/2023 50
Introduction to Array(CO1)

Megha Gupta Data Structure


4/24/2023 51
Introduction to Array(CO1)

Megha Gupta Data Structure


4/24/2023 52
Introduction to Array(CO1)

Megha Gupta Data Structure


4/24/2023 53
Introduction to Array (CO1)

Algorithm – Linear Search

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)

Algorithm – Linear Search (Another example)


Linear Search ( Array Arr, Value a ) // Arr is the name of the array, and a is the
searched element.

Step 1: Set i to 0 // i is the index of an array which starts from 0

Step 2: if(i > n) then go to step 7 // n is the number of elements in array

Step 3: if (Arr[i] = a) then go to step 6

Step 4: Set i to i + 1

Step 5: Goto step 2

Step 6: Print element a found at index i and go to step 8

Step 7: Print element not found

Step 8: Exit
Megha Gupta Data Structure
4/24/2023 55
Introduction to Array (CO1)

Python Program – Linear Search


def LinearSearch(L, element):
n = len(L)
for i in range(n):
if L[i] == element:
return i
return -1
myList = [1, 23, 45, 23, 34, 56, 12, 45, 67, 24]
print("Given list is:", myList)
position = LinearSearch(myList, 12)
print("Element 12 is at position:", position)

Megha Gupta Data Structure


4/24/2023 56
Introduction to Array (CO1)

How long will our search take?

▪ 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.

So the search takes an amount of time proportional to the


length of the array. O(n)

Megha Gupta Data Structure


4/24/2023 57
Introduction to Array (CO1)

▪ In the average case, the target value is somewhere in the array.


▪ In fact, since the target value can be anywhere in the array, any
element of the array is equally likely.
▪ So on average, the target value will be in the middle of the array.
▪ So the search takes an amount of time proportional to half the
length of the array.

Megha Gupta Data Structure


4/24/2023 58
Introduction to Array (CO1)

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)

Megha Gupta Data Structure


4/24/2023 60
Introduction to Array(CO1)

Megha Gupta Data Structure


4/24/2023 61
Introduction to Array (CO1)

Megha Gupta Data Structure


4/24/2023 62
Introduction to Array (CO1)

Binary Search Algorithm

binarySearch(arr, x, low, high)


repeat till low = high
mid = (low + high)/2
if (x == arr[mid])
return mid

else if (x > arr[mid]) // x is on the right side


low = mid + 1

else // x is on the left side


high = mid - 1

Megha Gupta Data Structure


4/24/2023 63
Introduction to Array (CO1)

Binary Search Program in python


def binary_search(arr, x): # Test array
low = 0 arr = [ 2, 3, 4, 10, 40 ]
high = len(arr) - 1 x = 10
mid = 0
while low <= high: # Function call
result = binary_search(arr, x)
mid = (high + low) // 2
if result != -1:
# If x is greater, ignore left half print("Element is present at index",
if arr[mid] < x: str(result))
low = mid + 1 else:
print("Element is not present in array")
# If x is smaller, ignore right half
elif arr[mid] > x:
high = mid - 1

# means x is present at mid


else:
return mid
# If we reach here, then the element was not present
return -1
Megha Gupta Data Structure
4/24/2023 64
Introduction to Array(CO1)

At each iteration, the array is divided by half.


So let’s say the length of array at any iteration is Therefore
n Length of array = n⁄2k = 1
At Iteration 1, => n = 2k
Length of array = n 10 Applying log function on both
At Iteration 2, sides:
Length of array = n⁄2 5 => log2 (n) = log2 (2k)
At Iteration 3, => log2 (n) = k log2 (2)
Length of array = (n⁄2)⁄2 = n⁄22 2 => k = log2 (n)
Hence the time complexity of
Therefore, after Iteration k,
Binary Search is
Length of array = n⁄2k 1

Also, we know that after


log2 (n)
After k divisions, the length of array becomes 1

Megha Gupta Data Structure


4/24/2023 65
Introduction to Array (CO1)

▪ Multidimensional array declaration


type name[size1][size2]...[sizeN];

▪ For example, the following declaration creates a three dimensional


integer array −
int threedim[5][10][4];

Megha Gupta Data Structure


4/24/2023 66
Introduction to Array(CO1)

▪ An array of arrays is known as 2D array.


▪ The two dimensional (2D) -A matrix can be
represented as a table of rows and columns.

Megha Gupta Data Structure


4/24/2023 67
Introduction to Array(CO1)

Megha Gupta Data Structure 4/24/2023 68


Introduction to Array(CO1)

Megha Gupta Data Structure


4/24/2023 69
Introduction to Array(CO1)

Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as


given:
Row Major System:
Address of A [ I1 ][ I2 ] = B + W * [( I1 – L1 ) * N2+ ( I2 – L2 )]
Column Major System:
Address of A [ I1 ][ I2 ] Column Major Wise = B + W * [( I1 – L1 ) + N1 * ( I2 – L2 )]

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)

Multi-dimensional Array in Python


# Python program to demonstrate printing
# of complete multidimensional list
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
print(a)

Output:[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

Accessing with the help of loop.


# Python program to demonstrate printing
# of complete multidimensional list row
# by row.
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
for record in a:
print(record)

Megha Gupta Data Structure


4/24/2023 71
Introduction to Array(CO1)

Accessing using square brackets.


# Python program to demonstrate that we
# can access multidimensional list using
# square brackets
a = [ [2, 4, 6, 8 ],
O/P:
[ 1, 3, 5, 7 ],
[ 8, 6, 4, 2 ],
2468
[ 7, 5, 3, 1 ] ]
1357
8642
for i in range(len(a)) :
7531
for j in range(len(a[i])) :
print(a[i][j], end=" ")
print()

Megha Gupta Data Structure


4/24/2023 72
Introduction to Array(CO1)

Methods on Multidimensional Array


1. append(): Adds an element at the end of the list.
Example:

# Adding a sublist

a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]


a.append([5, 10, 15, 20, 25])
print(a)
Output:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]

Megha Gupta Data Structure


4/24/2023 73
Introduction to Array(CO1)

2. extend(): Add the elements of a list (or any iterable), to the end of the current
list.

# Extending a sub list

a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]


a[0].extend([12, 14, 16, 18])
print(a)
Output:
[[2, 4, 6, 8, 10, 12, 14, 16, 18], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

Megha Gupta Data Structure


4/24/2023 74
Introduction to Array(CO1)

3. reverse(): Reverses the order of the list.

# Reversing a sublist

a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]


a[2].reverse()
print(a)
Output:
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [20, 16, 12, 8, 4]]

Megha Gupta Data Structure


4/24/2023 75
Introduction to Array(CO1)

▪ 1. Which of these best describes an array?


a) A data structure that shows a hierarchical behavior
b) Container of objects of similar types
c) Arrays are immutable once initialized
d) Array is not a data structure

▪ Answer: b

Megha Gupta Data Structure 4/24/2023 76


Introduction to Array(CO1)

▪ 2. Assuming int is of 4bytes, what is the size of int arr[15];?


a) 15
b) 19
c) 11
d) 60

▪ Answer: d

Megha Gupta Data Structure 4/24/2023 77


Introduction to Array(CO1)

▪ Elements in an array are accessed _____________


a) randomly
b) sequentially
c) exponentially
d) logarithmically

▪ Answer a.

Megha Gupta Data Structure 4/24/2023 78


Introduction to Array(CO1)

▪ Suppose listExample is [5, 3, 8, 15, 4], what is list1 after


listExample.extend([12, 5])?
▪ a) [5, 3, 8, 15, 4]
b) [12, 5, 5, 3, 8, 15, 4]
c) [5, 3, 8, 15, 4, 12, 5]
d) [ [5, 3, 8, 15, 4] [12, 5] ]

▪ Ans C.

Megha Gupta Data Structure 4/24/2023 79


Introduction to Array(CO1)

L= [4,21,13,14,52]
for i in L:
if(i%2==0):
print(i)

O/p: 4,14,52

Megha Gupta Data Structure 4/24/2023 80


Sorting Using Array(CO1)

Bubble Sort is the simplest sorting algorithm that works by repeatedly


swapping the adjacent elements if they are in wrong order.

Megha Gupta ACSE0301 DS


Unit 1
Sorting Using Array(CO1)

Bubble sort Illustration

Megha Gupta ACSE0301 DS Unit 1


Sorting Using Array(CO1)

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)

Megha Gupta Data Structure 4/24/2023 83


Sorting Using Array CO1)

Megha Gupta ACSE0301 DS Unit 1


Sorting Using Array CO1)

Insertion Sort
Algorithm
1. Set a marker for the sorted section, after the first
element.

2. Repeat the following until unsorted section is


empty:

a) Select the first unsorted element

b)Swap other elements to the right to create the


correct position and shift the unsorted elements

Megha Gupta
c)ACSE0301
Advance the DS
marker
Unit 1
to the right one element.
Sorting Using Array CO1)

Megha Gupta ACSE0301


DS Unit 1
Sorting Using Array CO1)

PYTHON PROGRAM FOR INSERTION SORT


def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
# example usage
arr = [5, 2, 8, 12, 3]
sorted_arr = insertion_sort(arr)
print(sorted_arr) # output: [2, 3, 5, 8, 12]
Megha Gupta Data Structure 4/24/2023 87
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.

The algorithm maintains two subarrays in a given array.


▪ The subarray which is already sorted.
▪ Remaining subarray which is unsorted.

1. Select the lowest element in the remaining array


2. Bring it to the starting position
3. Change the counter for unsorted array by one.

Megha Gupta ACSE0301


DS Unit 1
Sorting Using Array CO1)

Selection sort

Megha Gupta ACSE0301


DS Unit 1
Sorting Using Array CO1)

Megha Gupta ACSE0301 DS Unit 1


Sorting Using Array CO1)

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

Megha Gupta Data Structure 4/24/2023 91


Sorting Using Array CO1)

▪ Merge sort is a divide-and-conquer algorithm that sorts an array or list by dividing


it into two halves, sorting each half recursively, and then merging the sorted halves
back together. It works as follows:

▪ 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.

Megha Gupta Data Structure 4/24/2023 92


Sorting Using Array CO1)

▪ 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.

Megha Gupta Data Structure 4/24/2023 93


Sorting Using Array CO1)

Megha Gupta Data Structure 4/24/2023 94


Sorting Using Array CO1)

def mergeSort(arr, l, r):


if l < r:
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print("Given array is")
for i in range(n):
print("%d" % arr[i],end=" ")
mergeSort(arr, 0, n-1)
print("\n\nSorted array is")
for i in range(n):
print("%d" % arr[i],end=" ")
Megha Gupta Data Structure 4/24/2023 95
Sorting Using Array CO1)

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

Megha Gupta Data Structure 4/24/2023 96


Sorting Using Array CO1)

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)

Megha Gupta Data Structure 4/24/2023 97


Sorting Using Array CO1)

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?

Megha Gupta Data Structure 4/24/2023 98


Introduction to Stack

A stack is a data structure in which


items can be inserted only from one
end and get items back from the
same end.

There , the last item inserted into


stack, is the the first item to be taken
out from the stack. In short its also
called Last in First out [LIFO].

Megha Gupta Data Structure 4/24/2023 99


Introduction to Stack

● A Stack of book on table.

● Token stack in Bank.

● Stack of trays and plates.

Megha Gupta Data Structure 4/24/2023 100


Introduction to Stack

Top: Open end of the stack is called Top, From this end item can
be inserted.

Push: To insert an item from Top of stack is called push operation.


The push operation change the position of Top in stack.

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.

Megha Gupta Data Structure 4/24/2023 101


Introduction to Stack

IsEmpty: Stack considered empty when there is no item on Top.


IsEmpty operation return true when no item in stack else false.

IsFull: Stack considered full if no other element can be inserted on


top of the stack. This condition normally occur when stack
implement ed through array.

Megha Gupta Data Structure 4/24/2023 102


Introduction to 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

Megha Gupta Data Structure 4/24/2023 104


Introduction to Stack
Implementation of Stack

• Using Array

• Using Link List

Megha Gupta Data Structure 4/24/2023 105


Introduction to Stack

Megha Gupta Data Structure 4/24/2023 106


Introduction to Stack

Megha Gupta Data Structure 4/24/2023 107


Introduction to Stack

Megha Gupta Data Structure 4/24/2023 108


Introduction to Stack
stack = []
stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack')
print(stack)

# pop() function to pop element from stack in LIFO order

print('\nElements popped from stack:')


print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')


Megha Gupta print(stack)
Data Structure 4/24/2023 109
Introduction to Stack

Reversing a string: To reverse a string we can use following algorithm.


1. Given the sting and a stack
2. While there is not end of string, do the following.
3. Read a character form the string
4. Push it on the stack
5. End while
6. Re-initialize string position
7. While stack is not Empty, do the following.
8. Pop a character from the stack
9.Insert the character popped into next position in
string.
Megha Gupta Data Structure 4/24/2023 110
10.End While
Introduction to Stack

String is a b c d e f PUSH to SACK


Megha Gupta Data Structure 4/24/2023 111
Introduction to Stack

Reversed String: f e d c b a POP from SACK


Megha Gupta Data Structure 4/24/2023 112
Stack(CO1)

Q1 . In a stack, if a user tries to remove an element from an empty stack it is called


_________
a) Underflow
b) Empty collection
c) Overflow
d) Garbage Collection

Answer. a

Megha Gupta Data Structure 4/24/2023 113


Stack(CO1)

Q2. Consider the usual algorithm for determining whether a sequence of


parentheses is balanced. The maximum number of parentheses that appear on the
stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
a) 1
b) 2
c) 3
d) 4 or more

Answer : c

Megha Gupta Data Structure 4/24/2023 114


Stack(CO1)

Q3. Consider the usual algorithm for determining whether a sequence of


parentheses is balanced. The maximum number of parentheses that appear on the
stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
a) 1
b) 2
c) 3
d) 4 or more

Answer c.

Megha Gupta Data Structure 4/24/2023 115


Introduction to Stack

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...

An expression is a collection of operators and operands that represents a


specific value.

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

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 116


Introduction to Stack
Expression Types
Based on the operator position, expressions are divided into THREE types. They
are as follows...
1.Infix Expression
2.Postfix Expression
3.Prefix Expression

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 117


Introduction to Stack

Infix Expression: An expression in which the


operator is in between its two operands.
A+B
Prefix Expression: An expression in which operator precedes its
two operands is called an prefix expression.

+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

Infix expression can be directly evaluated but the standard


practice in CS is that the infix expression converted to
postfix form and then the expression is evaluated.

During both processes stack is proved to be a useful data


structure.

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 119


Introduction to Stack

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 120


Introduction to Stack

1. Given a expression in the infix form.


2. Find the highest precedence operator
3. If there are more then one operators with the same precedence
check associativity, i.e. pick the left most first.
4. Convert the operator and its operands from infix to postfix
(A + B) → A B+
1. Repeat steps 2 to 4, until all the operators in the given
expression are in the postfix form.
Megha Gupta ACSE0301: DS Unit 2 4/24/2023 121
Introduction to Stack

Q1. Convert the given infix expression 2*3/(2-1)+5*(4-1) to postfix


expression
Sol.

1. Enclosed in brackets, based on precedence and associativity

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)))

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 122


Introduction to Stack
2. Convert each bracket in postfix expression one by one
a. (((2*3)/(2-1))+(5*(4-1)))
b. (((23*)/(2-1))+(5*(4-1)))
c. (((23*)/(21-))+(5*(4-1)))
d. (((23*)/(21-))+(5*(41-)))
e. (((23*)(21-)/)+(5*(41-)))
f. (((23*)(21-)/)+(5(41-)*))
f. (((23*)(21-)/)(5(41-)*)+)

Ans. 23*21-/541-*+

H.W
1. A+B*C-D^E^F

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 123


Introduction to Stack

1. Given a expression in the infix form.


2. Find the highest precedence operator
3. If there are more then one operators with the same
precedence check associativity, i.e. pick the left most first.
4. Convert the operator and its operands from infix to prefix
A+ B --> +A B
5. Repeat steps 2 to 4, until all the operators in the given
expression are in the postfix form.

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 124


Introduction to Stack

Q1. A*B+C/D (Infix) Q2. A*(B+C/D)


((A*B)+(C/D)) (A*(B+(C/D)) )

*AB+C/D A*(B+/CD)

*AB+/CD A*(+B/CD)

+*AB/CD (Prefix) *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

1. Examine the given Input Sequence.


2. If it is operand output it.
3. If it is ‘(‘ push it on the stack.
4. If it is an operator and
a) If the stack is empty push it on the stack.
b) If the top of the stack is ‘(‘ then push it on to the stack.
c) If it has higher priority then top of the stack, push it on to
the stack.
d) Otherwise pop operator from the stack and output it. And
go to step 4.
5. If it is ‘)’ then pop of the operators from the stack and output
them until ‘(‘ is encountered.
6. If there are more input sequence then go to step 1.
7. If there are no more input sequence, pop of remaining
Megha Gupta elements
ACSE0301: fromDS the
Unit 2 stack and output them. 4/24/2023 126
Introduction to Stack

Infix to Postfix using stack



Example A*B+C become AB*C+

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 127


Introduction to Stack

Infix to Postfix using stack ...


Example A * (B + C * D) + E becomes A B C D * + * E +

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 128


Introduction to Stack
((A+B)*D)^(E-F))

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 129


Introduction to Stack
Infix to Prefix using Stack (Convert in Polish
Notation)
1.First, reverse the given infix expression.
2.Scan the characters one by one.
3.If the character is an operand, print it .
4.If the character is a closing parenthesis, then push it to the stack.
5.If the character is an opening parenthesis, pop the elements in the stack until we
find the corresponding closing parenthesis.
6.If the character scanned is an operator
•If the operator has precedence greater than or equal to the top of the stack, push
the operator to the stack.
•If the operator has precedence lesser than the top of the stack, pop the operator and
output it to the prefix notation output and then check the above condition again with
the new top of the stack.
7. After all the characters are scanned, reverse the prefix notation output

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 130


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 ‘(‘.

Step 2: Obtain the postfix expression of the modified expression i.e


CB*A+.

Step 3: Reverse the postfix expression. Hence in our example prefix is


+A*BC.

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 131


Introduction to Stack
Algorithm for Prefix
This is how you convert manually for theory question in the exam

Input String - Infix – ((a/b)+c)-(d+(e*f))

1.String after reversal – ))f*e(+d(-)c+)b/a((


2.Apply postfix
3.Reverse Postfix Expression (Given After the table below)

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 132


Introduction to Stack
Infix – ((a/b)+c)-(d+(e*f)) → ))f*e(+d(-)c+)b/a((

Sr. no. Expression Stack Prefix


0 ) )
1 ) ))
2 f )) f
3 * ))* f
4 e ))* fe
5 ( ) fe*
6 + )+ fe*
7 d )+ fe*d
8 ( fe*d+
9 – - fe*d+
10 ) -) fe*d+
11 c -) fe*d+c
12 + -)+ fe*d+c
13 ) -)+) fe*d+c
14 b -)+) fe*d+cb
15 / -)+)/ fe*d+cb
16 a -)+)/ fe*d+cba
17 ( -)+ fe*d+cba/
18 ( - fe*d+cba/+
19 fe*d+cba/+-

-+/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

Sr. no. Expression Stack Prefix


1 ) )
2 K ) K
3 / )/ K
4 H )/ KH
5 + )+ KH/
6 G )+ KH/G
7 ( KH/G+
8 * * KH/G+
9 F * KH/G+F
10 - - KH/G+F*
11 E - KH/G+F*E
12 / -/ KH/G+F*E
13 ) -/) KH/G+F*E
14 D -/) KH/G+F*ED
15 + -/)+ KH/G+F*ED
16 B -/)+ KH/G+F*EDB
17 ( -/ KH/G+F*EDB+
18 * -/* KH/G+F*EDB+
19 A -/* KH/G+F*EDB+A
20 - KH/G+F*EDB+A*/-

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 134


Introduction to Stack

1) Create a stack to store operands (or values).


2) Scan the given expression and do following for every scanned element.
…..a) If the element is a number, push it into the stack
…..b) If the element is a operator, pop two operands for the operator from
stack. Evaluate the operator and push the result back to the stack
3) When the expression is ended, the number in the stack is the final answer

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 135


Introduction to Stack

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)

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 136


Introduction to Stack

• Recursion is a process by which a function calls itself


repeatedly, until some specified condition has been
satisfied

• The process is used for repetitive computations in which


each action is stated in terms of a previous result.

• To solve a problem recursively, two conditions must be


satisfied.
• First, the problem must be written in a recursive form
• Second the problem statement must include a stopping
condition

Megha Gupta ACSE0301: DS Unit 2 4/24/2023


Introduction to Stack

RECURSIONS

Fun1() Fun2()
{ {

Fun2() Fun1()

} }

Megha Gupta ACSE0301: DS Unit 2 4/24/2023


Introduction to Stack

Head Recursion() Tail Recursion()

Fun() Fun()
{ {
Fun(); …….
……. ……
…… …….
……. Fun();
Head &Tail Recursion()
}
}
Fun()
{
Fun()
...….
……
…….
Fun();

}
Megha Gupta ACSE0301: DS Unit 2 4/24/2023
Introduction to Stack

• There is base condition, that stops further calling of the


function

• Function call itself directly or indirectly, it should reach


towards base condition.

Megha Gupta ACSE0301: DS Unit 2 4/24/2023


Introduction to Stack

factorial of n → (n!) = n * n-1 – n-2* ………*2*1

n!= n* (n-1)! And 0! = 1

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))

Megha Gupta ACSE0301: DS Unit 2 4/24/2023


Introduction to Stack

def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = int(input("Enter the number: "))

# check if the number is negative


if num < 0:
print("Sorry, factorial does not exist for
negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is",
recur_factorial(num))

Megha Gupta ACSE0301: DS Unit 2 4/24/2023


Recursion

Program for Fibonacci numbers

▪ The Fibonacci numbers are the numbers in the following


integer sequence.

▪ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

▪ In mathematical terms, the sequence Fn of Fibonacci


numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1.

Megha Gupta ACSE0301: DS Unit 2


4/24/2023 144
Recursion
def fib_num(n):
if n<=0:
print("Fibonacci can't be computed")
# First Fibonacci number
elif n==1:
return 0
# Second Fibonacci number
elif n==2:
return 1
else:
return fib_num(n-1)+fib_num(n-2)
#input
n=int(input("Enter n: "))
4/24/2023 145
print("{}th Fibonacci
Meghanumber
Gupta is ".format(n),fib_num(n))
ACSE0301: DS Unit 2
Recursion

Megha Gupta ACSE0301: DS Unit 2


4/24/2023 146
Introduction to Stack

• 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

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 148


Recursion

Binary Search Using Recursion


def binary_search(my_list, low, high, elem):
if high >= low:
mid = (high + low) // 2
if my_list[mid] == elem:
return mid
elif my_list[mid] > elem:
return binary_search(my_list, low, mid - 1, elem)
else:
return binary_search(my_list, mid + 1, high, elem)
else:
return -1
Megha Gupta ACSE0301: DS Unit 2
4/24/2023 149
Recursion

my_list = [ 1, 9, 11, 21, 34, 54, 67, 90 ]


elem_to_search = 1
print("The list is")
print(my_list)

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

Tower of Hanoi is a mathematical puzzle where we have three rods


and n disks.

Megha Gupta ACSE0301: DS Unit 2 15 4/24/2023


1
Introduction to Stack

The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple rules:

1) Only one disk can be moved at a time.

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.

3) No disk may be placed on top of a smaller disk.

Megha Gupta ACSE0301: DS Unit 2 15 4/24/2023


2
Introduction to Stack

Megha Gupta ACSE0301: DS Unit 2 15 4/24/2023


3
Introduction to Stack

Megha Gupta ACSE0301: DS Unit 2 15 4/24/2023


4
Introduction to Stack

def TowerOfHanoi(n , source, destination, auxiliary):


if n==1:
print ("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)

# Driver code
n=3
TowerOfHanoi(n,'A','B','C')
# A, C, B are the name of rods

Megha Gupta ACSE0301: DS Unit 2 15 4/24/2023


5
Introduction to Stack
Recursive Tree

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 156


Introduction to Stack

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 157


Introduction to Stack

Megha Gupta ACSE0301: DS Unit 2 4/24/2023 158


Recursion
▪ Difference Between Recursion and Iteration

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.

Megha Gupta ACSE0301: DS Unit 2


4/24/2023 161
Queue

• Queue is Linear Data Structure


• It follows First In First Out(FIFO) principal
• It has two pointers front and rear e.g.:
Front Rear

Megha Gupta Data Structure 4/24/2023 162


Queue

1. Using Array
2. Using Link List

Application of Queue

Queues are used in a lot of applications, few of them are:

•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

Megha Gupta Data Structure 4/24/2023 163


Queue

A[0] A[1] A[2] A[3] A[4]


F=R=(-1)

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

Megha Gupta Data Structure 4/24/2023 165


Queue

Insertion:
Algorithm:

Step 1: If REAR = MAX – 1 then


Write “Queue is Overflow”
Goto step 4
[End of IF]
Step 2: IF FRONT=-1 and REAR=-1
SET FRONT=REAR=0
ELSE
SET REAR=REAR+1
[END OF IF]
Step 3: SET QUEUE [REAR] = NUM
Step 4: EXIT
Megha Gupta Data Structure 4/24/2023 166
Queue

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

Megha Gupta Data Structure 4/24/2023 167


Queue

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

Megha Gupta Data Structure 4/24/2023 168


Queue

Deletion:
Algorithm:

Step 1: IF FRONT = -1 OR FRONT>REAR


Write “Queue is Underflow”
ELSE
SET VAL=QUEUE [FRONT]
FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT

Megha Gupta Data Structure 4/24/2023 169


Queue
Python Program

n=int(input("Enter the size of Queue:"))


A=[]
while(True):
print("Select the Operation:")
print("1.Enqueue 2.Dequeue 3. Display 4. Quit")
num = int(input())
if(num == 1):
val = int(input("Enter the element:"))
A.append(val)
elif(num == 2):
A.pop(0)
elif(num == 3):
for i in range(len(A)):
print(A[i],"")
elif(num == 4):
break
Megha Gupta Data Structure 4/24/2023 170
Queue

1. Circular Queue
2. Priority Queue
3. Deque
4. Multiple Queue

Megha Gupta Data Structure 4/24/2023 171


Queue

• Problem:
– Wastage of memory in standard queue in DEQUEUE
operation

Megha Gupta Data Structure 4/24/2023 172


Queue

• The Arrangement of the elements Q[0], Q[1], ..,Q[n] in a


circular fashion with Q[1] following Q[n] is called Circular
Queue.

• The last node is connected to first node to


make a circle.

• Initially, Both Front and Rear pointers points to


the beginning of the array.

• It is also known as “Ring Buffer”.


Megha Gupta Data Structure 4/24/2023 173
Queue

Megha Gupta Data Structure 4/24/2023 174


Queue

Step 1 - Check whether Circular queue is FULL. Front == (Rear+1)%Max

Step 2 - If it is FULL, then display "Queue is FULL!!! Insertion is not


possible!!!" and terminate the function.

Step 3 - If it is NOT FULL, then check Front == -1,


then Front =0.

Step 4 - Rear = (Rear+1)%max, set Cqueue[Rear] = value.

Megha Gupta Data Structure 4/24/2023 175


Queue

Step 1 - Check whether queue is EMPTY. (front == -1)

Step 2 - If it is EMPTY, then display “Circular Queue is EMPTY!!! Deletion is


not possible!!!" and terminate the function.

Step 3 - Val = Cqueue[front];


Step 4 – if(front==rear)
front = rear = -1;
Step 5 – front = (front+1)%Max;
Step 6 – return Val
Megha Gupta Data Structure 4/24/2023 176
Queue

Traffic light functioning is the best example for circular queues. The colors in
the traffic light follow a circular pattern.

In page replacement algorithms, a circular list of pages is maintained and


when a page needs to be replaced, the page in the front of the queue will be
chosen.

Megha Gupta Data Structure 4/24/2023 177


Queue

display() - Displays the elements of a Circular Queue

We can use the following steps to display the elements of a circular queue...

Step 1 - Check whether queue is EMPTY. (front == -1)


Step 2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the
function.
Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i =
front'.
Step 4 – for(i = front; i!=rear; i = (i+1)%Max)
Print Cqueue[i];
end
print(queue[rear]);
Step 5 - Exit

Megha Gupta Data Structure 4/24/2023 178


Queue
Python program to implement circular
queue
def getInput():
return int(input("Select a operation 1.Enqueue 2.Dequeue 3.Display 4.Quit "))
class circularQueue():
def __init__(self,size):
self.size=size
self.queue=[None for i in range(size)]
self.front=self.rear= -1
def enqueue(self):
data=int(input("Enter Element "))
if(self.rear+1)%self.size==self.front:
print(" Queue is Full")
elif self.front== -1:
self.front=0
self.rear=0
self.queue[self.rear]=data
else:
self.rear=(self.rear+1)%self.size
self.queue[self.rear]=data
Megha Gupta Data Structure 4/24/2023
179
Queue
Python program to implement circular queue (cont….)

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")

Megha Gupta Data Structure 4/24/2023 180


Queue
Python program to implement circular queue (cont….)

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")

Megha Gupta Data Structure 4/24/2023 181


Queue
Python program to implement circular queue (cont….)

size=int(input("Enter size of Queue "))


q=circularQueue(size)
while True:
op=getInput()
if op==1:
q.enqueue()
elif op==2:
q.dequeue()
elif op==3:
q.display()
else:
break

Megha Gupta Data Structure 4/24/2023 182


Queue

• In priority queue, each element is assigned a priority.


• Priority of an element determines the order in which the
elements will be processed.
• Rules:
1. An element with higher priority will processed
before an element with a lower priority.
2. Two elements with the same priority are
processed on a First Come First Serve basis.

Megha Gupta Data Structure 4/24/2023 183


Queue

Priority Queue

DATA PRIORTY
NUMBER
A 5
B 1
D 3
E 2
F 8
G 6

Megha Gupta Data Structure 4/24/2023 184


Queue

1. Ascending Priority Queue


In this type of priority queue, elements can be inserted
into any order but only the smallest priority element can
be removed.

2. Descending Priority Queue


In this type of priority queue, elements can be inserted
into any order but only the largest priority element can be
removed.

Megha Gupta Data Structure 4/24/2023 185


Queue

Insertion Operation:
• While inserting elements in priority queue we will add it at
the appropriate position depending on its priority

• It is inserted in such a way that the elements are always


ordered either in Ascending or descending sequence

Megha Gupta Data Structure 4/24/2023 186


Queue

Array Insertion of Priority Queue

DATA PRIORTY DATA PRIORTY


NUMBER NUMBER
A 5 B 1
B 1 E 2
D 3 D 3
E 2 A 5
F 8 G 6
G 6 F 8

Megha Gupta Data Structure 4/24/2023 187


Queue

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.

Megha Gupta Data Structure 4/24/2023 189


Queue

Here we set-
Lower is the
number higher is
the priority.

Megha Gupta Data Structure 4/24/2023 190


Queue

* Tuple is used to set priority of data

Megha Gupta Data Structure 4/24/2023 191


Queue

1. Prim's algorithm implementation can be done using priority queues.

2. Dijkstra's shortest path algorithm implementation can be done using


priority queues.

3. A* Search algorithm implementation can be done using priority queues.

4. Priority queues are used to sort heaps.

5. Priority queues are used in operating system for load balancing and
interrupt handling.

6. Priority queues are used in huffman codes for data compression.

7. In traffic light, depending upon the traffic, the colors will be given priority.
Megha Gupta Data Structure 4/24/2023 192
Queue

• A list in which elements can be inserted or deleted either end


• It is also known as “Head-Tail Linked List”
• It has two pointers LEFT and RIGHT, which point to either end
of the deque.
• Deque (Doubly Ended Queue) in Python is implemented
using the module “collections“. Deque is preferred over a list
in the cases where we need quicker append and pop
operations from both the ends of the container, as deque
provides an O(1) time complexity for append and pop
operations as compared to a list that provides O(n) time
complexity.

Megha Gupta Data Structure 4/24/2023 193


Queue

• Input Restricted Deque:-


In this dequeue, insertion can be done only at one of the
end, while deletion can be done from both ends.

• Output Restricted Deque:-


In this dequeue, deletion can be done only at one of the
ends, while insertions can be done on both ends

Megha Gupta Data Structure 4/24/2023 194


Queue

Input Restricted Deque

Megha Gupta Data Structure 4/24/2023 195


Queue

Output Restricted Deque

Megha Gupta Data Structure 4/24/2023 196


Queue
# importing "collections" for deque operations
import collections
# initializing deque
de = collections.deque([1, 2, 3])
print("deque: ", de)

# using append() to insert element at right end


# inserts 4 at the end of deque
de.append(4)

# printing modified deque


print("\nThe deque after appending at right is : ")
print(de)

# using appendleft() to insert element at left end inserts 6 at the beginning of deque
de.appendleft(6)

# printing modified deque


print("\nThe deque after appending at left is : ")
print(de)
Megha Gupta Data Structure 4/24/2023 197
Queue
# importing "collections" for deque operations
import collections
# initializing deque
de = collections.deque([1, 2, 3])
print("deque: ", de)
# using pop() to delete element from right end
# deletes 4 from the right end of deque
de.pop()
# printing modified deque
print("\nThe deque after deleting from right is : ")
print(de)
# using popleft() to delete element from left end
# deletes 6 from the left end of deque
de.popleft()
# printing modified deque
print("\nThe deque after deleting from left is : ")
print(de)

Megha Gupta Data Structure 4/24/2023 198


Queue

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.

2.Another common application of the deque is storing a software application's list of


undo operations.

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.

Megha Gupta Data Structure 4/24/2023 199


Queue

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

Megha Gupta Data Structure 4/24/2023 200


Queue

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

Megha Gupta Data Structure 4/24/2023 201


Queue

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)

Megha Gupta Data Structure 4/24/2023 202


Stacks and Queue

1. Write a function to implement a queue using two stacks.


2. Write a function to reverse a stack using another stack as a buffer.
3. Write a function to implement a stack that can also return
the minimum element in O(1) time complexity.
4. Write a function to check whether a given sequence of push and pop operations on a
stack is valid.
5. Write a function to implement a queue using two stacks such that enqueue
operation takes O(1) time complexity and dequeue operation takes O(n) time
complexity.
6. Write a function to implement a queue using two stacks such that enqueue and
dequeue operations both take O(1) time complexity.
7. Write a function to implement a queue using a single stack and no other data
structure.
Megha Gupta Data Structure 4/24/2023 203
8. Write a function to implement a stack using a single queue and no other data
Linked List
▪ Linked List can be defined as collection of objects called
nodes that are randomly stored in the memory.
▪ 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.
▪ The last node of the list contains pointer to the null.

4/24/2023 204
Megha Gupta Data Structure
Linked List

• A linked list is a linear data structure.


• Nodes make up linked lists.
• Nodes are structures made up of data and a pointer to another node.
• Usually the pointer is called next.

4/24/2023 205
Megha Gupta Data Structure
Introduction to Linked List

Linked List

• The elements of a linked list are not stored in adjacent memory


locations as in arrays.

• It is a linear collection of data elements, called nodes, where the


linear order is implemented by means of pointers.

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.

• A node in this type of linked list contains two types of fields


• data: which holds a list element
• next: which stores a link (i.e. pointer) to the next node in the list.

Megha Gupta Data Structure 4/24/2023 207


Linked List Representation

• Linked list can be visualized as a chain of nodes, where


every node points to the next node.

• As per the above illustration, following are the important


points to be considered.
– Linked List contains a link element called first.
– Each link carries a data field(s) and a link field called
next.
– Each link is linked with its next link using its next link.
– Last link carries a link as null to mark the end of the list.
4/24/2023 208
Megha Gupta Data Structure
Properties of linked list

• The nodes in a linked list are not stored contiguously in the memory

• You don’t have to shift any element in the list

• Memory for each node can be allocated dynamically whenever the need
arises.

• The size of a linked list can grow or shrink dynamically

Megha Gupta Data Structure 4/24/2023 209


Basic Operations on Linked List

▪ Following are the basic operations supported by a list.


▪ Insertion − Adds an element at the beginning of the list.
▪ Deletion − Deletes an element at the beginning of the list.
▪ Display − Displays the complete list.
▪ Search − Searches an element using the given key.
▪ Delete − Deletes an element using the given key.

4/24/2023 210
Megha Gupta Data Structure
Arrays & Linked list

Arrays Linked list

Fixed size: Resizing is expensive Dynamic size

Insertions and Deletions are inefficient: Insertions and Deletions are efficient: No
Elements are usually shifted shifting

Random access i.e., efficient indexing No random access


→ Not suitable for operations requiring accessing
elements by index such as sorting

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

▪ Following are the various types of linked list.


▪ Singly Linked List − Item navigation is forward only.
▪ Doubly Linked List − Items can be navigated forward and
backward.
▪ Circular Linked List − Last item contains link of the first
element as next
▪ Circular Doubly Linked List − Last item contains link of
the first element as next and the first element has a link to
the last element as previous. Items can be navigated
forward and backward.

4/24/2023 212
Megha Gupta Data Structure
Singly Linked list

• A singly linked list is a dynamic data structure which may grow or


shrink, and growing and shrinking depends on the operation made.

• 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.

data next data next data next

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

# Linked List class (Linking the nodes of linked list)


class LinkedList:
# Function to initialize the Linked List object
def __init__(self):
self.head = None

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

Megha Gupta Data Structure 4/24/2023 217


Creation and Traversal of single linked list
(contd..)
# print method for the linked list
def printlinklist(self):
if(self.head==None):
print("linklist is empty")
else:
curr = self.head
while(curr!=None):
print(curr.data)
curr = curr.next
# Singly Linked List with insertion and print methods
SLL = LinkedList()
SLL.printlinklist()
SLL.insert(5)
SLL.insert(6) Output
SLL.insert(7)
SLL.printlinklist()

4/24/2023 218
Megha Gupta Data Structure
Insertion in a Single Linked List

▪ There are three possible positions where we can enter a new


node in a linked list –
▪ Insertion at beginning
▪ Insertion at end
▪ Insertion at given position

▪ Adding a new node in linked list is a more than one step


activity.

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

Megha Gupta Data Structure 4/24/2023 221


Insertion in single linked list (at
beginning)
# print method for the linked list (contd..)
def printLL(self):
current = self.head
if(current!=None):
print("The List Contains:",end="\n")
while(current):
print(current.data)
current = current.next
else:
print("List is Empty.")

# Singly Linked List with insertion and print methods


LL = LinkedList()
LL.insert_beg(3)
LL.insert_beg(4)
LL.insert_beg(5)
LL.printLL()

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

Megha Gupta Data Structure 4/24/2023 224


Insertion in single linked list (at end) (contd..)
# print method for the linked list
def printLL(self):
current = self.head
if(current!=None):
print("The List Contains:",end="\n")
while(current):
print(current.data)
current = current.next
else:
print("List is Empty.")
# Singly Linked List with insertion and print methods
LL = LinkedList()
LL.insert_end(3)
LL.insert_end(4)
LL.insert_end(5)
LL.printLL()
4/24/2023 225
Megha Gupta Data Structure
Insertion in a Single Linked List
(at given position)
▪ Insertion at given position

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

Megha Gupta Data Structure 4/24/2023 227


Insertion in single linked list (at position)
# insertion method for the linked else:
list at given position
current=self.head
for i in range(1, pos-1):
def insert_position(self, data,
pos): current = current.next
newNode = Node(data) if(current!=None):
newNode.next=current.next
if(pos<1):
current.next=newNode
print("\nPosition should be
>=1.") else:
print("\nInvalid Pos.")
elif(pos==1):
newNode.next=self.head
self.head=newNode

Megha Gupta Data Structure 4/24/2023 228


Insertion in single linked list (at position)
# print method for the linked list # Singly Linked List with insertion
def printLL(self): and print methods
current = self.head LL = LinkedList()
LL.create(2)
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.insert_position(9, 4)
current = current.next LL.printLL()
else:
print("List is Empty.")

Megha Gupta Data Structure 4/24/2023 229


Deletion in a Single Linked List

▪ There are three possible positions where we can enter a new


node in a linked list –
▪ Deletion at beginning
▪ Deletion at end
▪ Deletion from given position

▪ Deleting new node in linked list is a more than one step


activity.

4/24/2023 230
Megha Gupta Data Structure
Deletion in Single Linked List (from beginning)

▪ Deletion 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

Megha Gupta Data Structure 4/24/2023 232


Deletion in Single Linked List (from beginning)
#Delete first node of the list # print method for the linked list
def del_beg(self): def printLL(self):
if(self.head == None): current = self.head
if(current!=None):
print("Underflow-Link List is
empty") print("The List
Contains:",end="\n")
while(current):
else: print(current.data)
temp = self.head current = current.next
self.head = self.head.next else:
print("the deleted element is", print("List is Empty.")
temp.data)
temp = None

Megha Gupta Data Structure 4/24/2023 233


Deletion in Single Linked List (from beginning)
# Singly Linked List with deletion and print
methods
LL = LinkedList()
LL.create(3)
LL.create(4)
LL.create(5)
LL.printLL()
LL.del_beg()
LL.printLL()

Megha Gupta Data Structure 4/24/2023 234


Deletion in Single Linked List (from end)

▪ Deletion from end

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

Megha Gupta Data Structure 4/24/2023 236


Deletion in Single Linked List (from end)
#Delete last node of the list # print method for the linked list
def del_end(self): def printLL(self):
if(self.head == None): current = self.head
print("Underflow-Link List is if(current!=None):
empty")
print("The List
Contains:",end="\n")
else: while(current):
temp = self.head print(current.data)
while(temp.next!=None): current = current.next
prev=temp else:
temp=temp.next print("List is Empty.")
prev.next=None
print("The deleted element is",
temp.data)
temp = None
Megha Gupta Data Structure 4/24/2023 237
Deletion in Single Linked List (from end)
# Singly Linked List with deletion and print
methods
LL = LinkedList()
LL.create(3)
LL.create(4)
LL.create(5)
LL.printLL()
LL.del_end()
LL.printLL()

Megha Gupta Data Structure 4/24/2023 238


Deletion in Single Linked List (from
position)

▪ Deletion from position

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

Megha Gupta Data Structure 4/24/2023 240


Deletion in Single Linked List (from position)
# Deletion method from the linked else:
list at given position temp=self.head
def del_position(self, pos): for i in range(1, pos):
if(pos<1): if(temp!=None):
print("\nPosition should be prev=temp
>=1.") temp=temp.next

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()

Megha Gupta Data Structure 4/24/2023 242


Reverse of a Single Linked List

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

class Node: def push(self, new_data): llist = LinkedList()


def __init__(self, data): new_node = Node(new_data) llist.push(20)
self.data = data new_node.next = self.head llist.push(4)
self.next = None self.head = new_node llist.push(15)
llist.push(85)
class LinkedList: def printList(self):
def __init__(self): temp = self.head print("Original Linked List")
self.head = None while(temp): llist.printList()
print(temp.data,end=" ")
def reverseList(self): temp = temp.next llist.reverseList()
prev = None
current = self.head print("\nReversed Linked List")
while(current is not None): llist.printList()
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
Megha Gupta Data Structure 4/24/2023 244
Singly Circular 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

Megha Gupta Data Structure 4/24/2023 246


Traversal of single circular linked list
# print method for the single circular linked list
def printlinklist(self):
if(self.head==None):
print("linklist is empty")
else:
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
if current_node == self.head:
break
# Singly Linked List with insertion and print methods
CLL = SinglyCircularLinkedList()
CLL.printlinklist()
CLL.insert(5)
CLL.insert(6) Output
CLL.insert(7)
CLL.printlinklist()

4/24/2023 247
Megha Gupta Data Structure
Insertion in a Single Circular Linked List

▪ There are three possible positions where we can enter a new


node in a Single Circular linked list –
▪ Insertion at beginning
▪ Insertion at end
▪ Insertion at given position

▪ Adding a new node in linked list is a more than one step


activity.

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

Megha Gupta Data Structure 4/24/2023 249


Insertion in single circular linked list (at end)
# A single node of a # insertion method for the linked list at
singly linked list end
class Node: def insert_end(self, data):
def __init__(self, data): new_node = Node(data)
self.data = data current_node = self.head
self.next = None new_node.next = self.head
if(self.head==None):
new_node.next = new_node
else:
# A Linked List class
with a single head while(current.next!=self.head):
node current = current.next
class LinkedList: current.next = newNode
def __init__(self):
self.head = None

Megha Gupta Data Structure 4/24/2023 250


Insertion in single circular linked list (at position)
# insertion method for the singly circular
linked list at given position
def insert_position(self, data, pos):
else:
newNode = Node(data) current=self.head
current_node = self.head for i in range(1, pos-1):
new_node.next = self.head current = current.next
if(pos<1):
print("\nPosition should be >=1.") newNode.next=current.next
elif(pos==1): current.next=newNode
if (self.head==None):
new_node.next = new_node
else:
while current_node.next != self.head:
current_node = current_node.next
current_node.next = new_node
self.head = new_node

Megha Gupta Data Structure 4/24/2023 251


Deletion in a Single Circular Linked List

▪ There are three possible positions where we can enter a new


node in a linked list –
▪ Deletion at beginning
▪ Deletion at end
▪ Deletion from given position
▪ Deletion_by_value

▪ Deleting new node in linked list is a more than one step


activity.

4/24/2023 252
Megha Gupta Data Structure
Deletion in Single Circular Linked List (by value)

Megha Gupta Data Structure 4/24/2023 253


Deletion in Single Circular Linked List (from beg)
#Delete first node of the list
def del_beg(self):
if(self.head == None):
print("Underflow-Link List is empty")

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

Megha Gupta Data Structure 4/24/2023 254


Deletion in Single Circular Linked List (from end)
#Delete last node of the singly circular link list
def del_end(self):
if(self.head == None):
print("Underflow-Link List is empty")

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

Megha Gupta Data Structure 4/24/2023 255


Deletion in Single circular Linked List (from position)
# Deletion method from the linked else:
list at given position temp=self.head
def del_position(self, pos): for i in range(1, pos):
if(pos<1): if(temp!=None):
print("\nPosition should be prev=temp
>=1.") temp=temp.next

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

▪ Doubly linked list is a complex type of linked list in which a


node contains a pointer to the previous as well as the next
node in the sequence.
▪ Therefore, in a doubly linked list, a node consists of three
parts: node data, pointer to the next node in sequence (next
pointer) , pointer to the previous node (previous pointer).
▪ A sample node in a doubly linked list is shown in the figure.

4/24/2023 257
Megha Gupta Data Structure
Doubly Linked List

A doubly linked list containing three nodes is shown in the


following image.

4/24/2023 258
Megha Gupta Data Structure
Creating a Node of Doubly Linked List

▪ Create a class for creating a node in a doubly linked list, with


three attributes: the data, previous pointer and next pointer.
The code looks like this:

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

Megha Gupta Data Structure 4/24/2023 261


Creation and Traversal of doubly linked list (contd..)
# print method for the linked list # Singly 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.printLL()
print(current.data)
current = current.next
else:
print("List is Empty.")

4/24/2023 262
Megha Gupta Data Structure
Insertion at the Beginning Linked List

▪ Insertion at the Beginning of Doubly 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

Megha Gupta Data Structure 4/24/2023 264


Insertion at Beginning in Doubly linked list (contd..)
# print method for the linked list # Singly Linked List with creation
def printLL(self): and print methods
current = self.head LL = DoublyLinkedList()
LL.insert_beg(6)
if(current!=None):
LL.insert_beg(5)
print("The List LL.insert_beg(4)
Contains:",end="\n")
LL.insert_beg(3)
while(current!=None):
LL.printLL()
print(current.data)
current = current.next
else:
print("List is Empty.")

4/24/2023 265
Megha Gupta Data Structure
Insertion at the end of Doubly Linked List

▪ 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

Megha Gupta Data Structure 4/24/2023 267


Insertion at end in Doubly linked list (contd..)
# print method for the linked list # Singly Linked List with creation
def printLL(self): and print methods
current = self.head LL = DoublyLinkedList()
LL.insert_end(3)
if(current!=None):
LL.insert_end(4)
print("The List LL.insert_end(5)
Contains:",end="\n")
LL.insert_end(6)
while(current!=None):
LL.printLL()
print(current.data)
current = current.next
else:
print("List is Empty.")

4/24/2023 268
Megha Gupta Data Structure
Insertion in Doubly Linked List (at position)

▪ Insertion at given position in Doubly Linked List

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

Megha Gupta Data Structure 4/24/2023 270


Insertion in Doubly Linked List (at position) (contd..)
# insertion method for the doubly else:
linked list at given position current=self.head
for i in range(1, pos-1):
def insert_position(self, data, if(current!=None):
pos): current=current.next
newNode = Node(data)
if(pos<1): if(current!=None):
print("\nPosition should be newNode.next=current.next
>=1.") current.next.prev=newNode
current.next=newNode
elif(pos==1): newNode.prev=current

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

▪ Similar to single linked list there are three possible positions


where we can enter a new node in a doubly linked list –
▪ Deletion at beginning
▪ Deletion at end
▪ Deletion from given position

▪ Deleting new node in linked list is a more than one step


activity.

4/24/2023 273
Megha Gupta Data Structure
Deletion in Doubly Linked List (from beginning)

▪ Deletion 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

Megha Gupta Data Structure 4/24/2023 275


Deletion in Doubly Linked List (from beginning) (contd..)
#Delete first node of the list # print method for the linked
def del_beg(self): list
if(self.head == None): def printLL(self):
current = self.head
print("Underflow-Link List is empty")
if(current!=None):
else: print("The List
temp = self.head Contains:",end="\n")
self.head = self.head.next while(current!=None):
self.head.prev=None print(current.data)
current =
print("the deleted element is", current.next
temp.data)
else:
temp = None
print("List is Empty.")

4/24/2023 276
Megha Gupta Data Structure
Deletion in Doubly Linked List (from beginning) (contd..)

# Doubly Linked List with creation, deletion and print


methods
LL = DoublyLinkedList()
LL.create(3)
LL.create(4)
LL.create(5)
LL.create(6)
LL.printLL()
LL.del_beg()
LL.printLL()

4/24/2023 277
Megha Gupta Data Structure
Deletion in Doubly Linked List (from end)

▪ Deletion 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

Megha Gupta Data Structure 4/24/2023 279


Deletion in Doubly Linked List (from end) (contd..)
#Delete last node of the list
# print method for the linked
def del_end(self): list
if(self.head == None): def printLL(self):
print("Underflow-Link List is empty") current = self.head
if(current!=None):
else: print("The List
temp = self.head Contains:",end="\n")
while(temp.next!=None): while(current!=None):
prev=temp print(current.data)
temp=temp.next current =
current.next
prev.next=None else:
print("The deleted element is", print("List is Empty.")
temp.data)
temp = None

4/24/2023 280
Megha Gupta Data Structure
Deletion in Doubly Linked List (from end) (contd..)

# Doubly Linked List with creation, deletion and print


methods
LL = DoublyLinkedList()
LL.create(3)
LL.create(4)
LL.create(5)
LL.create(6)
LL.printLL()
LL.del_end()
LL.printLL()

4/24/2023 281
Megha Gupta Data Structure
Deletion in Doubly Linked List (from position)

▪ Deletion from end

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

Megha Gupta Data Structure 4/24/2023 283


Deletion in Doubly Linked List (from position)(contd..)
# Deletion method from the linked list
at given position
if(temp!=None):
def del_position(self, pos):
current.next=temp.next
if(pos<1):
temp.next.prev=current
print("\nPosition should be print("the deleted
>=1.")
element is", temp.data)
temp=None
else:
temp=self.head else:
for i in range(1, pos): print("\nThe position
if(temp!=None): does not exist in link list.")
current=temp
temp=temp.next

4/24/2023 284
Megha Gupta Data Structure
Deletion in Doubly Linked List (from position) (contd..)

# print method for the linked # Doubly Linked List with


list creation, deletion and print
def printLL(self): methods
current = self.head LL = DoublyLinkedList()
if(current!=None): LL.create(3)
print("The List LL.create(4)
Contains:",end="\n") LL.create(5)
while(current!=None): LL.create(6)
print(current.data) LL.create(7)
current = LL.create(8)
current.next LL.printLL()
else: LL.del_position(4)
print("List is Empty.") LL.printLL()

4/24/2023 285
Megha Gupta Data Structure
Deletion in Doubly Linked List (from position) (contd..)

1. How do you check if a linked list is empty?


2. How do you count the number of nodes in a linked list?
3. How do you find the last element of a linked list?
4. How do you check if an element is present in a linked list?
5. How do you insert a node at the end of a linked list?
6. How do you delete the last node of a linked list?
7. How do you insert a node at a given position in a linked list?
8. How do you delete a node from a given position in a linked list?
9. How do you find the nth node from the end of a linked list?
10.How do you merge two sorted linked lists into a single sorted linked list?

Megha Gupta Data Structure 4/24/2023 286


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?

Megha Gupta Data Structure 4/24/2023 287


Tree (CO4)

▪ A tree is a very popular non-linear data structure used


in a wide range of applications. A tree data structure
can be defined as follows...
▪ Tree is a non-linear data structure which organizes data in
hierarchical structure and this is a recursive definition.
OR
▪ Tree data structure is a collection of data (Node) which is
organized in hierarchical structure recursively
▪ In tree data structure, every individual element is
called as Node
▪ In a tree data structure, if we have N number of nodes
then we can have a maximum of N-1 number of links.

Megha Gupta Data Structure


4/24/2023 288
Tree Terminology

▪ 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.

Megha Gupta Data Structure


4/24/2023 289
Tree Terminology

▪ 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.

Megha Gupta Data Structure


4/24/2023 290
Tree Terminology

▪ 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".

Megha Gupta Data Structure


4/24/2023 291
Tree Terminology

▪ 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.

Megha Gupta Data Structure


4/24/2023 292
Tree Terminology

▪ 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

Megha Gupta Data Structure


4/24/2023 293
Tree Terminology

▪ 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.

Megha Gupta Data Structure


4/24/2023 294
Tree Terminology

▪ 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.

Megha Gupta Data Structure


4/24/2023 295
Tree Terminology

▪ 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'

Megha Gupta Data Structure


4/24/2023 296
Tree Terminology

▪ 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).

Megha Gupta Data Structure


4/24/2023 297
Tree Terminology

▪ 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'.

Megha Gupta Data Structure


4/24/2023 298
Tree Terminology

▪ 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'.

Megha Gupta Data Structure


4/24/2023 299
Tree Terminology

▪ 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.

Megha Gupta Data Structure


4/24/2023 300
Tree Terminology

▪ 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.

Megha Gupta Data Structure


4/24/2023 301
Binary Tree (CO3)

▪ In a normal tree, every node can have any number of


children.
▪ A binary tree is a special type of tree data structure in
which every node can have a maximum of 2 children.
▪ One is known as a left child and the other is known as
right child.
▪ A tree in which every node can have a maximum of
two children is called Binary Tree.
▪ In a binary tree, every node can have either 0 children
or 1 child or 2 children but not more than 2 children.

Megha Gupta Data Structure


4/24/2023 302
Trees
Binary Tree(Properties)
1) The maximum number of nodes at level ‘l’ of a binary tree is 2l.
Here level is the number of nodes on the path from the root to the
node (including root and node). Level of the root is 0.
This can be proved by induction.
For root, l = 0, number of nodes = 20 = 1
Assume that the maximum number of nodes on level ‘l’ is 2l
Since in Binary tree every node has at most 2 children, next level
would have twice nodes, i.e. 2 * 2l
2. The Maximum number of nodes in a binary tree of height ‘h’ is 2h+1
– 1.
3. In a Binary Tree with N nodes, minimum possible height or the
minimum number of levels is? log2(N+1) -1

Megha Gupta Data Structure 4/24/2023 303


Binary Tree

▪ Strictly Binary Tree


▪ A binary tree in which every node has either two or
zero number of children is called Strictly Binary Tree
▪ Strictly binary tree is also called as Full Binary Tree
or Proper Binary Tree or 2-Tree

Megha Gupta Data Structure


4/24/2023 304
Binary Tree

▪ Strictly binary tree data structure is used to represent


mathematical expressions.

Megha Gupta Data Structure


4/24/2023 305
Trees
Full Binary Tree

In a Full Binary Tree, number of leaf nodes is the number of


internal nodes plus 1
L=I+1
Where L = Number of leaf nodes, I = Number of internal nodes

Megha Gupta Data Structure 4/24/2023 306


Trees

FULL Binary Tree theorem

Theorem: Let T be a nonempty, full binary tree Then:

(a) If T has I internal nodes, the number of leaves is L = I + 1.

(b) If T has I internal nodes, the total number of nodes is N = 2I + 1.

(c) If T has a total of N nodes, the number of internal nodes is I = (N – 1)/2.

(d) If T has a total of N nodes, the number of leaves is L = (N + 1)/2.

(e) If T has L leaves, the total number of nodes is N = 2L – 1.

(f) If T has L leaves, the number of internal nodes is I = L – 1.

Megha Gupta Data Structure 4/24/2023 307


Binary Tree

▪ Complete Binary Tree


▪ A complete binary tree is a binary tree in which all the
levels are completely filled except possibly the lowest one,
which is filled from the left.
▪ A complete binary tree is just like a full binary tree, but
with two major differences
▪ All the leaf elements must lean towards the left.
▪ The last leaf element might not have a right sibling i.e. a
complete binary tree doesn't have to be a full binary
tree.

Megha Gupta Data Structure


4/24/2023 308
Binary Tree

▪ Extended Binary Tree


▪ The full binary tree obtained by adding dummy nodes to a
binary tree is called as Extended Binary Tree.

Megha Gupta Data Structure


4/24/2023 309
Binary Tree Representation (CO3)

▪ A binary tree data structure is represented using two


methods. Those methods are as follows...
▪ Array Representation
▪ Linked List Representation

▪ Consider the following binary tree...

Megha Gupta Data Structure


4/24/2023 310
Binary Tree Representation

▪ Array Representation of Binary Tree


▪ In array representation of a binary tree, we use one-
dimensional array (1-D Array) to represent a binary tree.
▪ Consider the above example of a binary tree and it is
represented as follows...

▪ To represent a binary tree of depth 'n' using array


representation, we need one dimensional array with a
maximum size of 2n + 1.

Megha Gupta Data Structure


4/24/2023 311
Binary Tree Representation

▪ Linked List Representation of Binary Tree


▪ We use a double linked list to represent a binary tree.
▪ In a double linked list, every node consists of three fields.
▪ First field for storing left child address, second for storing
actual data and third for storing right child address.
In this linked list representation, a node has the following
structure...

Megha Gupta Data Structure


4/24/2023 312
Binary Tree Representation

▪ Linked List Representation of Binary Tree (contd..)


▪ The above example of the binary tree represented using
Linked list representation is shown as follows...

Megha Gupta Data Structure


4/24/2023 313
Binary Tree Traversal (CO3)

▪ Displaying (or) visiting order of nodes in a binary tree is


called as Binary Tree Traversal.
▪ There are three types of binary tree traversals.
▪ In - Order Traversal
▪ Pre - Order Traversal
▪ Post - Order Traversal

▪ Consider the following binary tree...

Megha Gupta Data Structure


4/24/2023 314
Trees

▪ Preorder (Node,Left,Right)
▪ Postorder (Left, Right, Node)
▪ Inorder(Left, Node, Right)

Megha Gupta Data Structure 4/24/2023 315


Trees

(a) Inorder (Left, Node, Right) : 4 2 5 1 3


(b) Preorder (Node, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Node) : 4 5 2 3 1

Megha Gupta Data Structure 4/24/2023 316


Trees

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

Megha Gupta Data Structure 4/24/2023 317


Trees

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.

Megha Gupta Data Structure 4/24/2023 318


Trees

1. Pickup last key of post 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.

3. Create right subtree of root node recursively by selecting keys


which are following the root node in Inorder

Megha Gupta Data Structure 4/24/2023 319


Trees

Inorder: 1 2 3 4 5 7 8
Postorder: 1 3 4 2 7 8 5

Megha Gupta Data Structure 4/24/2023 320


Trees

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.

3. Create right subtree of root node recursively by selecting keys which


are following the root node in Inorder

Megha Gupta Data Structure 4/24/2023 321


Trees

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

Megha Gupta Data Structure 4/24/2023 322


Binary Search Tree (CO3)

▪ Binary Search or ordered binary tree can be defined as a


class of binary trees, in which the nodes are arranged in a
specific order
▪ In a binary search tree, the value of all the nodes in the left
sub-tree is less than the value of the root.
▪ Similarly, value of all the nodes in the right sub-tree is greater
than or equal to the value of the root.
▪ This rule will be recursively applied to all the left and right
sub-trees of the root.

Megha Gupta Data Structure


4/24/2023 323
Trees

Construct all possible Binary Search tree by inserting following keys in


any order.

10, 20,30

Megha Gupta Data Structure 4/24/2023 324


Binary Search Tree

▪ Advantages of using binary search tree


▪ Searching become very efficient in a binary search tree
since, we get a hint at each step, about which sub-tree
contains the desired element.
▪ The binary search tree is considered as efficient data
structure in compare to arrays and linked lists.
▪ In searching process, it removes half sub-tree at every step.
Searching for an element in a binary search tree takes
o(log2n) time. In worst case, the time it takes to search an
element is 0(n).
▪ It also speed up the insertion and deletion operations as
compare to that in array and linked list.

Megha Gupta Data Structure


4/24/2023 325
Binary Search Tree

▪ Operations on Binary Search Tree

SN Operation Description

1 Searching in BST Finding the location of some specific


element in a binary search tree.

2 Insertion in BST Adding a new element to the binary


search tree at the appropriate
location so that the property of BST
do not violate.

3 Deletion in BST Deleting some specific node from a


binary search tree. However, there
can be various cases in deletion
depending upon the number of
children, the node have.

Megha Gupta Data Structure


4/24/2023 326
Binary Search Tree

▪ Creation or Insertion of binary search tree


▪ Create the binary search tree using the following data
elements.
43, 10, 79, 90, 12, 54, 11, 9, 50
▪ Insert 43 into the tree as the root of the tree.
▪ Read the next element, if it is lesser than the root node
element, insert it as the root of the left sub-tree.
▪ Otherwise, insert it as the root of the right of the right sub-
tree.
▪ The process of creating BST by using the given elements, is
shown in next slide

Megha Gupta Data Structure


4/24/2023 327
Binary Search Tree
▪ Creation or Insertion of binary search tree (contd..)

Megha Gupta Data Structure


4/24/2023 328
Binary Search Tree

Case 1 : Deleting the leaf node from BST

Task 1 : Finding key takes either log2(n) or O(n) times.


Task 2 : Identify leaf node parent pointer which is pointing to it
and make it NULL.

Megha Gupta Data Structure 4/24/2023 329


Binary Search Tree

Case 2 : Deleting the node which has only one child

Task 1 : Finding key takes either log2(n) or O(n) times.


Task 2 : Copy the child to the node and delete the child

Megha Gupta Data Structure 4/24/2023 330


Binary Search Tree

Case 3 : Deleting the node which has left subtree or right


subtree.

Task 1 : Finding key takes either log2(n) or O(n) times.


Task 2 : Replace the deleted node with the max of LST or min
of RST.

Megha Gupta Data Structure 4/24/2023 331


Binary Search Tree

Megha Gupta Data Structure 4/24/2023 332


Contd..

Megha Gupta Data Structure 4/24/2023 333


Time Complexity

Operations Best case time Average case Worst case time


complexity time complexity complexity

Insertion O(log n) O(log n) O(n)

Deletion O(log n) O(log n) O(n)

Search O(log n) O(log n) O(n)

Megha Gupta Data Structure


4/24/2023 334
Trees

Post Order Traversal of BST is 10,9,23,22,27,25,15,95,60,40,29.


Find PreOrder traversal.

Megha Gupta Data Structure 4/24/2023 335


Binary Heap
▪ A heap is a complete binary tree, and the binary tree is a tree in
which the node can have atmost two children.
▪ A complete binary tree is a binary tree in which all the levels
except the last level, i.e., leaf node should be completely filled, and
all the nodes should be left-justified.

Megha Gupta Data Structure


4/24/2023 336
Binary Heap
▪ There are two types of the heap:
➢ Min Heap
➢ Max heap

Min Heap
▪ The value of the parent node should be less than or equal to either of
its children.

Megha Gupta Data Structure


4/24/2023 337
Max Heap
▪ The value of the parent node is greater than or equal to its children.

Megha Gupta Data Structure


4/24/2023 338
Insertion in a Heap tree
44, 33, 77, 11, 55, 88, 66

▪ 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.

Megha Gupta Data Structure


4/24/2023 339
Insertion in a Heap tree

Megha Gupta Data Structure


4/24/2023 340
AVL Tree

▪ AVL Tree is invented by GM Adelson - Velsky and EM


Landis in 1962. The tree is named AVL in honor of its
inventors.

▪ AVL Tree can be defined as height balanced binary


search tree in which each node is associated with a
balance factor which is calculated by subtracting the
height of its right sub-tree from that of its left sub-tree.

▪ Tree is said to be balanced if balance factor of each


node is in between -1 to 1, otherwise, the tree will be
unbalanced and need to be balanced.

BalanceFactor = height(left-subtree) − height(right-


subtree)
Megha Gupta Data Structure 4/24/2023 341
AVL Tree

BalanceFactor = height(left-subtree) − height(right-


subtree)
Megha Gupta Data Structure 4/24/2023 342
AVL Tree

Megha Gupta Data Structure 4/24/2023 343


AVL Rotations
▪ We perform rotation in AVL tree only in case if Balance Factor is other
than -1, 0, and 1.
▪ There are basically four types of rotations which are as follows:

➢ L L rotation: Inserted node is in the left subtree of left subtree of A


➢ R R rotation : Inserted node is in the right subtree of right subtree
of A
➢ L R rotation : Inserted node is in the right subtree of left subtree of
A
➢ R L rotation : Inserted node is in the left subtree of right subtree of
A

▪ 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.

Megha Gupta Data Structure 4/24/2023 344


Left Rotation/RR Rotation

▪ If a tree becomes unbalanced, when a node is inserted into the right


subtree of the right subtree, then we perform a single left rotation.
▪ In this example, node A has become unbalanced as a node is inserted
in the right subtree of A's right subtree.
▪ We perform the left rotation by making A the left-subtree of B.

Megha Gupta Data Structure 4/24/2023 345


Right Rotation/LL Rotation

▪ AVL tree may become unbalanced, if a node is inserted in the left


subtree of the left subtree.
▪ The tree then needs a right rotation.
▪ As depicted, the unbalanced node becomes the right child of its
left child by performing a right rotation.

Megha Gupta Data Structure 4/24/2023 346


Right Rotation/LL Rotation

▪ The second type of double rotation is Right-Left Rotation. It is a


combination of right rotation followed by left rotation.
State Action

A node has been inserted into the left


subtree of the right subtree. This makes A, an
unbalanced node with balance factor 2.

First, we perform the right rotation


along C node, making C the right subtree of
its own left subtree B. Now, B becomes the
right subtree of A.

Megha Gupta Data Structure 4/24/2023 347


Right Rotation/LL Rotation

Node A is still unbalanced because


of the right subtree of its right
subtree and requires a left rotation.

A left rotation is performed by


making B the new root node of the
subtree. A becomes the left subtree
of its right subtree B.

The tree is now balanced.

Megha Gupta Data Structure 4/24/2023 348


Trees
Q: Construct an AVL tree having the following elements
H, I, J, B, A, E, C, F, D, G, K, L

1. Insert H, I, J

Megha Gupta Data Structure 4/24/2023 349


Trees
• On inserting the above 2. Insert B, A
elements, especially in the
case of H, the BST becomes
unbalanced as the Balance
Factor of H is -2.
• Since the BST is right-
skewed, we will perform RR
Rotation on node H.
The resultant balance tree is:

Megha Gupta Data Structure 4/24/2023 350


Trees

• On inserting the above elements, especially in case of A, the BST


becomes unbalanced as the Balance Factor of H and I is 2, we consider
the first node from the last inserted node i.e. H.
• Since the BST from H is left-skewed, we will perform LL Rotation on
node H.
The resultant balance tree is:

Megha Gupta Data Structure 4/24/2023 351


Trees

3. Insert E
On inserting E,

BST becomes unbalanced as the


Balance Factor of I is 2, since if we
travel from E to I we find that it is
inserted in the left subtree of right
subtree of I,

we will perform LR Rotation on node


I. LR = RR + LL rotation

Megha Gupta Data Structure 4/24/2023 352


Trees

3 a) We first perform RR rotation on node B


The resultant tree after RR rotation is:

Megha Gupta Data Structure 4/24/2023 353


Trees

3b) We first perform LL rotation on the node I


The resultant balanced tree after LL rotation is:

Megha Gupta Data Structure 4/24/2023 354


Trees

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,

we will perform RL Rotation on


node I. RL = LL + RR rotation.

Megha Gupta Data Structure 4/24/2023 355


Trees

4a) We first perform LL rotation on node E


The resultant tree after LL rotation is:

Megha Gupta Data Structure 4/24/2023 356


Trees

4b) We then perform RR rotation on node B


The resultant balanced tree after RR rotation is:

Megha Gupta Data Structure 4/24/2023 357


Trees

5. Insert G

• On inserting G, BST become unbalanced as the Balance Factor of H is 2,


since if we travel from G to H, we find that it is inserted in the left
subtree of right subtree of H, we will perform LR Rotation on node I.

LR = RR + LL rotation.

Megha Gupta Data Structure 4/24/2023 358


Trees

6. Insert K

• On inserting K, BST becomes unbalanced as the Balance Factor of I is


-2.
• Since the BST is right-skewed from I to K, hence we will perform RR
Rotation on the node I.

Megha Gupta Data Structure 4/24/2023 359


Trees

The resultant balanced tree after RR rotation is:

Megha Gupta Data Structure 4/24/2023 360


Trees

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

Megha Gupta Data Structure 4/24/2023 361


Trees

Deletion in AVL Tree


• Deleting a node from an AVL tree is similar to that in a binary
search tree. Deletion may disturb the balance factor of an AVL tree
and therefore the tree needs to be rebalanced in order to maintain
the AVLness.
• For this purpose, we need to perform rotations.
• The two types of rotations are L rotation and R rotation.

• If the node which is to be deleted is present in the left sub-tree of


the critical node, then L rotation needs to be applied else if, the
node which is to be deleted is present in the right sub-tree of the
critical node, the R rotation will be applied.

• 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:

Megha Gupta Data Structure 4/24/2023 362


Trees
R0 rotation (Node B has balance factor 0 )

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.

Megha Gupta Data Structure 4/24/2023 363


Trees
Example:
Delete the node 30 from the AVL tree 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.

Megha Gupta Data Structure 4/24/2023 364


Trees
R1 Rotation (Node B has balance factor 1)

R1 Rotation is to be performed if the balance factor of Node B is 1. In


R1 rotation, the critical node A is moved to its right having sub-trees
T2 and T3 as its left and right child respectively. T1 is to be placed as
the left sub-tree of the node B.
The process involved in R1 rotation is shown in the following image.

Megha Gupta Data Structure 4/24/2023 365


Trees

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.

Megha Gupta Data Structure 4/24/2023 366


Trees
R-1 Rotation (Node B has balance factor 1)
R-1 rotation is to be performed if the node B has balance factor -1. This case
is treated in the same way as LR rotation. In this case, the node C, which is
the right child of node B, becomes the root node of the tree with B and A as
its left and right children respectively.
The sub-trees T1, T2 becomes the left and right sub-trees of B whereas, T3,
T4 become the left and right sub-trees of A.
The process involved in R-1 rotation is shown in the following image.

Megha Gupta Data Structure 4/24/2023 367


Trees
Example
Delete the node 60 from the AVL tree 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.

Megha Gupta Data Structure 4/24/2023 368


Threaded Binary Tree (CO3)

▪ In a threaded binary tree, NULL pointers are replaced by


references of other nodes in the tree. These extra references
are called as threads.
▪ Threaded Binary Tree is also a binary tree in which all left
child pointers that are NULL (in Linked list representation)
points to its in-order predecessor, and all right child pointers
that are NULL (in Linked list representation) points to its in-
order successor.
▪ If there is no in-order predecessor or in-order successor,
then it points to the root node.

Megha Gupta Data Structure


4/24/2023 369
Threaded Binary Tree (contd..)

▪ To convert the above example binary tree into a threaded


binary tree, first find the in-order traversal of that tree...
▪ In-order traversal of above binary tree...
H-D-I-B-E-A-F-J-C-G

Megha Gupta Data Structure


4/24/2023 370
Threaded Binary Tree (CO3)

▪ In a threaded binary tree, NULL pointers are replaced by


references of other nodes in the tree. These extra references
are called as threads.
▪ Threaded Binary Tree is also a binary tree in which all left
child pointers that are NULL (in Linked list representation)
points to its in-order predecessor, and all right child pointers
that are NULL (in Linked list representation) points to its in-
order successor.
▪ If there is no in-order predecessor or in-order successor,
then it points to the root node.

Megha Gupta Data Structure


4/24/2023 371
Threaded Binary Tree (contd..)

▪ To convert the above example binary tree into a threaded


binary tree, first find the in-order traversal of that tree...
▪ In-order traversal of above binary tree...
H-D-I-B-E-A-F-J-C-G

Megha Gupta Data Structure


4/24/2023 372
Trees

• So far we have assumed that we can store an entire data


structure in main memory
• What if we have so much data that it won’t fit?
• We will have to use disk storage but when this happens our time
complexity fails

Megha Gupta KCS 301: DS Unit 4 4/24/2023 373


Trees

Megha Gupta KCS 301: DS Unit 4 4/24/2023 374


Trees

Megha Gupta KCS 301: DS Unit 4 4/24/2023 375


Trees

Megha Gupta KCS 301: DS Unit 4 4/24/2023 376


Trees

Insertion in the B-Tree


Search the element in the B-Tree is the same manner as in the m-way
search tree.
If the element is not present then search tends to finish at some leaf
node.

Two cases arise-

Case 1. When leaf element is not full then insert element into it.

Case 2. When leaf node is full


a) Insert the element into the node
b) Split the node at its median into two nodes at the same level and
pushing the median element up by one level into the parent node.
c) If parent node accommodating the median element is not full then
exit otherwise repeat the above steps. It may even call the
Megha Gupta rearrangement
KCS 301: DS Unit 4 of keys in the root nodes or the formation of new 4/24/2023 377
root itself.
Trees
Constructing a B Tree

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

Megha Gupta KCS 301: DS Unit 4 4/24/2023 378


Trees
Constructing a B Tree

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

Megha Gupta KCS 301: DS Unit 4 4/24/2023 379


Trees

4. Insert X

5. Insert C

6. Insert L

Megha Gupta KCS 301: DS Unit 4 4/24/2023 380


Trees
7. Insert Z

8. Insert Y

9. Insert T

Megha Gupta KCS 301: DS Unit 4 4/24/2023 381


Trees
10. Insert G

11 Insert J

12 Insert I

Megha Gupta KCS 301: DS Unit 4 4/24/2023 382


Trees

13. Insert D

14. Insert H

Megha Gupta KCS 301: DS Unit 4 4/24/2023 383


Trees
15. Insert R

16. Insert V

Megha Gupta KCS 301: DS Unit 4 4/24/2023 384


Trees

17. Insert E

18. Insert U

Megha Gupta KCS 301: DS Unit 4 4/24/2023 385


Trees

19. Insert F

20. Insert O

Megha Gupta KCS 301: DS Unit 4 4/24/2023 386


Trees

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.

Megha Gupta KCS 301: DS Unit 4 4/24/2023 387


Trees

Delete 6

Megha Gupta KCS 301: DS Unit 4 4/24/2023 388


Trees

6 deleted

Megha Gupta KCS 301: DS Unit 4 4/24/2023 389


Trees

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

Megha Gupta KCS 301: DS Unit 4 4/24/2023 390


Trees

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.

Megha Gupta KCS 301: DS Unit 4 4/24/2023 391


Trees

13 deleted

Megha Gupta KCS 301: DS Unit 4 4/24/2023 392


Trees

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.

Megha Gupta KCS 301: DS Unit 4 4/24/2023 393


Trees

7 deleted

Megha Gupta KCS 301: DS Unit 4 4/24/2023 394


Trees
Case-III
If key k is not present in an internal node x, determine the root of the appropriate
subtree that must contain k. If the root has only t − 1 keys, execute either of the
following two cases to ensure that we descend to a node containing at least t keys.
Finally, recurse to the appropriate child of x.
Case-III-a
If the root has only t−1 keys but has a sibling with t keys, give the root an extra key
by moving a key from x to the root, moving a key from the roots immediate left or
right sibling up into x, and moving the appropriate child from the sibling to x.
Case-III-b
If the root and all of its siblings have t−1 keys, merge the root with one sibling. This involves moving a key down
from x into the new merged node to become the median key for that node.

Megha Gupta KCS 301: DS Unit 4 4/24/2023 395


Trees

After deleting 2

Megha Gupta KCS 301: DS Unit 4 4/24/2023 396


Trees
Interview Questions

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?

Megha Gupta Data Structure 4/24/2023 397


Trees
Interview Questions

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?

8. Can you explain how to serialize and deserialize a binary tree?

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?

Megha Gupta Data Structure 4/24/2023 398


Trees
Interview Questions

Threaded Binary Tree:

1.What is a threaded binary tree?


2.What are the advantages of using threaded binary trees?
3.What are the two types of threaded binary trees?
4.How do you implement an inorder traversal using threaded binary trees?
5.How do you implement a preorder traversal using threaded binary trees?

Megha Gupta Data Structure 4/24/2023 399


Trees
Interview Questions

1.What is an AVL tree?


2.What is the height of an AVL tree?
3.What is the maximum height of an AVL tree?
4.How do you balance an AVL tree?
5.What is the time complexity of searching, insertion, and
deletion in an AVL tree?
6.Can an AVL tree have duplicate keys?

Megha Gupta Data Structure 4/24/2023 400


Trees
Interview Questions

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?

Megha Gupta Data Structure 4/24/2023 401


Graphs

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 is a collection of vertices and arcs in which vertices are


connected with arcs
or
Graph is a collection of nodes and edges in which nodes are
connected with edges

Generally, a graph G is represented as G = ( V, E ), where V is set


of vertices and E is set of edges.

Megha Gupta Data Structure 4/24/2023 402


Graphs
Example
The following is a graph with 5 vertices and 6 edges.
This graph G can be defined as G = ( V , E )
Where V = {A,B,C,D,E} and E =
{(A,B),(A,C)(A,D),(B,D),(C,D),(B,E), (E,D)}.

Megha Gupta Data Structure 4/24/2023 403


Graphs

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)).

Megha Gupta Data Structure 4/24/2023 404


Graphs

Edges are three types.

1.Undirected Edge - An undirected egde is a bidirectional edge.


If there is undirected edge between vertices A and B then edge
(A , B) is equal to edge (B , A).
2.Directed Edge - A directed egde is a unidirectional edge. If
there is directed edge between vertices A and B then edge (A ,
B) is not equal to edge (B , A).
3.Weighted Edge - A weighted egde is a edge with value (cost)
on it.

Megha Gupta Data Structure 4/24/2023 405


Graphs

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.

Megha Gupta Data Structure 4/24/2023 406


Graphs

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.

Megha Gupta Data Structure 4/24/2023 407


Graphs

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.

Megha Gupta Data Structure 4/24/2023 408


Graphs

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.

Megha Gupta Data Structure 4/24/2023 409


Graphs

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.

Megha Gupta Data Structure 4/24/2023 410


Graphs

Graph Representations

Graph data structure is represented using following representations...

1.Adjacency Matrix
2.Incidence Matrix
3.Adjacency List

Megha Gupta Data Structure 4/24/2023 411


Graphs

Adjacency Matrix
In this representation, the graph is represented using a matrix of size
total number of vertices by a total number of vertices.

That means a graph with 4 vertices is represented using a matrix of


size 4X4.

In this matrix, both rows and columns represent vertices.

This matrix is filled with either 1 or 0.

Here, 1 represents that there is an edge from row vertex to column


vertex and 0 represents that there is no edge from row vertex to
column vertex.
Megha Gupta Data Structure 4/24/2023 412
Graphs

UNDIRECTED GRAPH REPRESENTATION...

Directed graph representation...

Megha Gupta Data Structure 4/24/2023 413


Graphs

Incidence Matrix

In this representation, the graph is represented using a matrix of


size total number of vertices by a total number of edges.

That means graph with 4 vertices and 6 edges is represented using


a matrix of size 4X6.

In this matrix, rows represent vertices and columns represents


edges. This matrix is filled with 0 or 1 or -1.

Megha Gupta Data Structure 4/24/2023 414


Graphs
Incidence Matrix

Here, 0 represents that the row edge is not connected to column


vertex

1 represents that the row edge is connected as the outgoing edge to


column vertex and -1 represents that the row edge is connected as
the incoming edge to column vertex.

For example, consider the following directed graph representation...

Megha Gupta Data Structure 4/24/2023 415


Graphs

Adjacency List
In this representation, every vertex of a graph contains list of its
adjacent vertices.

For example, consider the following directed graph representation


implemented using linked list...

This representation can also be implemented using an array as follows..

Megha Gupta Data Structure 4/24/2023 416


Graphs

Graph Traversal – DFS

Graph traversal is a technique used for a searching vertex in a graph. The


graph traversal is also used to decide the order of vertices is visited in the
search process. A graph traversal finds the edges to be used in the search
process without creating loops. That means using graph traversal we visit
all the vertices of the graph without getting into looping path.

There are two graph traversal techniques and they are as follows...
1.DFS (Depth First Search)
2.BFS (Breadth First Search)

Megha Gupta Data Structure 4/24/2023 417


Graphs

DFS (Depth First Search)

DFS traversal of a graph produces a spanning tree as final result.


Spanning Tree is a graph without loops.

We use Stack data structure with maximum size of total


number of vertices in the graph to implement DFS traversal.

Megha Gupta Data Structure 4/24/2023 418


Graphs
DFS (Depth First Search)
We use the following steps to implement DFS traversal...
• Step 1 - Define a Stack of size total number of vertices in the
graph.

• Step 2 - Select any vertex as starting point for traversal. Visit


that vertex and push it on to the Stack.

• Step 3 - Visitany one of the non-visited adjacent vertices of a


vertex which is at the top of stack and push it on to the
stack.

Megha Gupta Data Structure 4/24/2023 419


Graphs

• Step 4 - Repeat step 3 until there is no new vertex to be


visited from the vertex which is at the top of the stack.

• Step 5 - When there is no new vertex to visit then use back


tracking and pop one vertex from the stack.

• Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.

• Step 7 - When stack becomes Empty, then produce final


spanning tree by removing unused edges from the graph

Megha Gupta Data Structure 4/24/2023 420


Graphs
EXAMPLE

Megha Gupta Data Structure 4/24/2023 421


Graphs

Megha Gupta Data Structure 4/24/2023 422


Graphs

Megha Gupta Data Structure 4/24/2023 423


Graphs

Megha Gupta Data Structure 4/24/2023 424


Graphs

Megha Gupta Data Structure 4/24/2023 425


Graphs

Megha Gupta Data Structure 4/24/2023 426


Graphs

Megha Gupta Data Structure 4/24/2023 427


Graphs

Megha Gupta Data Structure 4/24/2023 428


Graphs
Graph Traversal – BFS

Graph traversal is a technique used for searching a vertex in a


graph. The graph traversal is also used to decide the order of
vertices is visited in the search process.

A graph traversal finds the edges to be used in the search process


without creating loops. That means using graph traversal we visit
all the vertices of the graph without getting into looping path.

There are two graph traversal techniques and they are as


follows...
1.DFS (Depth First Search)
2.BFS (Breadth First Search)

Megha Gupta Data Structure 4/24/2023 429


Graphs

BFS (Breadth First Search)

BFS traversal of a graph produces a spanning tree as final result.


Spanning Tree is a graph without loops. We use Queue data
structure with maximum size of total number of vertices in the
graph to implement BFS traversal.

We use the following steps to implement BFS traversal...


• Step 1 - Define a Queue of size total number of vertices in the
graph.
• Step 2 - Select any vertex as starting point for traversal. Visit
that vertex and insert it into the Queue.

Megha Gupta Data Structure 4/24/2023 430


Graphs

• Step 3 - Visit all the non-visited adjacent vertices of


the vertex which is at front of the Queue and insert
them into the Queue.

• 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 5 - Repeat steps 3 and 4 until queue becomes empty.

• Step 6 - When queue becomes empty, then produce final spanning tree by
removing unused edges from the graph.

Megha Gupta Data Structure 4/24/2023 431


Graphs

Megha Gupta Data Structure 4/24/2023 432


Graphs

Megha Gupta Data Structure 4/24/2023 433


Graphs

Megha Gupta Data Structure 4/24/2023 434


Graphs

Queue became Empty, So, stop the BFS process.

Final result of BFS is a Spanning tree as shown below

Megha Gupta Data Structure 4/24/2023 435


Graphs
Spanning Tree

Spanning tree can be defined as a sub-graph of connected,


undirected graph G that is a tree produced by removing the
desired number of edges from a graph.
In other words, Spanning tree is a non-cyclic sub-graph of a
connected and undirected graph G that connects all the vertices
together.
A graph G can have multiple spanning trees.

Megha Gupta Data Structure 4/24/2023 436


S. No. Parameters BFS DFS

1Stands for BFS stands for Breadth First Search. DFS stands for Depth First Search.

BFS(Breadth First Search) uses Queue


data structure for finding the shortest DFS(Depth First Search) uses Stack data
2Data Structure path. structure.

DFS is also a traversal approach in which the


BFS is a traversal approach in which we traverse begins at the root node and
first walk through all nodes on the proceeds through the nodes as far as possible
same level before moving on to the until we reach the node with no unvisited
3Definition next level. nearby nodes.

BFS can be used to find a single source


shortest path in an unweighted graph
because, in BFS, we reach a vertex with In DFS, we might traverse through more
a minimum number of edges from a edges to reach a destination vertex from a
4Technique source vertex. source.

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.

In BFS there is no concept of DFS algorithm is a recursive algorithm that


12Backtracking backtracking. uses the idea of backtracking
BFS is used in various applications
such as bipartite graphs, shortest DFS is used in various applications such as
13Applications paths, etc. acyclic graphs and topological order etc.

14Memory BFS requires more memory. DFS requires less memory.


BFS is optimal for finding the shortest DFS is not optimal for finding the shortest
15Optimality path. path.

17Speed BFS is slow as compared to DFS. DFS is fast as compared to BFS.


When the target is close to the When the target is far from the source, DFS is
18When to use? source, BFS performs better. preferable.
Megha Gupta Data Structure 4/24/2023 438
Spanning Trees

▪ A spanning tree of a graph is just a subgraph that contains all


the vertices and is a tree.
▪ A graph may have many spanning trees.

Graph A Some Spanning Trees from Graph A

Megha Gupta Data Structure


4/24/2023 439
Spanning Trees
Complete Graph All 16 of its Spanning Trees

Megha Gupta Data Structure


4/24/2023 440
Graphs
Spanning Tree

Minimum Spanning Tree

There can be weights assigned to every edge in a weighted graph.


However, A minimum spanning tree is a spanning tree which has
minimal total weight.
In other words, minimum spanning tree is the one which contains
the least weight among all other spanning tree of some particular
graph.

Megha Gupta Data Structure 4/24/2023 441


Graphs

In this section of the tutorial, we will discuss the algorithms to calculate


the shortest path between two nodes in a graph.
There are two algorithms which are being used for this purpose.
o Prim's Algorithm
o Kruskal's Algorithm

Megha Gupta Data Structure 4/24/2023 442


Graphs

Prim's Algorithm

Prim's Algorithm is used to find the minimum spanning tree from a


graph. Prim's algorithm finds the subset of edges that includes every
vertex of the graph such that the sum of the weights of the edges can
be minimized.

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.

Megha Gupta Data Structure 4/24/2023 443


Graphs

Prim's Algorithm
The algorithm is given as follows.
Algorithm

o Step 1: Select a starting vertex


o Step 2: Repeat Steps 3 and 4 until there are fringe vertices
o Step 3: Select an edge e connecting the tree vertex and fringe
vertex that has minimum weight
o Step 4: Add the selected edge and the vertex to the
minimum spanning tree T
[END OF LOOP]
o Step 5: EXIT

Megha Gupta Data Structure 4/24/2023 444


Graphs
Example :
Construct a minimum spanning tree of the graph given in the
following figure by using prim's 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.

Megha Gupta Data Structure 4/24/2023 445


Graphs

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.

Megha Gupta Data Structure 4/24/2023 446


Graphs

Megha Gupta Data Structure 4/24/2023 447


Graphs
Kruskal's Algorithm

Kruskal's Algorithm is used to find the minimum spanning tree for


a connected weighted graph.

The main target of the algorithm is to find the subset of edges by


using which, we can traverse every vertex of the graph.

Kruskal's algorithm follows greedy approach which finds an


optimum solution at every stage instead of focusing on a global
optimum.

Megha Gupta Data Structure 4/24/2023 448


Graphs

The Kruskal's algorithm is given as follows.

Algorithm
o Step 1: Create a forest in such a way that each graph
is a separate tree.

o Step 2: Create a priority queue Q that contains all


the edges of the graph.

o Step 3: Repeat Steps 4 and 5 while Q is NOT EMPTY

Megha Gupta Data Structure 4/24/2023 449


Graphs

o Step 4: Remove an edge from Q

o Step 5: IF the edge obtained in Step 4 connects two


different trees, then Add it to the forest (for combining
two trees into one tree).

ELSE
Discard the edge

Step 6: END

Megha Gupta Data Structure 4/24/2023 450


Graphs

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

Sort the edges according to their weights.

Edge AB DE BC CD AE AC AD
Weight 1 2 3 4 5 7 10

Start constructing the tree; Add AB to the MST;

Add DE to the MST;

Megha Gupta Data Structure 4/24/2023 452


Graphs

Megha Gupta Data Structure 4/24/2023 453


Graphs

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.

Megha Gupta Data Structure 4/24/2023 454


Shortest Path Problems

What is shortest path ?


▪ shortest length between two vertices for an unweighted
graph:
▪ smallest cost between two vertices for a weighted graph:

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?

▪ Model the problem as a graph problem:


▪ Road map is a weighted graph:

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

▪ Shortest-path weight from u to v:


p

δ(u, v) = min w(p) : u v if there exists a path from u to v

∞ otherwise

▪ Shortest path u to v is any path p such that w(p) = δ(u, v)


4/24/2023 457
Variants of Shortest Paths
▪ Single-source shortest path
▪ G = (V, E)  find a shortest path from a given source vertex
s to each vertex v  V
▪ Single-destination shortest path
▪ Find a shortest path to a given destination vertex t from
each vertex v
▪ Reverse the direction of each edge  single-source

▪ Single-pair shortest path


▪ Find a shortest path from u to v for given vertices u and v
▪ Solve the single-source problem

▪ 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}

Megha Gupta Data Structure 4/24/2023 459


Shortest Path Algorithm

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}

Megha Gupta Data Structure 4/24/2023 460


Shortest Path Algorithm
Priority queue → D E F
6 12 11
Solution set (S)= {A,B,C}
Extract min(Queue) = D
S = S U {D}
= {A,B,C,D}

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}

Megha Gupta Data Structure 4/24/2023 461


Shortest Path Algorithm

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}

Source Distance From Source


A A B C D E F
0 2 5 6 12 11

Megha Gupta Data Structure 4/24/2023 462


Dijkstra's Algorithm
Dijkstra's Algorithm

formula for calculating the distance between the


vertices:
if( d(u) + c(u, v) < d(v)):
d(v) = d(u) +c(u, v)

Megha Gupta Data Structure 4/24/2023 463


Dijkstra's Algorithm
Dijkstra's Algorithm

Megha Gupta Data Structure 4/24/2023 464


Dijkstra’s Algorithm
t 1 x

Find the single source shortest path from the  


10 9
2 4
vertex S. s 0 3 6

5 7
 
2
y z

Megha Gupta Data Structure 4/24/2023 465


Dijkstra’s Algorithm

▪ Find shortest path from s to t.

24
2 3
9

s
18
14
2 6
6
30 4 19
11
15 5
5
6
20 16

t
7 44

Megha Gupta Data Structure 4/24/2023 466


Dijkstra’s Pseudo Code
function dijkstra(V,E,W,S)
for each vertex v € V in G
d[V] <- infinite
d[S] <- 0
Q =V
S = NULL

while Q IS NOT EMPTY


u <- Extract MIN from Q
S = S U {u}
for each unvisited neighbour V of U
if d[V] > d[u]+w(u,v)
d[V] <- d[u] + w(u,v)

Megha Gupta Data Structure 4/24/2023 467


Applications of Dijkstra's Algorithm

- Traffic Information Systems are most prominent use


- Mapping (Map Quest, Google Maps)
- Routing Systems

Megha Gupta Data Structure 4/24/2023 468


Applications of Dijkstra's Algorithm

 One particularly relevant this week:


epidemiology

 Prof. Lauren Meyers (MIT, Biology Dept.) uses


networks to model the spread of infectious diseases
and design prevention and response strategies.

Megha Gupta Data Structure 4/24/2023 469


Applications of Dijkstra's Algorithm

 Vertices represent individuals, and edges their


possible contacts. It is useful to calculate how a
particular individual is connected to others.

 Knowing the shortest path lengths to other


individuals can be a relevant indicator of the
potential of a particular individual to infect others.

Megha Gupta Data Structure 4/24/2023 470


Floyd Warshall Algorithm-

•Floyd Warshall Algorithm is a famous algorithm.

•It is used to solve All Pairs Shortest Path Problem.

•It computes the shortest path between every pair of vertices of the given graph.

•Floyd Warshall Algorithm is an example of dynamic programming approach.

Megha Gupta Data Structure 4/24/2023 471


Floyd Warshall Algorithm-

Advantages-
Floyd Warshall Algorithm has the following main advantages-

•It is extremely simple.


•It is easy to implement.

Megha Gupta Data Structure 4/24/2023 472


Floyd Warshall Algorithm-

Floyd Warshall Algorithm is as shown below-

Megha Gupta Data Structure 4/24/2023 473


Floyd Warshall Algorithm-

Time Complexity-

•Floyd Warshall Algorithm consists of three loops over all the nodes.

•The inner most loop consists of only constant complexity operations.

•Hence, the asymptotic complexity of Floyd Warshall algorithm is O(n3).

•Here, n is the number of nodes in the given graph.

Megha Gupta Data Structure 4/24/2023 474


Floyd Warshall Algorithm-

When Floyd Warshall Algorithm Is Used?


•Floyd Warshall Algorithm is best suited for dense graphs.

•This is because its complexity depends only on the number of vertices in the given
graph.

•For sparse graphs, Johnson’s Algorithm is more suitable.

Megha Gupta Data Structure 4/24/2023 475


Floyd Warshall Problem

Problem-

Consider the following directed weighted graph-

Using Floyd Warshall Algorithm, find the shortest path distance between every pair of
vertices.

Megha Gupta Data Structure 4/24/2023 476


Floyd Warshall Algorithm-
Solution-

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:

•Write the initial distance matrix.


•It represents the distance between every pair of vertices in the form of given weights.

Megha Gupta Data Structure 4/24/2023 477


Floyd Warshall Algorithm-

Step-02: (Continue)

•For diagonal elements (representing self-loops), distance


value = 0.
•For vertices having a direct edge between them, distance
value = weight of that edge.
•For vertices having no direct edge between them, distance
value = ∞.
Initial distance matrix for the given graph is-

Megha Gupta Data Structure 4/24/2023 478


Floyd Warshall Algorithm-

Step-03:

Using Floyd Warshall Algorithm, write the following 4 matrices-

Megha Gupta Data Structure 4/24/2023 479


Floyd Warshall Algorithm-

Step-03:

The last matrix D4 represents the shortest path


distance between every pair of vertices.

Megha Gupta Data Structure 4/24/2023 480


Floyd Warshall Algorithm-

Megha Gupta Data Structure 4/24/2023 481


Floyd Warshall Algorithm-

Megha Gupta Data Structure 4/24/2023 482


Floyd Warshall Algorithm-

Megha Gupta Data Structure 4/24/2023 483


Floyd Warshall Algorithm-

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.

Megha Gupta Data Structure 4/24/2023 484


Transitive Closure of a Graph

Transitive Closure of a Graph

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.

The reach-ability matrix is called the Transitive Closure of a Graph.

Transitive closure of graphs is

1111
1111
1111
0001

Megha Gupta Data Structure 4/24/2023 485


Graphs

Interview Questions

What is a graph data structure? How is it different from a tree?


What is a directed graph? What is an undirected graph?
How can you represent a graph in memory? Can you show an example?
How can you traverse a graph? Can you explain the difference between depth-first
search and breadth-first search?
Can you explain Dijkstra's algorithm for finding the shortest path in a weighted
graph? Can you show an example?
What is a cycle in a graph? How can you detect cycles in a graph?

Megha Gupta Data Structure 4/24/2023 486


Graphs

Interview Questions

What is a spanning tree of a graph? Can you explain the difference between a minimum

spanning tree and a maximum spanning tree?

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?

Megha Gupta Data Structure 4/24/2023 487


Graphs

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

one is better for which types of graphs?

Can you explain Kruskal's algorithm for finding the minimum spanning tree in a graph? Can

you show an example?

Megha Gupta Data Structure 4/24/2023 488


Graphs

Interview Questions based on differences

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?

What is the difference between a breadth-first search and a depth-first search in a


graph? Can you explain the advantages and disadvantages of each algorithm?

Megha Gupta Data Structure 4/24/2023 489


Graphs

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

You might also like