DS Workbook 23SC1202

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 199

INDEX

Title of the Programs


Remarks&
Exp. Date
Signature
No
1 Develop a program to implement the sorting techniques.
a. Insertion Sort
b. Shell Sort
2 Develop a program to implement the sorting technique.
a. Quick Sort
b. Merge Sort
3 List Implementation-
a. Singly Linked List

4 List Implementation-(Operations like search,sort,sum)


a. Singly Linked List
5 Circular Linked List
a. Circular Linked List
b. Doubly Linked List
6 Linked Implementation of –
a. Stack

7 Linked Implementation of –
a. Queue
8 Stack Applications–
a. Infix to Postfix Expression Conversion
b. Postfix Expression Evaluation
9 Hashing–
a. Separate chaining
b. Open Addressing
10 Binary search Tree
a. Creation of BST
b. Traversal–In-order, Pre-order, Post-order
11 AVL Tree–Self Balancing Tree

12 Graphs–
a. BFS
b. DFS

Faculty In-charge Course Coordinator HOD/BES-1


Table of contents

Lab Contents Page


Exercise Number
Organization of Students Lab Workbook 6
Start
Lab Continuous Evaluation Plan 7
Pre requisite for Sorting–Shell Sort, Insertion 11
Pre-Lab Task 11
Lab-1 14
In-Lab Task
Post-Lab Task 19
Skill Session 22
Pre requisite for Sorting–Quick Sort, Merge Sort 31
Pre-Lab Task 31
Lab-2 In-Lab Task 34
Post-Lab Task 38
Skill Session 40
Pre requisite for SLL 47
Pre-Lab Task 47
Lab-3
In-Lab Task 48
Post-Lab Task 51
Skill Session 53
Pre requisite for SLL 59
Pre-Lab Task 59
Lab-4 In-Lab Task 60
Post-Lab Task 65
Skill Session 69
Pre requisite for DLL, CLL 76
Pre-Lab Task 76
Lab-5
In-Lab Task 77
Post-Lab Task 81
Skill Session 86
Pre requisite for Stack 97
Lab-6 Pre-Lab Task 97
In-Lab Task 99
Post-Lab Task 102
Skill Session 104
Pre requisite for Queue 111
Pre-Lab Task 111
Lab-7
In-Lab Task 112
Post-Lab Task 117
Skill Session 120
Pre requisite for Stack Applications 132

Lab-8 Pre-Lab Task 132


In-Lab Task 133
Post-Lab Task 136
Skill Session 137
Pre requisite for Hashing 145
Pre-Lab Task 145
Lab-9
In-Lab Task 146
Post-Lab Task 149
Skill Session 151
Pre requisite for BST 161
Pre-Lab Task 161
Lab-10
In-Lab Task 162
Post-Lab Task 165
Skill Session 167
Pre requisite for AVL Tree 177
Pre-Lab Task 177
Lab-11 In-Lab Task 178
Post-Lab Task 181
Skill Session 183
Pre requisite for Graphs 190
Pre-Lab Task 190
Lab-12 In-Lab Task 191
Post-Lab Task 194
Skill Session 196
ORGANIZATION OF THE STUDENTS LAB WORK BOOK

The laboratory framework includes a creative element but shifts the time-
intensive aspects outside of the Two-Hour closed laboratory period.
Within this structure, each laboratory includes three parts: Pre-lab, In-lab,
and post-lab.

a. Pre-Lab

The Pre-lab exercise is a homework assignment that links the lecture with the
laboratory period - typically takes 2 hours to complete. The goal is to
synthesize the information they learn in lecture with material from their
textbook to produce a working piece of software. Pre-lab Students attending
a two-hour closed laboratory are expected to make a good-faith effort to
complete the Pre-lab exercise before coming to the lab. Their work need not
be perfect, but their effort must be real(roughly 80percent correct).

b. In-Lab

The In-lab section takes place during the actual laboratory period. The First
hour of the laboratory period can be used to resolve any problems the students
might have experienced in completing the Pre-lab exercises. The intent is to
give constructive feedback so that students leave the lab with working Pre-
lab software - a significant accomplishment on their part. During the second
hour, students complete the In-lab exercise to reinforce the concepts learned
in the Pre-lab. Students leave the lab having received feedback on their Pre-
lab and In-lab work.

c. Post-Lab

The last phase of each laboratory is a homework assignment that is done


following the laboratory period. In the post-lab, students analyze the
efficiency or utility of a given system call. Each post-lab exercise should take
roughly 120 minutes to complete.

6
2023-24 EVEN SEMESTER LAB CONTINUOUS EVALUATION

Pre- In-Lab(30M)
S. Lab(15 Viva Total Faculty
No Date Experiment Name - (50M) Signature
M)
voce
Logic Implemen Executi Logic Execution Result Analysis
tation (5M) (5M) (5M)
(5M) on (5M) (10M) (10M)
(5M)

7
2023-24 EVEN SEMESTER LAB CONTINUOUS EVALUATION

Pre- In-Lab(30M)
S. Lab(15 Viva Total Faculty
No Date Experiment Name - (50M) Signature
M)
Impleme voce
Logic Executi Logic Execution Result Analysis
ntation (5M) (5M) (5M)
(5M) on(5M) (10M) (10M)
(5M)

10

11

12

Faculty In-Charge Course - Coordinator HOD/BES-I

8
2023-24 EVEN SEMESTER SKILLCONTINUOUS EVALUATION

Skill- Session(50M)
Sl Total Faculty Signature
No Date Experiment Name LOGIC EXECUTION RESULT ANALYSIS (50M)
(20M) (10M) (10M) (10M)

9
23SC1202- DATA STRUCTURES

2023-24 EVEN SEMESTER SKILL CONTINUOUS EVALUATION

Skill Session(50M)
Sl Total Faculty Signature
No Date Experiment LOGIC EXECUTION RESULT ANALYSIS (50M)
Name (20M) (10M) (10M) (10M)

10

11

12

Faculty In-Charge Course Coordinator HOD/BES-I

10
23SC1202- DATA STRUCTURES

WEEK -1

Lab Session:
Date of the Session: / / Time of the Session: ________to_________

Pre requisite:
Mathematical induction
Rudimentary calculus
Basic discrete probability theory
Find whether an element is present in an array.
Find an element in a sorted array.

Pre-Lab Task:
1.Find the time complexity of the following Snippets:
a. sum=0;

for(i=1; i<=n; i++)


{
sum = sum +I;
}
printf(“%d”,sum);

11
23SC1202- DATA STRUCTURES

b. for(int i=1;i<=n; i++)

{
for(int j=1;j<=n;j++)
{
sum = sum + i*j;
}
}
printf(“Sum =%d” , sum);

c. sum=0;

for(int i = 1; i < =n; i*=2)


{
sum++;
}
printf(“Sum =%d”, sum);

12
23SC1202- DATA STRUCTURES

2.In Indian air force 20 – NCC Brigadier Lakshman wants to sort his troop’s corps in ascending order
according to the corps height. So, help Brg. Lakshman to arrange corps accordingly. (Imagine corps
height as elements in array).

Hint: Insertion sort helps to sort array in best time complexity.

Program: -

Sample Input and Output:

13
23SC1202- DATA STRUCTURES

In-lab Task:

1. CARDS GAME (INSERTION SORT-I)

One common task for computers is to sort data. For example, people might want to see all their files on a
computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often
used to introduce the study of algorithms.

Insertion Sort
These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with a
nearly sorted list.

Sample Input

5
24683

Sample Output

24688
24668
24468
23468

Link: https://www.hackerrank.com/challenges/insertionsort1/problem

Program: -

14
23SC1202- DATA STRUCTURES

Sample Input and Output:

15
23SC1202- DATA STRUCTURES

2. Score Sort (Shell Sort)

You work in the examination department of a school, and you've been given a task to sort the
test scores of students in ascending order. The scores are stored in a list where each element
represents the score of a student.

Input Format

The first line contains the integer N, the size of the array. The next line contains N space-
separated integers.

Constraints

• 1<=N<=1000 • -1000<=a[i]<=1000

Link: https://www.hackerrank.com/contests/ds-week-1/challenges/score-sortshell-sort

Program:-

16
23SC1202- DATA STRUCTURES

Sample Input and Output:

17
23SC1202- DATA STRUCTURES

3.Insertion Sort - Part 2


In Insertion Sort Part 1, you inserted one element into an array at its correct sorted position. Using the same
approach repeatedly, can you sort an entire array?
Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted
array, one element at a time? Note that in the first step, when you consider an array with just the first element,
it is already sorted since there's nothing to compare it to.
In this challenge, print the array after each iteration of the insertion sort, i.e., whenever the next element has
been inserted at its correct position. Since the array composed of just the first element is already sorted, begin
printing after placing the second element.
Link: https://www.hackerrank.com/contests/ds-week-1/challenges/insertionsort2
Program:

Sample Input and Output:

18
23SC1202- DATA STRUCTURES

Post-labTask:

1.InsertionSort
You are given an array AA of size NN. Sort the array using Insertion Sort and print the sorted array.

Input
The first line of the input contains a single integer TT denoting the number of test cases. The description of TT
test cases follows.

• The first line of each test case contains a single integer NN.
• The second line contains NN space-separated integers A1,A2,…,ANA1,A2,…,AN.

Output

For each test case print a single line containing NN space-separated integers - the sorted array.

Constraints

• 1≤T≤101≤T≤10
• 1≤N≤1031≤N≤103
• −109≤Ai≤109−109≤Ai≤109

Link: https://www.codechef.com/DSCA2019/problems/NSECDS03

Program:-

19
23SC1202- DATA STRUCTURES

Sample Input and Output:

20
23SC1202- DATA STRUCTURES

2. Sort an Array – Leet Code


Given an array of integers nums, sort the array in ascending order and return it.
You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the
smallest space complexity possible.

Link: https://leetcode.com/problems/sort-an-array/description/
Program:

Sample Input and Output:

21
23SC1202- DATA STRUCTURES

Skill Session:
1.Find the time complexity of the following Snippets:
a. for(i=1; i<=n; i++)
{
j=i;
while( j<i)
{
Printf(“ %d ”, i*j);
}
}

b. i =1;
while(i!=1)
{
sum++;
}
Printf(“%d”, i);

22
23SC1202- DATA STRUCTURES

2.Correctness and the Loop Invariant

In the previous challenge, you wrote code to perform an Insertion Sort on an unsorted array. But how
would you prove that the code is correct? I.e., how do you show that for any input your code will provide
the right output?

Link: https://www.hackerrank.com/challenges/correctness-invariant/problem

Program: -

Sample Input and Output:

23
23SC1202- DATA STRUCTURES

3. Insertion Sort

Given an array sort it using insertion sort and binary search in it to find the position to place the element.
Additionally, you need to count the number of times recursive calls done by binary search function to
find the position.

Link: https://www.codechef.com/problems/BIIN

Program-

Sample Input and Output:

24
23SC1202- DATA STRUCTURES

4. Odd index element sum(Shell sort).

Given a list of N array elements apply shell sort on array. Print the odd index element sum.

Input Format
The first line contains the integer N, the size of the array .

The next line contains N space-separated integers

Constraints
1<= N <= 1000

-1000<= a[i]<= 1000

Output Format

After sorting using shell sort, Print the odd index element sum.

Link: https://www.hackerrank.com/contests/data-structures-week-3/challenges/odd-index-element-
sumshell-sort-
Program: -

25
23SC1202- DATA STRUCTURES

Sample Input and Output:

26
23SC1202- DATA STRUCTURES

5.Sort the People


You are given an array of strings names, and an array heights that consists of distinct positive integers. Both
arrays are of length n.
For each index i, names[i] and heights[i] denote the name and height of the ith person.
Return names sorted in descending order by the people's heights.
Example 1:
Input: names = ["Mary","John","Emma"], heights = [180,165,170]
Output: ["Mary","Emma","John"]
Explanation: Mary is the tallest, followed by Emma and John.
Link: https://leetcode.com/problems/sort-the-people/description/
Program: -

27
23SC1202- DATA STRUCTURES

Sample Input and Output:

28
23SC1202- DATA STRUCTURES

6. Sorting Twist

You all must have used insertion sort somewhere in your life. It is a classical sorting technique. One
variant of insertion sort works as follows when sorting an array a[1...N] in non-descending order:

for i = 2 to N
j=i
while j > 1 and a[j] < a[j - 1]
swap a[j] and a[j - 1]
j = j-1

The pseudocode is simple to follow. In the ith step, element a[i] is inserted in the sorted sequence
a[1...i-1]. This is done by moving a[i] backward by swapping it with the previous element until it ends
up in it's right position.
As you probably already know, the algorithm can be really slow. To study this more, you want to find
out the number of times the swap operation is performed when sorting an array.

Link: https://www.codechef.com/SOPC2012/problems/SOPC03

Program: -

29
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Evaluator’s use only)

30
23SC1202- DATA STRUCTURES

Week-2

Lab Session:

Date of the Session: / / Time of the Session: to

Pre requisite:
▪ Divide and Conquer Algorithm
▪ Sorting
▪ Swapping items in place of partitioning of the array

Pre Lab-Task:
1.Friends and Farewell photo(Using Bucket Sort)

A group of 8 friends of final year B. Tech in KL wanted to take a group photo in their first-year
class room as a memory. When they went to class in FED building, one of the girls remembered
the concept of quick sort and they decided to stand in way that the first girls height is pivot and
all the remaining 7 girls will stand in such a way that, all the girls whose height is less than first
girl’s height will position in the left of the girl and the girls whose height is greater than the
first girl’s height will position towards the right of the first girl.
your task is to print the girls’ heights sorted according to the first girl’s height.

The first line contains n , the number of friends wish to take a


picture The second line contains n integers, heights of n girls

Input

156 151 1 5 3 171 176 168 173 161

Output

151 153 156 161 168 171 173 176

Trace:

31
23SC1202- DATA STRUCTURES

32
23SC1202- DATA STRUCTURES

2. External Sort-Merge Algorithm

External sorting typically uses a hybrid sort-merge strategy. In the sorting phase, chunks of
data small enough to fit in the main memory are read, sorted, and written out to a temporary
file. In the merge phase, the sorted sub-files are combined into a single larger file.

By taking N elements in to array and sort the data using


External sorting algorithm.

Trace:

33
23SC1202- DATA STRUCTURES

In Lab Task
1.Implement Quick sort:

Given a list of N array elements apply Quick sort on array.

There will be two lines of input:

• - the size of the array


• - the n numbers of the array

Print every partitioned sub-array on a new line.


Constraints

• 1<=N<=1000
• -1000<=x<=1000 x belongs to ar

Each number is unique.

Link: https://www.hackerrank.com/challenges/quicksort2/problem

Program: -

34
23SC1202- DATA STRUCTURES

Sample Input and Output:

35
23SC1202- DATA STRUCTURES

2.Quick Sort:

You are given an array AA of size NN. Sort the array using Quick Sort and print the sorted array.
Input
The first line of the input contains a single integer TT denoting the number of test cases. The
description of TT test cases follows.
The first line of each test case contains a single integer NN.
The second line contains N.N space-separated integers A_1, A_2…, A_NA1,A2,…,AN.
Output
For each test case print a single line containing NN space-separated integers - the sorted array.

Link: https://www.codechef.com/DSCA2019/problems/NSECDS06

Program: -

Sample Input and Output:

36
23SC1202- DATA STRUCTURES

3.MERGE SORT

Given a list of N array elementrs apply Merge sort.

*Note: MergeSort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the
two halves and then merges the two sorted halves.
Input Format.
Link:https://www.hackerrank.com/contests/17cs1102/challenges/merge-sort-6/
Program: -

Sample Input and Output:

37
23SC1202- DATA STRUCTURES

Post Lab Task:


1.Sorting Tool
Chaitya is a great problem solver. He found that most of his problems could be solved by arranging them
in a particular order. The problem input consists of N. numbers, smaller than or equal to M. Chaitya’s
analysis consists of sorting this sequence according to their occurrences.

The output must be sorted so that for two numbers A and B, A will appear before B if the number of
times A appears in the original order is larger than the number of times B does. If the number of
occurrences is equal, the number whose value appears sooner in the input should appear sooner in the
sorted sequence.

Help Chaitya by creating a custom sorting tool.

Link:https://www.codechef.com/problems/KJCP01

Program: -

Sample Input and Output:

38
23SC1202- DATA STRUCTURES

2.Merge Similar Items


You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array
items has the following properties:
items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the
ith item.
The value of each item in items is unique.
Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights
of all items with value valuei.
Note: ret should be returned in ascending order by value.

Example 1:
Input: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]Output: [[1,6],[3,9],[4,5]]Explanation:
The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight
= 1 + 5 = 6.
The item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight
= 8 + 1 = 9.
The item with value = 4 occurs in items1 with weight = 5, total weight = 5.
Therefore, we return [[1,6],[3,9],[4,5]].

Link: https://leetcode.com/problems/merge-similar-items/description/

Program: -

Sample Input and Output:

39
23SC1202- DATA STRUCTURES

Skill Problems:
1. Merge Sorted Array
You are given two integer arrays nums1and nums2, sorted in non-decreasing order, and two integers’
m and n, representing the number of elements in nums 1 and nums2 respectively.

Link: https://leetcode.com/problems/merge-sorted-array/

Program: -

Sample Input and Output:

40
23SC1202- DATA STRUCTURES

2. Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number
sorted in non-decreasing order.

Example 1:
Input: nums = [-4,-1,0,3,10]Output: [0,1,9,16,100]Explanation: After squaring, the array becomes
[16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Example 2:
Input: nums = [-7,-3,2,3,11]Output: [4,9,9,49,121]

Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in non-decreasing order.

Link: https://leetcode.com/problems/squares-of-a-sorted-array/description/
Program: -

Sample Input and Output:

41
23SC1202- DATA STRUCTURES

3. Sort the Students by KthScore

There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix score, where
each row represents one student and score[i][j] denotes the score the ith student got in the jth exam. The matrix
score contains distinct integers only.
You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their scores in the kth (0-
indexed) exam from the highest to the lowest.
Return the matrix after sorting it.

Link: https://leetcode.com/problems/sort-the-students-by-their-kth-score/description/

Program: -

Sample Input and Output:

42
23SC1202- DATA STRUCTURES

4. Merge Sort-II
Problem : You must be aware of the sorting technique, called merge sort where we sort an input array by first
dividing it into two halves, and then sorting the each half recursively before finally merging these sorted halves.
A GEU student, Mohan want to understand this recursive algorithm more clearly and is interested to know how
the recursive function calls are getting called during the merge sort program execution for the given input
parameters
- input array (A), begin index (s) and the end index (t).

When the function merge_sort(A,s,t) is called, the recursive functions calls would be executed as per the
input parameters. Mohan is interested to take a snapshot of the function calling stack when merge_sort(A,i,i)
is being executed, where s <= i <= t. Mohan also wants to know the recursive function depth at that point of
time.
Assume that, if the input array consists of odd number of elements then it is divide in such a way that the left
half contains one element more than the right half.

Link: https://www.codechef.com/problems/MRGSRT?tab=statement
Program: -

Sample Input and Output:

43
23SC1202- DATA STRUCTURES

5. Quicksort 1 - Partition

The first line contains, the size of N.


The second line contains space-separated integers (the unsorted array). The first integer, , is the pivot
element, .
Constraints
• 1<=N<=1000
• -1000<=arr[i]<=1000 where 0<=i<n
• All elements are distinct.

Link: https://www.hackerrank.com/challenges/quicksort1/problem

Program: -

Sample Input and Output:

44
23SC1202- DATA STRUCTURES

6. merge sort
A Student named Ramus have given an array of elements to sort in ascending order by her teacher
Lalitha. Ramus is too lazy to sort the elements so he divided the array into two parts and given to two of
his friends. His two friends are also lazy to sort So, each of them has divided the array into two parts and
given to two of their friends. The process continues until each boy gets one element and they finally
merge all the elements. Now your task is to find which person gets which elements.

Input:
• First line will contain a integer n.
• Each testcase contains of a single line of input of n integers.

Output:

• i person is given with these numbers: numbers

Link: https://www.codechef.com/problems/MESO

Program:-

45
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Evaluator’s use only)

46
23SC1202- DATA STRUCTURES

WEEK - 3

Lab Session:

Date of the Session: ___/___ /____ Time of the Session___ to___

Pre-lab:

1. What is a singly linked list? What are the primary components of a node in a singly linked list?

2. List the different types of linked list?

3. Write the operations name which can be perform on singly linked list?

4. How does a singly linked list differ from an array in terms of memory allocation?

5. What is the primary advantage of a singly linked list over an array?

47
23SC1202- DATA STRUCTURES

In-lab:

1.You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new
node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked
list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is
empty.

Link: https://www.hackerrank.com/challenges/insert-a-node-at-the-tail-of-a-linked-list/problem

Program: -

Sample Input and Output:

48
23SC1202- DATA STRUCTURES

2.This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each
node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to
print.

Link: https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list/problem

Program: -

Sample Input and Output:

49
23SC1202- DATA STRUCTURES

3.Reversed Linked List


You are given a linked list that contains N integers, you have to print the elements of linked list in the reverse order.
Input format
• First line: N
• Next line: N space-separated integers that denote elements of the Linked list.
Output format
Print the N elements of the original list.
Link: https://www.hackerrank.com/contests/ds-week3/challenges/reversed-linked-list-3

Program: -

Sample Input and Output:

50
23SC1202- DATA STRUCTURES

Post-Lab:
1.Implement a singly linked list having all unique elements with the following operations.

I 0 x – Inserts element x at the end.


I 1 y x – If the element y exists, then insert element x after the element y, else insert element y before the
existing element x. Assuming either the element x or the element y exists.
I 2 z y x – Inserts element x in the middle of the elements z and y. The element z appears before the
element y.
U x p – Links the next pointer of the element x to the node lying at the pth position from the element x
while traversing towards right. In case of insufficient number of nodes, the counting continues by updating
the existing linked list to its circular version.

Link: https://www.codechef.com/PRACTICE/problems-old/MIDLE003

Program: -

Sample Input and Output:

51
23SC1202- DATA STRUCTURES

2.Given the head of a linked list, Find the number of critical points. (The starting and end are not considered
critical points). Local minima or maxima are called critical points.
A Node is called a local minimum if both next and previous elements are greater than the current element.
A Node is called a local maximum if both next and previous elements are smaller than the current element.
Constraints
• 1≤ Number of elements in the linked list, N ≤105

1. 1≤Node.data≤109

Link: h ttps://www.codechef.com/practice/course/linked-lists/LINKLISTF/problems/CRITLIST

Program:

Sample Input and Output:

52
23SC1202- DATA STRUCTURES

Skill - Session:
1.You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending
order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer
may be null indicating that the list is empty.

Example

head refers to the first node in the list 1→2 →2→3→3→3→3→ NULL.

Remove 1 of the 2 data values and return head pointing to the revised list 1→2 →3 NULL.
Link: https://www.hackerrank.com/challenges/delete-duplicate-value-nodes-from-a-sorted-linked-list/problem
Program: -

Sample Input and Output:

53
23SC1202- DATA STRUCTURES

2.You are given a increasing order sorted singly linked list. You should find the minimum integer in the list
which is greater than or equal to x.

More formally, there is a singly liked list built on an array of n elements. Element with index i contains two
integers: value i is the integer value in this element, and nexti that is the index of the next element of the
singly linked list (or -1, if the current element is the last). The list is sorted, i.e. if next i ≠ - 1, then value next
i > value i.

Link: https://codeforces.com/problemset/problem/843/B

Program:

Sample Input and Output:

54
23SC1202- DATA STRUCTURES

3.Design your implementation of the linked list. You can choose to use a singly or doubly linked list.A node
in a singly linked list should have two attributes: val and next. val is the value of the current node, and next
is a pointer/reference to the next node.If you want to use the doubly linked list, you will need one more
attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-
indexed.

Link: https://leetcode.com/problems/design-linked-list/description/
Program: -

Sample Input and Output:

55
23SC1202- DATA STRUCTURES

4.Given the heads of two singly linked-lists headA and headB, return the node at which the two lists
intersect. If the two linked lists have no intersection at all, return null.

For example, the following two linked lists begin to intersect at node c1:

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

Link: https://leetcode.com/problems/intersection-of-two-linked-lists/description/

Program:

Sample Input and Output:

56
23SC1202- DATA STRUCTURES

5. Find the middle of a given linked list using recursion


Given a singly linked list, find middle of the linked list. For example, if given linked list is 1->2->3->4->5 then
output should be 3.
If there are even nodes, then there would be two middle nodes, we need to print second middle element. For
example, if given linked list is 1->2->3->4->5->6 then output should be 4.
Note: Insert function should add nodes in the linked list.
INPUT: First line No. of Node n in linked list. Second Line Should be n Space Seprated Data of LinkedList.
Output: Output Should be middle element of Linked.
Link: https://www.hackerrank.com/contests/ds-week3/challenges/find-the-middle-of-a-given-linked-list-
using-recursion
Program: -

Sample Input and Output:

57
23SC1202- DATA STRUCTURES

6.Starting from the second node delete all alternate nodes.

Given a Singly Linked List, starting from the second node delete all alternate nodes of it.

Sample Input
10 20 30 40 50 None
Sample Output
10 30 50 None

Link: https://www.hackerrank.com/contests/ds-week3/challenges/starting-from-the-second-node-delete-all-
alternate-nodes-

Program: -

Sample Input and Output:


(For Evaluator’s use only)

58
23SC1202- DATA STRUCTURES

WEEK – 4
Lab Session:

Date of the Session: ___/___ /____ Time of the Session___ to___

Pre-lab:

1.How is a singly linked list different from a doubly linked list?

2.What is the time complexity for inserting an element at the beginning of a singly linked list?

3.How do you find the length of a singly linked list?

4.What is the time complexity for finding an element in a singly linked list?

5.What is the difference between iterative and recursive approaches to traverse a singly linked list?

59
23SC1202- DATA STRUCTURES

In-lab:

1. Middle of the Linked List


Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:

Input: head = [1,2,3,4,5]


Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:

Input: head = [1,2,3,4,5,6]


Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
Link: https://leetcode.com/problems/middle-of-the-linked-list/description/

Program: -

60
23SC1202- DATA STRUCTURES

Sample Input and Output:

61
23SC1202- DATA STRUCTURES

2. Linked List Cycle

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously
following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is
connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Input: head = [3,2,0,-4], pos = 1

Output: true

Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Link: https://leetcode.com/problems/linked-list-cycle/description/

Program: -

62
23SC1202- DATA STRUCTURES

Sample Input and Output:

63
23SC1202- DATA STRUCTURES

3. Remove Friends

After getting her PhD, Christie has become a celebrity at her university, and her facebook profile is full of friend
requests. Being the nice girl she is, Christie has accepted all the requests.
Now Kuldeep is jealous of all the attention she is getting from other guys, so he asks her to delete some of the guys
from her friend list.
To avoid a 'scene', Christie decides to remove some friends from her friend list, since she knows the popularity of
each of the friend she has, she uses the following algorithm to delete a friend.

Link: https://www.hackerrank.com/contests/ds-week3/challenges/

Program: -

Sample Input and Output:

64
23SC1202- DATA STRUCTURES

Post-Lab:
1.Write a C program to implement Single Linked List.(all operations)
Program:-

65
23SC1202- DATA STRUCTURES

Sample Input and Output:

66
23SC1202- DATA STRUCTURES

2.Find the Middle

You are given the head of a singly linked list A of length N. The values in the list are 1, 2,…,
AN respectively. You need to find the value of the middle element of the linked list.
The middle element of a linked list of length N is the ( [N/2]+1)-th element from the head of the list.
Input Format
The first line of the input contains a single integer T - the number of test cases. The description of T test
cases follows.
The first line of each test case contains a single integer N.
The second line of each test case contains N space-separated integers 1, 2,…,AN.

Output Format
For each test case, the function you complete should return the value of the middle element of the list.
Note: You need to complete the function get Middle Element to solve the problem.
Constraints
1≤T≤100
1≤N≤105
1≤Ai≤109 for each valid i
the sum of N over all test cases does not exceed 2 .105

Link:https://www.codechef.com/practice/course/interview-dsa/DSAPREP_08/problems/LLMID

Program:

67
23SC1202- DATA STRUCTURES

Sample Input and Output:

68
23SC1202- DATA STRUCTURES

Skill - Session:

1. Print Linked List


Let's put the learning to use. We already learnt how to traverse a Linked List using a while loop . We have to keep
two things in mind:
1.Take head as the starting reference.
2.Loop till p is not NULL.
Sanad has a problem, he is a beginner to Linked Lists just like you and he needs your help.
Given a linked list fill the function printList() to print the elements of the list. You have to print each element of the
list in a new line.

Link: https://www.hackerrank.com/contests/ds-week3/challenges/print-linked-list-2-1

Program: -

Sample Input and Output:

69
23SC1202- DATA STRUCTURES

2. Delete a node in the middle of a single linked list

Given a linkedlist, for example:-


Input:- A->B->C->D->E
you have to delete node C.
Constraint :- You have only access to the node to be deleted (node C).
Output :- A->B->D->E

Link: https://www.hackerrank.com/contests/ds-week4-1/challenges/delete-node-in-linked-list

Program: -

Sample Input and Output:

70
23SC1202- DATA STRUCTURES

3.Delete Duplicate Nodes from a Linked List


You're given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order.
Delete as few nodes as possible so that the list does not contain any value more than once. The given head pointer
may be null indicating that the list is empty.

Link: https://www.hackerrank.com/contests/ds-week4-1/challenges/delete-duplicate-nodes-from-a-linked-list

Program: -

Sample Input and Output:

71
23SC1202- DATA STRUCTURES

4. Moves the last node to the front

Write a function that moves the last node to the front in a given Singly Linked List.
Sample 1:
Input: 1 → 2 → 3 → 4 → 5
Output: 5 → 1 → 2 → 3 → 4
Sample 2:
Input: 3 → 8 → 1 → 5 → 7 → 12
Output: 12 → 3 → 8 → 1 → 5 → 7

Link: https://www.hackerrank.com/contests/ds-week4-1/challenges/moves-the-node

Program:

Sample Input and Output:

72
23SC1202- DATA STRUCTURES

5. Create and return a new list

Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists.
The new list should be made with its own memory — the original lists should not be changed.
Sample 1:
Input: First linked list: 1 → 2 → 3 → 4 → 6
Second linked list be 2 → 4 → 6 → 8,
Output: 2 → 4 → 6.
The elements 2, 4, 6 are common in both the list so they appear in the intersection list.

Link: https://www.hackerrank.com/contests/ds-week4-1/challenges/create-and-return-a-new-list

Program:

Sample Input and Output:

73
23SC1202- DATA STRUCTURES

6. Returns the value at the Nth node from the end


Given a Linked List and a number N, write a function that returns the value at the Nth node from the end of the
Linked List.
Sample 1:
Input: 10 → 20 → 30 → 40 → 50 → None
N=2
Output: 40

Link: https://www.hackerrank.com/contests/ds-week4-1/challenges

Program:

74
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Evaluator’s use only)

75
23SC1202- DATA STRUCTURES

WEEK -5

Lab Session:

Date of the Session: ___/___ /____ Time of the Session_____ to______

Pre requisite:
• Dynamic Memory Allocation
• Singly Linked List

Pre-lab:
1.Write the node structure definition of a doubly linked list.

2.Draw a sample doubly linked list for the following integers 2 , 5 ,7 , 9,13. Insert each element in the beginning.
13<-> 9<->7<->5<->2<->Null

3.State the advantages of a Doubly linked list over a singly linked list. Also mention few applications
where implementations will be suitable using a DLL.

4.How does a singly linked list differ from a circular linked list in terms of memory allocation?

5.Write the necessary steps to display all the elements of a circularly linked list.

76
23SC1202- DATA STRUCTURES

In-lab Task:

1. Inserting a node into a sorted Doubly Linked List


Given a reference to the head of a doubly-linked list and an integer, create a new DoublyLinkedListNode
object having data value and insert it at the proper location to maintain the sort.
Function Description
Complete the sortedInsert function in the editor below. sortedInsert has two parameters:

• Doubly Linked List Node pointer head: a reference to the head of a doubly-linked list
• int data: An integer denoting the value of the

• field for the Doubly Linked List Node you must insert into the list.

Link: https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem
Program:

Sample Input and Output:

77
23SC1202- DATA STRUCTURES

2.Reverse a Doubly Linked List

Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the
next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of
the reversed list.

Note: The head node might be NULL to indicate that the list is empty.

Function Description

Complete the reverse function in the editor below.

reverse has the following parameter(s):

• Doubly Linked List Node head: a reference to the head of a DoublyLinkedList


Returns - Doubly Linked List Node: a reference to the head of the reversed list

Constraints
• 1<=n<=1000
• 1<=list[i]<=1000 where list[i] is the ith element of the linked list.

Link: https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem

Program:

Sample Input and Output:

78
23SC1202- DATA STRUCTURES

3. Write a c program to find Sum of Elements in CLL

Input Format

The first line of input contains , the number of elements in the linked list. The next n lines contain one
element each, the data values for each node.

Constraints

1 <= n <= 100 1 <= list[i] <=1000

Output Format

Sum of Eelements in CLL

Sample Input 0
5
10 20 5 6 33
Sample Output 0
74
Explanation 0

sum of elements of CLL 10+20+5+6+33=74

Link: http://tinyurl.com/kcvpvne9 (Hacker rank-Sum of Elements in CLL)

Program:

79
23SC1202- DATA STRUCTURES

Sample Input and Output:

80
23SC1202- DATA STRUCTURES

Post-Lab:
1. Write a C program to implement Doubly Linked List (All Operations)
You are given head of the non-empty sorted linked list where the value of the ith node will be Ai.
Your task is to delete all duplicates such that each element appears only once and return the linked list sorted.

Input:

• First line will contain T, number of test cases. Then the test cases follow.
• The first line contains one integer N — the length of the linked list.
• The second line contains N space separated integers A1,A2,…AN — the value of the linked list nodes starting
from the head for the linked list.

Note:

• For Java language, you need to:


Complete the function in the submit solution tab:
Node removeDuplicates(Node head){...}

• For C++ language, you need to:


Complete the function in the submit solution tab:
Node* removeDuplicates(Node* head){...}

• For Python language, you need to:


Complete the function in the submit solution tab:
def Node removeDuplicates(self, head):
Output:

The function you complete should return the required answer.

Constraints

• 1≤T≤10
• 1≤N,Ai≤1051≤N,Ai≤105

Sample 1:

Input
Output
3
5
11688
5
12345
4
5555
168
12345
5

81
23SC1202- DATA STRUCTURES

Explanation:

Test case 1: We will remove duplicate entry of 11, 88. So the sorted linked list will be 1→6→81→6→8.

Test case 2: There is no duplicate entry. So the sorted linked list will be 1→2→3→4→51→2→3→4→5.

Test case 3: We will remove duplicate entry of 55. So the sorted linked list will be 55.
Link: https://www.codechef.com/practice/course/linked-lists/LINKLISTF/problems/PREP55
Program:

82
23SC1202- DATA STRUCTURES

Sample Input and Output:

83
23SC1202- DATA STRUCTURES

2. Write a C program to implement circular linked list (All Operations)

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer
to the head of a linked list, determine if it contains a cycle. If it does, return 1 . Otherwise, return 0.
Example
head refers to the list of nodes 1->2->3->NULL
The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0.
head refers to the list of nodes 1->2->3->1->NULL
There is a cycle where node 3 points back to node 1, so return 1.
Function Description
Complete the has_cycle function in the editor below.
It has the following parameter:
• SinglyLinkedListNode pointer head: a reference to the head of the list

Returns
• Int 1 if there is a cycle or 0 if there is not

Note: If the list is empty, head will be null.


Input Format
The code stub reads from stdin and passes the appropriate argument to your function. The custom test cases format
will not be described for this question due to its complexity. Expand the section for the main function and review the
code if you would like to figure out how to create a custom case.
Constraints
• 0<=list size <=1000

Sample Input
References to each of the following linked lists are passed as arguments to your function:

Sample Output
0
1

Explanation
1. The first list has no cycle, so return 0.

84
23SC1202- DATA STRUCTURES

2. The second list has a cycle, so return 1.

Link: https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle/problem

Program:

Sample Input and Output:

85
23SC1202- DATA STRUCTURES

Skill Session:

1. Design Linked List

Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next
is a pointer/reference to the next node.

If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the
linked list. Assume all nodes in the linked list are 0-indexed.

Implement the MyLinkedList class:

• MyLinkedList() Initializes the MyLinkedList object.


• int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
• void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion,
the new node will be the first node of the linked list.
• void addAtTail(int val) Append a node of value val as the last element of the linked list.
• void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index
equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the
length, the node will not be inserted.
• void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.

Example 1:

Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output
[null, null, null, null, 2, null, 3]

Explanation
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3

Constraints:

• 0 <= index, val <= 1000


• Please do not use the built-in LinkedList library.
• At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.

Link : https://leetcode.com/problems/design-linked-list/

Program:

86
23SC1202- DATA STRUCTURES

Sample Input and Output:

87
23SC1202- DATA STRUCTURES

2. Flatten a Multilevel Doubly Linked List

You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional
child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special
nodes.

Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked
list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the
flattened list.

Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.

Example 1:

Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]


Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Explanation: The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:

Link:https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/

Program:

88
23SC1202- DATA STRUCTURES

Sample Input and Output:

89
23SC1202- DATA STRUCTURES

3.Find the Winner of the Circular Game

There are n friends that are playing a game. The friends are sitting in a circle and are numbered
from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend
for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.
The rules of the game are as follows:
1. Start at the 1st friend.
2. Count the next k friends in the clockwise direction including the friend you started at. The counting wraps
around the circle and may count some friends more than once.
3. The last friend you counted leaves the circle and loses the game.
4. If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately
clockwise of the friend who just lost and repeat.
1. Else, the last friend in the circle wins the game.
Given the number of friends, n, and an integer k, return the winner of the game.

Example 1:

Input: n = 5, k = 2
Output: 3
Explanation: Here are the steps of the game:
1) Start at friend 1.
2) Count 2 friends clockwise, which are friends 1 and 2.
3) Friend 2 leaves the circle. Next start is friend 3.
4) Count 2 friends clockwise, which are friends 3 and 4.
5) Friend 4 leaves the circle. Next start is friend 5.
6) Count 2 friends clockwise, which are friends 5 and 1.
7) Friend 1 leaves the circle. Next start is friend 3.
8) Count 2 friends clockwise, which are friends 3 and 5.
9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.
Example 2:
Input: n = 6, k = 5
Output: 1
Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.

Constraints:
• 1 <= k <= n <= 500
Link: https://leetcode.com/problems/find-the-winner-of-the-circular-game/description/

Program:

90
23SC1202- DATA STRUCTURES

Sample Input and Output:

91
23SC1202- DATA STRUCTURES

3. Linked List Cycle II

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following
the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-
indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1


Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:

Input: head = [1,2], pos = 0


Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:

Input: head = [1], pos = -1


Output: no cycle
Explanation: There is no cycle in the linked list.

Constraints:

The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.

Link: https://leetcode.com/problems/linked-list-cycle-ii/description/

Program:

92
23SC1202- DATA STRUCTURES

Sample Input and Output:

93
23SC1202- DATA STRUCTURES

4.LARGEST ELEMENT IN A DOUBLY LINKED LIST

Given the head of the doubly linked list , traverse the entire list and find the node with the maximum data and also
print the predecessor nodes value.

For example:

If the existing list is 2<->66<->89<->23<->12<->NULL

Print the maximum node value 89 and its predecessor node value 66, so print the output 89 and 66.
Link:https://www.hackerrank.com/contests/week-5-skill-5/challenges/largest-element-in-a-doubly-linked-list

Program:

Sample Input and Output:

94
23SC1202- DATA STRUCTURES

6. DELETE THE ELEMENT FROM A SPECIFIED POSITION IN A DOUBLY LINKED LIST

Problem Description:

Given a reference to the head of a doubly linked list and an integer that specifies the position, the task is to delete the
node from that position. As a preliminary task first validate if the position specified is valid and then perform deletion
operation.
For Example if the list consists of 5 nodes and the position to be deleted is given as 7 then position is not a valid
position , so display a suitable message stating invalid position .

Link:https://www.hackerrank.com/contests/week-5-skill-5/challenges/6-delete-the-element-from-a-specified-
position-in-a-doubly-linked-list

Program:

95
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Valuator’s use only)

96
23SC1202- DATA STRUCTURES

WEEK -6

Lab Session:
Date of the Session: ___/___ /____ Time of the Session_____ to______

Pre requisite:
• Stack – First in last out
• One opening for storing the data
• Initially Top = -1
• Operation – Insertion – Push()
• Operation – Deletion – Pop()
• Applications of stack

Pre-lab:
1. What are the steps involved in pushing an element onto a stack implemented using a linked list, and how does
this process differ from a stack implemented with an array?

2.How does the linked list implementation enhance the dynamic nature of a stack, and what advantages does it offer
over array-based implementations?

3. Can you compare the time and space complexity of basic stack operations (push, pop) in a linked list-based
implementation versus an array-based implementation?

97
23SC1202- DATA STRUCTURES

4. In a linked list-based stack, how is the concept of a "top" pointer utilized, and how does it facilitate efficient push
and pop operations?

5. Explain the role of a stack data structure in ensuring balanced braces in a programming context. How does the
stack track the opening and closing braces to validate their proper pairing?

98
23SC1202- DATA STRUCTURES

In-lab Task:

1. Maximum Element
You have an empty sequence, and you will be given queries. Each query is one of these three types:
1. Push the element x into the stack.
2. Delete the element present at the top of the stack.
3. Print the maximum element in the stack.
Link:https://www.hackerrank.com/challenges/maximum-element/problem?isFullScreen=true

Program:

Sample Input and Output

99
23SC1202- DATA STRUCTURES

2. Waiter
you are a waiter at a party. There is a pile of numbered plates. Create an empty array. At each iteration, , remove
each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible by the prime
number. If it is, stack it in pile . Otherwise, stack it in stack . Store the values in from top to bottom in . In the next
iteration, do the same with the values in stack . Once the required number of iterations is complete, store the
remaining values in in , again from top to bottom. Return the array.

Link: https://www.hackerrank.com/challenges/waiter/problem?isFullScreen=true

Program:

Sample Input and Output

100
23SC1202- DATA STRUCTURES

3.Stacks

Palindrome is a word, phrase, number, or other sequence of characters which reads the same backwards and forwards.
Can you determine if a given string, , is a palindrome?.To solve this challenge, we must first take each character in ,
enqueue it in a queue, and also push that same character onto a stack. Once that's done, we must dequeue the first
character from the queue and pop the top character off the stack, then compare the two characters to see if they are
the same; as long as the characters match, we continue dequeuing, popping, and comparing each character until our
containers are empty (a non-match means isn't a palindrome).

Link: https://www.hackerrank.com/challenges/30-queues-stacks/problem?h_r=internal-search

Program:

Sample Input and Output:

101
23SC1202- DATA STRUCTURES

Post-Lab:

1.Reverse a Stack

Once upon a time, in the realm of programming, there was a magical stack that could only be described using a
mystical singly linked list. Legend had it that the elements within this stack longed for a change in their order – a
reversal that would transform the ordinary into the extraordinary.

The wise developers of the kingdom were summoned to craft a function that would perform this enchanting feat.
They were tasked with invoking the powers of programming to create a spell that would reverse the stack's very
essence.

The function, now known as the "Reverse Incantation," was to be written in the ancient language of code. Its
purpose was to take the stack in its current state and weave a magical algorithm, turning the last into the first and the
first into the last.

(You are given a stack implemented using a singly linked list. Write a function to reverse the stack.)

Link: www.hackerrank.com/ds-week6-postlab-programs

Program:

Sample Input and Output:

102
23SC1202- DATA STRUCTURES

2.Palindrome detector using Stack

The function, known as the "Palindrome Oracle," was to be written in the ancient language of code. Its purpose was
to traverse the linked list, mapping its elements in both directions, and unveil whether the list was a harmonious
palindrome or a mere collection of disconnected characters.

As the lines of code wove their spell, the Palindrome Oracle emerged, ready to shine light on the true nature of the
linked list. With each invocation, the Oracle would whisper tales of symmetry or unravel the secrets of imbalance
within the linked list.(Given a singly linked list, write a function to determine if it forms a palindrome. A palindrome
is a sequence that reads the same forward as backward.)

Link: www.hackerrank.com/ds-week6-postlab-programs
Program:

Sample Input and Output:

103
23SC1202- DATA STRUCTURES

104
23SC1202- DATA STRUCTURES

Skill Session:

1.Equal Stacks
You have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can
change the height of a stack by removing and discarding its topmost cylinder any number of times.

Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means
you must remove zero or more cylinders from the top of zero or more of the three stacks until they are all the same
height, then return the height.

Link: https://www.hackerrank.com/challenges/equal-stacks/problem?isFullScreen=true

Program:

Sample Input and Output:

105
23SC1202- DATA STRUCTURES

2.Implementing Min Stack:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Write a program
to demonstrate the Min Stack

Link: www.hackerrank.com/ds-week6-postlab-programs

Program:

Sample Input and Output:

106
23SC1202- DATA STRUCTURES

3.Give string a S consisting of only (( and )). Find whether S is a valid parenthesis string.

Note: A valid parentheses string is defined as:


• Empty string is valid.
• If P is valid, ()(P) is also valid.
• If P and Q are valid, PQ is also valid.

Link:https://www.codechef.com/practice/course/stacks-and-queues/STAQUEF/problems/PsREP59

Program:

Sample Input and Output:

107
23SC1202- DATA STRUCTURES

4.Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: Any left
parenthesis '(' must have a corresponding two consecutive right parenthesis '))'. Left parenthesis '(' must go before
the corresponding two consecutive right parenthesis '))'. In other words, we treat '(' as an opening parenthesis and '))'
as a closing parenthesis. For example, "())", "())(())))" and "(())())))" are balanced, ")()", "()))" and "(()))" are not
balanced. You can insert the characters '(' and ')' at any position of the string to balance it if needed. Return the
minimum number of insertions needed to make s balanced.

Link:https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/

Program:

Sample Input and Output:

108
23SC1202- DATA STRUCTURES

5.Stack using single linked list

Design and implement a stack data structure using a singly linked list to efficiently manage a collection of elements.
The goal is to create a flexible and dynamic stack that supports standard stack operations while leveraging the
advantages of a linked list structure.

Sample Input Sample


Output
1 3
6 2
push 1 1
push 2
push 3 pop pop
top

Link:www.hackerrank.com/ds-week6-postlab-programs

Program:

109
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Valuator’s use only)

110
23SC1202- DATA STRUCTURES

WEEK -7
Lab Session:
Date of the Session:____/____/____ Time of the Session_____to_____
Pre requisite:
• Queue using Arrays
• Dynamic Memory Allocation
• Singly Linked List

Pre-lab Task:
1. Linked List implementation of Queue has advantages compared to Array implementation of Queue. Implement the
enqueue operation of the Linked Queue.

2. Linked List implementation of Queue has advantages compared to Array implementation of Queue. Implement the
deque operation of the Linked Queue.

111
23SC1202- DATA STRUCTURES

In-lab Task:
1) Implement a Queue using Linked List
Implement a Queue using Linked List with the following operations.
1. Insert
2. Delete (Display "Queue is empty" if queue is empty).
3. Display (Display "NULL" if queue is empty).
4. Exit
Input Format
First line contains the Menu followed Input for given menu.

Constraints
NA
Output Format: Print the output based on the Menu

Link:https://www.hackerrank.com/contests/17cs1102/challenges/7b-implement-a-queue-using-linked-list

Program:

Sample Input and Output:

112
23SC1202- DATA STRUCTURES

2. Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest
elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-
Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest)
is always the first one to be removed.
A basic queue has the following operations:
• Enqueue: add a new element to the end of the queue.
• Dequeue: remove the element from the front of the queue and return it.
In this challenge, you must first implement a queue using two stacks. Then process q queries, where each query is
one of the following 3 types:
1. 1 x: Enqueue element x into the end of the queue.
2. 2: Dequeue the element at the front of the queue.
3. 3: Print the element at the front of the queue.
Input Format
The first line contains a single integer, q, denoting the number of queries.
Each line i of the q subsequent lines contains a single query in the form described in the problem statement above.
All three queries start with an integer denoting the query type, but only query 1 is followed by an additional space-
separated value, x, denoting the value to be enqueued.
Constraints
• 1 ≤ q ≤ 105
• 1 ≤ type ≤ 3
• 1 ≤ |x| ≤ 109
• It is guaranteed that a valid answer always exists for each query of type 3.
Output Format
For each query of type 3, print the value of the element at the front of the queue on a new line.

Link:https://www.hackerrank.com/contests/17cs1102/challenges/queue-using-two-stacks

Program:

113
23SC1202- DATA STRUCTURES

Sample Input and Output:

114
23SC1202- DATA STRUCTURES

3. Queues and Stacks

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backwards and
forwards. Can you determine if a given string, s, is a palindrome?
To solve this challenge, we must first take each character in s, enqueue it in a queue, and also push that same character
onto a stack. Once that's done, we must dequeue the first character from the queue and pop the top character off
the stack, then compare the two characters to see if they are the same; as long as the characters match, we continue
dequeueing, popping, and comparing each character until our containers are empty (a non-match means s isn't a
palindrome).
Write the following declarations and implementations:
1. Two instance variables: one for your stack, and one for your queue.
2. A void pushCharacter(char ch) method that pushes a character onto a stack.
3. A void enqueueCharacter(char ch) method that enqueues a character in the queue instance variable.
4. A char popCharacter() method that pops and returns the character at the top of the stack instance variable.
5. A char dequeueCharacter() method that dequeues and returns the first character in the queue instance
variable.
Input Format
You do not need to read anything from stdin. The locked stub code in your editor reads a single line containing string s.
It then calls the methods specified above to pass each character to your instance variables.
Constraints
• s is composed of lowercase English letters.
Output Format
You are not responsible for printing any output to stdout. If your code is correctly written and s is a palindrome, the
locked stub code will print The word, s, is a palindrome.; otherwise, it will print The word, s, is not a palindrome.

Link:https://www.hackerrank.com/challenges/30-queues-stacks/problem?h_r=internal-search

Program:

115
23SC1202- DATA STRUCTURES

Sample Input and Output:

116
23SC1202- DATA STRUCTURES

Post-lab Task:

1. Code Queue
You are working with a high-class city mall development plan which is based on a full automation system. The owner
has said to you that the entry for movies should be in such a way that all those who have registered for the movie can
enter in easy whereas the one who hasn't registered shall not be allowed.

All technical work has been done and you as a programmer have to develop a queue program in order to meet the
required conditions by the owner. You can perform all the queue operations. During the input, the customer name and
tickets are to be uploaded, and further in the program, the user shall enter its name and ticket number which is to be
checked in the database and the required message is to displayed.

EXAMPLE-
Input:
Name: Bob Ticket num: 9182
Name: Jonny Ticket num: 4568
Data has been uploaded
Output:
Name: Bob Ticket num: 9182
Data found, Enjoy the movie
Name: Jonny Ticket num: 8219
Ticket ID not found, re-register

Link:https://www.codechef.com/problems/KCPROG4

Program:

117
23SC1202- DATA STRUCTURES

Sample Input and Output:

118
23SC1202- DATA STRUCTURES

2. Implement Queue using Stacks

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the
functions of a normal queue (push, peek, pop, and empty).
Implement the MyQueue class:
• void push(int x) Pushes element x to the back of the queue.
• int pop() Removes the element from the front of the queue and returns it.
• int peek() Returns the element at the front of the queue.
• boolean empty() Returns true if the queue is empty, false otherwise.
Notes:
• You must use only standard operations of a stack, which means only push to top, peek/pop from top, size,
and is empty operations are valid.
• Depending on your language, the stack may not be supported natively. You may simulate a stack using a list
or deque (double-ended queue) as long as you use only a stack's standard operations.

Example 1:
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
Link:https://leetcode.com/problems/implement-queue-using-stacks/description/

Program:

Sample Input and Output:

119
23SC1202- DATA STRUCTURES

Skill Session:

1 Circular Queue using Arrays


Implement a Circular Queue using arrays with the following operations.
1. Insert (Display "Queue Overflow" if queue is full).
2. Delete (Display "Queue Underflow" if queue is empty).
3. Display (Display NULL if queue is empty).
4. Exit
*Note: The circular queue is a linear data structure. It follows FIFO principle. In circular queue, the last node is
connected back to the first node to make a circle.

Input Format
First line contains the Menu followed Input for given menu.
Constraints
Array Size is 5
Output Format: Print the output based on the Menu

Link:https://www.hackerrank.com/contests/17cs1102/challenges/7a-circular-queue-using-arryas
Program:

120
23SC1202- DATA STRUCTURES

Sample Input and Output:

121
23SC1202- DATA STRUCTURES

2. Design Front Middle Back Queue

Design a queue that supports push and pop operations in the front, middle, and back.
Implement the FrontMiddleBack class:
• FrontMiddleBack() Initializes the queue.
• void pushFront(int val) Adds val to the front of the queue.
• void pushMiddle(int val) Adds val to the middle of the queue.
• void pushBack(int val) Adds val to the back of the queue.
• int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1.
• int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1.
• int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1.
Notice that when there are two middle position choices, the operation is performed on the frontmost middle position
choice. For example:
• Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5].
• Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6].
Example 1:
Input:
["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle",
"popMiddle", "popBack", "popFront"]
[[], [1], [2], [3], [4], [], [], [], [], []]
Output:
[null, null, null, null, null, 1, 3, 4, 2, -1]

Explanation:
FrontMiddleBackQueue q = new FrontMiddleBackQueue();
q.pushFront(1); // [1]
q.pushBack(2); // [1, 2]
q.pushMiddle(3); // [1, 3, 2]
q.pushMiddle(4); // [1, 4, 3, 2]
q.popFront(); // return 1 -> [4, 3, 2]
q.popMiddle(); // return 3 -> [4, 2]
q.popMiddle(); // return 4 -> [2]
q.popBack(); // return 2 -> []
q.popFront(); // return -1 -> [] (The queue is empty)

Constraints:
• 1 <= val <= 109
• At most 1000 calls will be made to pushFront, pushMiddle, pushBack, popFront, popMiddle, and popBack.

Link:https://leetcode.com/problems/design-front-middle-back-queue/

Program:

122
23SC1202- DATA STRUCTURES

Sample Input and Output:

123
23SC1202- DATA STRUCTURES

3. Number of Visible People in a Queue

There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an
array heights of distinct integers where heights[i] represents the height of the ith person.
A person can see another person to their right in the queue if everybody in between is shorter than both of them. More
formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2],
..., heights[j-1]).
Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the
queue.
Example 1:

Input: heights = [10,6,8,5,11,9]


Output: [3,1,2,1,1,0]
Explanation:
Person 0 can see person 1, 2, and 4.
Person 1 can see person 2.
Person 2 can see person 3 and 4.
Person 3 can see person 4.
Person 4 can see person 5.
Person 5 can see no one since nobody is to the right of them.
Example 2:
Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]

Constraints:
• n == heights.length
• 1 <= n <= 105
• 1 <= heights[i] <= 105
• All the values of heights are unique.

Link:https://leetcode.com/problems/number-of-visible-people-in-a-queue/

Program:

124
23SC1202- DATA STRUCTURES

Sample Input and Output:

125
23SC1202- DATA STRUCTURES

4.Maximum element in Queue

You have been given a sequence A of N digits. Each digit in this sequence ranges from 1 to 10^9 . You need to
perform 2 types of operations on this list: • Add(x): Add element x to the end of the list. • Max(list): Find the
maximum element in the current sequence. For each query of type 2, you need to print the result of that operation.

Input Format

The first line consist of a single integer N denoting the size of the initial sequence. The next line consists of N space
separated integers denoting the elements of the initial sequence. The next line contains a single integer q denoting
the number of queries. The next q lines contains the details of the operation. The first integer type indicates the type
of query. If type(i) ==1, it is followed by another integer x and you need to perform operation of type 1 else
operations of type 2

Constraints

1 ≤ N ≤ 10^5 1 ≤ a[i] ≤ 10^9 1 ≤ q ≤ 10^4

Output Format

For each operation of the second type, print a single integer on a new line.

Sample Input 0

12345

11

12

13

Sample Output 0

Link: https://www.hackerrank.com/contests/ds-week7/challenges/maximum-in-queue

Program:

126
23SC1202- DATA STRUCTURES

Sample Input and Output:

127
23SC1202- DATA STRUCTURES

5. Query on queues

You are given an array containing N integers and you have to answer K queries. Each query contains an integer X
which is the index of the i-tℎ (1 based index) element of the queue. Write a program to determine the following for
each query: • The number of segments containing the index X as the leftmost or the rightmost element. and the
number at the index X is ≥ each element of that segment. Note: Segment formation example: You have 3 numbers 1,
2, and 3. The possible segments for 3 are [3], [2,3] and [1,2,3]. Similarly, the possible segments for 2 are [2],[1,2].

Input Format

First line: T (number of test cases) • First line in each test case: Two space-separated integers N and K • Second line
in each test case: N space-separated integers (denoting the elements of the queue) • Next K lines in each test case: X

Constraints

1 ≤ T ≤50 1 ≤ N, K ≤10^5 1 ≤ Each element of the queues ≤ 10^9 1 ≤ X ≤ N

Output Format

Print the answer to each query.

Sample Input 0

42

4213

Sample Output 0

Link: https://www.hackerrank.com/contests/ds-week7/challenges/query-on-queues

Program:

128
23SC1202- DATA STRUCTURES

Sample Input and Output:

129
23SC1202- DATA STRUCTURES

6. Queue Problem 1

Students are waiting in the queue to buy the movie ticket. You have to find the number of arrangements of queue
such that no. of boys is always greater than no. of girls at any position. For example: BBBGG, BBGBG are valid
arrangements while BGBBG, BBGGB are invalid arrangements in which B denotes a Boy and G denotes a Girl.
Note that every person is considered as a distinct person. Therefore, B1B2G1B3G2 and B1B3G1B2G2 are
considered as distinct arrangements.

Input Format

The first line contains the integer n and m denoting the number of boys and the number of girls respectively.

Constraints

0 < n < 12 0 < m < 12

Output Format

Print the number of possible arrangements satisfying the above conditions.

Sample Input 0

32

Sample Output 0

24

Link: https://www.hackerrank.com/contests/ds-week7/challenges/queue-problem-1-1

Program:

130
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Valuator’s use only)

131
23SC1202- DATA STRUCTURES

WEEK -8
Lab Session:

Date of the Session: ___/___ /____ Time of the Session____ to____

Pre requisite:
• Infix Notation
• Postfix Notation Basic discrete probability theory
• Operators and Precedence Find whether an element is present in an array.
• Stacks
• Parentheses Handling
• Programming Language Basics
• Character Handling (if using a programming language) Find an element in a sorted array.

Pre-Lab Task:

1. convert the infix expression to postfix expression


(a*b)+(c*d)/(e-f)^(y+p)

2. convert the infix expression to a postfix expression

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

3. convert the infix expression to a postfix expression


4+2*(8-6)/3

4. Evaluate the converted expression of question 3.

5. Evaluate the bellow symbols are balancing r not?


((({{{{}}}})))

132
23SC1202- DATA STRUCTURES

In-lab Task:
1. Postfix Expression Evaluation
Implement a program to evaluate a post-fix expression.
Input Format
The first input will be a single integer N denoting the number of test cases to take. After this, there will be exactly N
lines, each line a valid postfix string. The string will be a valid postfix expression consisting of only integers and
binary operators (+, -, *, /, and ?). Every integer and operator will be compulsorily separated by a SPACE. The
symbol ‘?’ denotes the end of the expression.
Sample input 100 200 + 2 / 5 * 7 +
Sample output 757

Link:https://www.hackerrank.com/contests/week8-ds-lab-23sc1202/challenges/postfix-expression-evaluation-4

Program:

Sample Input and Output:

133
23SC1202- DATA STRUCTURES

2. Infix to Postfix
My Laptop, Mac, really hates every time I write an infix expression! You have to ease the task for Mac by
transforming a given Infix expression to Postfix. Instead of numeric variables the expression given is using
lowercase English letters (a to z). The priority of operators is as follows '+', '-', '*', '/', '^' (increasing left to right) '^' is
for exponentiation. Each case would be a string without space in valid form. There won't be any case with ambiguity
i.e., such that two different answers are possible e.g., (a+b+c), it would be well parenthesized in that case.

Link : www.codechef.com/problems/INFPOS03

Program:

Sample Input and Output:

134
23SC1202- DATA STRUCTURES

3. Check for balanced parentheses in an expression


Problem Description
You have been given an expression containing parenthesis that you will be provided as input you have to check
Whether the expression has balanced parentheses is or not. Input Format Input will be in form of brackets.
Constraints
Your code must be memory efficient.
Output Format
Output must be:0 for not-balanced 1forbalanced
Sample Input 0 {(())}
Sample Output 0 1
Sample Input 1 {()
Sample Output 1 0

Link: https://www.hackerrank.com/contests/week8-ds-lab-23sc1202/challenges/balanced-parentheses-in-an-
expression

Program:

Sample Input and Output:

135
23SC1202- DATA STRUCTURES

Post Lab Task:


1. Draw the expression tree and find the infix and prefix expressions for the following postfix expression:
AB*CD/+EF-*.

2. Draw the expression tree and find the infix and prefix expressions for the following infix expression:
K + L - M*N + (O^P) * W/U/V * T + Q.

136
23SC1202- DATA STRUCTURES

Skill Session:

1.Write a program in C to convert an infix expression to a postfix expression using the stack data structure.
You are given an Infix expression.Use the stack data structure to convert it to a Postfix expression.
Stack is already implemented for your convenience in the code editor.
You can use the stack using the following functions-
createStack(capacity) - This function is used to create a stack. It takes one argument capacity which defines the
maximum capacity of stack.
isEmpty() - This function returns 1 if the stack is empty, otherwise it returns 0.
peek() - This function returns the top element in the stack.
push(stack, item) - This function can be used to push items into the stack. It takes two arguments, stack - the pointer
to the stack, and the item to push in the stack.
pop() - This function can be used to pop the top element of the stack.

Input Format
The first line contains a variable N, the length of the expression
The second line contains a string S containing an infix expression
Output Format
In a single line output the postfix expression

Sample 1:Input/Output
7
A+B*C+D
ABC*+D+

Sample 2:Input/Output
17
((A+B)-C*(D/E))+F
AB+CDE/*-F+
Link: https://www.codechef.com/learn/course/college-data-structures-c/CPDSC02/problems/DSAC29E

Program:

137
23SC1202- DATA STRUCTURES

Sample Input and Output:

138
23SC1202- DATA STRUCTURES

2. Check for balanced parentheses in an expression


Problem Description
You have been given an expression containing parenthesis that You will be provided as input you have to check
whether the expression has balanced parenthesis is or not.

Link:https://www.hackerrank.com/contests/the-great-programming-challange/challenges/check-for-balanced-
parentheses-in-an-expression

Program:

Sample Input and Output:

139
23SC1202- DATA STRUCTURES

3. Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result
of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as
eval().
Example 1:
Input: s = "1 + 1"
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
Constraints:
1 <= s.length <= 3 * 105
s consists of digits, '+', '-', '(', ')', and ' '.
s represents a valid expression.
'+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
'-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
There will be no two consecutive operators in the input.
Every number and running calculation will fit in a signed 32-bit integer.

Link: https://leetcode.com/problems/basic-calculator/description/

Program:

Sample Input and Output:

140
23SC1202- DATA STRUCTURES

4. Convert an infix expression into postfix expression.


Input Format
The first input will be a single integer N denoting the number of test cases to take. Followed by N infix strings.
Binary operators (+, -, *, / and ?) and parenthesis. Every integer, operator and parenthesis will be compulsorily
separated by a SPACE. The symbol ‘?’ denotes the end of an expression.
Constraints
1 < t < 100
1 < arr[i] < 100

Output Format
N lines denoting postfix expression.
Every integer and operator must be separated by a single SPACE.
Sample Input 0
1
31 * ( 4 + 50 ) ?
Sample Output 0
31 4 50 + *
Sample Input 1
1
( ( 32 + 34 * 12 ) * ( 1 + 2 ) / ( 1 + 1 ) ) * ( 23 - 21 ) ?
Sample Output 1
32 34 12 * + 1 2 + * 1 1 + / 23 21 - *
Link: https://www.hackerrank.com/contests/week8-ds-lab-23sc1202/challenges/convert-an-infix-expression-
into-a-postfix-expression

Program:

Sample Input and Output:

141
23SC1202- DATA STRUCTURES

5 Evaluate Postfix Expression

Input Description
The first input will be a single integer N denoting the number of test cases to take. After this, there will be exactly N
lines, each line a valid postfix string. The string will be a valid postfix expression consisting of only integers and
binary operators (+, -, *, /, and $). Every integer and operator will be compulsorily separated by a SPACE. The
symbol „? ‟ denotes the end of the expression.
Output Description
Exactly N lines, each line denoting the output of the expression. In case the output is in fractions, please print only
the integer part of the output.
Sample Input 2 3 1 * + 9 -
Sample Output -4

Link:https://www.hackerrank.com/contests/week8-ds-lab-23sc1202/challenges/evaluate-postfix-expression-1-1

Program:

Sample Input and Output:

142
23SC1202- DATA STRUCTURES

6.Convert an infix expression into a postfix expression.


Note: In case two operators have equal precedence, the order of operation goes from left to right Input Description
The first input will be a single integer N denoting the number of test cases to take. After this there will be exactly N
lines, each line a valid infix string. The string will be a valid postfix expression consisting of integers, binary operators
(+, -, *, /and $), and parenthesis. Every integer, operator, and parenthesis will be compulsorily separated by a SPACE.
The symbol „ ? ‟denotes the end of the expression.
Output Description
Exactly N lines, each line denoting the postfix expression. Every integer and operator must be separated by a single
SPACE.
Sample Input 131*(4+50)
Sample Output 31 450+*

Link:https://www.hackerrank.com/contests/week8-ds-lab-23sc1202/challenges

Program:

143
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Valuator’s use only)

144
23SC1202- DATA STRUCTURES

WEEK -9

Date of the Session: ____/_____/____ Time of the Session: ____/_____/____

Pre requisite:

• Hashing, Hashing function, Hashing table


• Node – structure definition for Hashing
• Dynamic memory allocation
• Types of hashing
Pre-Lab Task:

1. Define Hashing.

2. What is collision? What are different collision resolution techniques?

3. Why is rehashing done?

4. What is the load factor? How to calculate load factor?

5. What is a hash table? What is the hash function?

145
23SC1202- DATA STRUCTURES

In-Lab Task:

1. Key mod K is a hash function used for a particular hashing. In Case of collision Separate chaining is used to
link key with hash value. Print the keys corresponding to every hash value in increasing order on separate lines
where collision occurs.

INPUT
First line consists of the number N denoting the number of keys.
Next line contains N keys and K value separated by spaces.
OUTPUT
Print the keys corresponding to every hash value in increasing order on separate lines where collision occurs.
CONSTRAINTS
0<N<100
0<K<100
SAMPLE INPUT
7
50 101 73 92 85 76 700 7
SAMPLE OUTPUT
50 85 92
73 101
Link: www.hackerrank.com/week9-ds-23sc1202lab

Program:

Sample Input and Output:

146
23SC1202- DATA STRUCTURES

2. Hash Tables: Ice Cream Parlor

Each time Sunny and Johnny take a trip to the Ice Cream Parlor, they pool their money to buy ice cream. On any given
day, the Parlor offers a line of Flavors. Each flavour has a cost associated with it. Given the value of money and the
cost of each flavour for t trips to the Ice Cream Parlor, help Sunny and Johnny choose two distinct Flavors such that
they spend their entire pool of money during each visit. ID numbers are the 1- based index number associated with a
cost. For each trip to the Parlor, print the ID numbers for the two types of ice cream that Sunny and Johnny purchase
as two space-separated integers on a new line. You must print the smaller ID first and the larger ID second.
Example
cost= [2,1, 3, 5, 6]
They would purchase flavour ID's 1 and 3 for a cost of 2+3=5. Use 1 based indexing for your response.
Sample Input
STDIN Function
----- --------
2 t=2
4 money = 4
5 cost [] size n = 5
1 4 5 3 2 cost = [1, 4, 5, 3, 2]
4 money = 4
4 cost[] size n = 4
2 2 4 3 cost = [2, 2, 4, 3]
Sample Output
14
12
Link: https://www.hackerrank.com/challenges/ctci-ice-cream-parlor/problem

Program:

Sample Input and Output:

147
23SC1202- DATA STRUCTURES

3, Cells in a Matrix

You are given an integer N denoting an N×N matrix. Initially, each cell of the matrix is empty. You are given K tasks.
In each task, you are given a cell (i, j) where cell (i, j) represents the itℎ row and jtℎ column of the given matrix. You have to
perform each task sequentially in the given order. Each task is described in cell (i, j). For each task, you have to place X in each
cell of row i and each cell column j. After you complete each task, you are required to print the number of empty cells in the
matrix.
Input format
• The first line contains two space-separated integers N and K where N is the number of rows
and columns in the given matrix and K is the number of tasks respectively.
• Next K lines contain two space-separated integers i and j.
Output format
Print K space-separated integers denoting the number of empty cells in the matrix.
Constraints
1≤N≤105
1≤K≤1000
1≤i,j≤N

Link: www.hackerrank.com/week9-ds-23sc1202lab

Program:

Sample Input and Output:

148
23SC1202- DATA STRUCTURES

Post-Lab Task

1. You are given two arrays a=[a1,a2,...,an] and b=[b1,b2,...,bn], with a1=a2=...=an=0.
First, you must choose two of indices i,j (1≤i,j≤n,i≠j) and assign ai=aj=1. Then perform the following operation as
many times as you want: Choose an index k(1≤k≤n), and add the product of the two largest integers in a to ak. That
is, ak=ak+ai⋅aj, where ak≥aj≥ai for all l(1≤l≤n,l≠i,l≠j). Now, determine if you can transform the array a into the
array b or not.
If you can construct the array, then print “YES”. Otherwise, print “NO”.
Sample Input
3
4
8100
4
5220
4
6300
Sample Output
YES
YES
NO

Link www.hackerrank.com/week9-ds-23sc1202lab
Program:

Sample Input and Output:

149
23SC1202- DATA STRUCTURES

2. Plot the Curve

You are given with integers a,b, c, d, m. These represent the modular equation of a curve y2
mod m=(ax3+bx2+cx+d) mod m
Also, you are provided with an array A of size N. Now, your task is to find the number of pairs in the array that
satisfy the given modular equation.
If (Ai,Aj) is a pair then Ai2 mod m=(aAi3+bA i2+c Ai+d) mod m.
Since the answer could be very large output it modulo 109+7.
Note: A pair is counted different from some other pair if either Ai of the two pairs is different or Aj of the two pairs
is different. Also for the convenience of calculations, we may count (Ai, Ai) as a valid pair if it satisfies given
constraints.
Input Format First line of the input contains number of test cases T.First line for each test case consists of 5 space-
separated integers a, b,c, d, m, corresponding to modular equation given. Next line contains a single integer N.Next
line contains N space-separated integers corresponding to values of array A.
Output Format: For each test case, output a single line corresponding to number of valid pairs in the array
mod 109+7.
Link: www.hackerrank.com/week9-ds-23sc1202lab

Program:

Sample Input and Output:

150
23SC1202- DATA STRUCTURES

Skill Session
1. Design a HashSet without using any built-in hash table libraries.
Implement MyHashSet class:
void add(key) Inserts the value key into the HashSet.
bool contains(key) Returns whether the value key exists in the HashSet or not.
void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.
Link:https://leetcode.com/problems/design-hashset/
Program:

Sample Input and Output:

151
23SC1202- DATA STRUCTURES

152
23SC1202- DATA STRUCTURES

2. Highest Rating
Neha and Jenish are good friends. Neha challenges Jenish to find the Highest possible Rating of given array A after
applying some queries. According to Neha, Rating of an array is highest occurrence of a element in the given array.
Jenish is provided with the Magical Number M and Q. For Each element in the given Array A, Jenish can Perform
Addition or Subtraction with M at most Q times.
Since Jenish is so confused and not able to come out with the solution, Help him to find Highest Ratings Possible for
Given Array after applying queries to each element.

Sample Input

1
1
4
1234

Sample Output

Link: www.hackerrank.com/week9-ds-23sc1202lab

Program:

153
23SC1202- DATA STRUCTURES

Sample Input and Output:

154
23SC1202- DATA STRUCTURES

3. Festivals
Alice likes festivals a lot as we all do. He also likes spending money on these festivals. He spends money in buying
various things on these festivals. But he has problem of forgetting. He only remembers his top three maximum
spendings for any festival.For eg, on Holi he spends 25 units on colors, 50 units on water sprays, 100 units on gifts,
150 units on sweets but he remebers only his top 3 spendings ,i.e., 50, 100 & 150.Now as the year ends he wants to
know the festival on which he spent most of his money that he can remember.
Input Format
First line contains an integer T, denoting number of test cases.Second line contains an integer N, denoting number of
spendings in a year.Each of the next N lines contain a string S and an integer X denoting festival name and spending
on one of the events of that festival.
Output Format
For each test case, print a single line containing the festival name and its total spending that he remembers.If there
are more than 1 festival with the maximum spending, print the one which has lexicographically smallest name.
Sample Input
2
6
B 20
A2
A 10
A 10
B 30
A 30
3
abc 10
xyz 15
oop 8

Sample Output
A 50
xyz 15
Link: www.hackerrank.com/week9-ds-23sc1202lab
Program:

Sample Input and Output:

155
23SC1202- DATA STRUCTURES

4. Linear Probing

You need to implement linear probing. You have to perform insertion, deletion operations in it following the below
input format.
Input format: First line contains the size of the hash table Next line contains the no of queries q Next q lines
contains 3 types of queries Type 1 contains 1 followed by an integer that need to be inserted into the hash table
Type 2 contains 2 followed by an integer that need to be deleted from the hash table Type 3 contains a single integer
3 which indicates that the elements of hash table need to be displayed.
Output format:
If the operation is insertion there is nothing to be printed. If operation is to display then print the hash table.
For displaying, print the elements of the hash table on the same line separated by space.
Print -1 for empty buckets.
Sample Input:
10
8
15
1 15
1 25
16
3
25
2 15
3
Sample Output:
-1 -1 -1 -1 -1 5 15 25 6 -1
-1 -1 -1 -1 -1 25 6 -1 -1 –1
Link: www.hackerrank.com/week9-ds-23sc1202lab
Program:

156
23SC1202- DATA STRUCTURES

Sample Input and Output:

157
23SC1202- DATA STRUCTURES

5. Pairs of Elements

You are given an array of length N. You are required to count the number of (I,J) pairs where 1⩽i<j⩽N such that the
difference of the array elements on that indices is equal to the sum of the square of their indices.
That is the count of the number of pairs of (i,j) such that it satisfies this equation (A[j]−A[i]=i2+j2).
Input format
• The first line contains the length of the array N. (1⩽N⩽105)
• The second line contains N integers representing array elements. (1⩽A[i]⩽1012)
Output format
Print the number of pairs that satisfy the provided condition.
Sample Input
5
4 9 6 29 30
Sample Output
3
Link: www.hackerrank.com/week9-ds-23sc1202lab
Program:

Sample Input and Output:

158
23SC1202- DATA STRUCTURES

6.Ransom Note

Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him through his
handwriting. He found a magazine and wants to know if he can cut out whole words from it and use them to create an
untraceable replica of his ransom note. The words in his note are case-sensitive and he must use only whole words
available in the magazine. He cannot use substrings or concatenation to create the words he needs. Given the words
in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole
words from the magazine; otherwise, print No.
Link: https://www.hackerrank.com/challenges/ctci-ransom-note/problem
Program:

159
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Valuator’s use only)

160
23SC1202- DATA STRUCTURES

WEEK -10

Date of the Session:____/_____/____ Time of the Session: ____/_____/____

Pre requisite:
• Tree, Sub-tree, Parent, Child - nodes
• Node – Degree, Height, Level, Depth
• Structure definition for a tree node
• Dynamic memory allocation
Pre-Lab Task:

1. For the given tree structure, traverse the in-order, pre order and post order

In-Order:
Pre-Order:
Post-Order:
2. For the given node values, construct the BST structure and traverse in-order, pre order and post
order. 10,18,45,23,89,98,26,32,44,12,14,99
In-Order:
Pre-Order:
Post-Order:
3. List the meris and demerits of BST.

4. Write the Applications of BST?

5. How many categories do we have to delete a node from BST list them?

161
23SC1202- DATA STRUCTURES

In-Lab Task:
1. Binary Search Tree: Insertion
You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the
values into their appropriate position in the binary search tree and return the root of the updated binary tree.
You just have to complete the function.
Sample Input
4
/\
27
/\
13
The value to be inserted is 6.
Sample Output
4
/\
2 7
/\/
1. 36
Link:https://www.hackerrank.com/challenges/binary-search-tree-insertion/problem

Program:

Sample Input and Output:

162
23SC1202- DATA STRUCTURES

2. Construct Binary Search Tree from Preorder Traversal

Example 1: Input Preorder = [8, 5, 1, 7, 10, 12]


Output: [8, 5, 10, 1, 7, null, 12
Example 2: Input Preorder = [1, 3]
Output: [1, null, 3]
All the values of the preorder are Unique
Link:https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/

Program:

Sample Input and Output:

163
23SC1202- DATA STRUCTURES

3. Construct Binary Search Tree from Preorder Traversal and inorder traversal
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is
the inorder traversal of the same tree, construct and return the binary tree.

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]


Output: [3,9,20,null,null,15,7]

Input: preorder = [-1], inorder = [-1]


Output: [-1]

Link:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

Program:

Sample Input and Output:

164
23SC1202- DATA STRUCTURES

Post-Lab Task:

1. Construct Binary Search Tree from inorder and postorder Traversal


Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is
the postorder traversal of the same tree, construct and return the binary tree.

Example 1: Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]


Output: [3,9,20,null,null,15,7]
Example 2: Input: inorder = [-1], postorder = [-1] Output: [-1]

165
23SC1202- DATA STRUCTURES

2. Tree: Post order Traversal

Complete the postOrder function in your editor below, which has 1parameter: a pointer to the root of a binary
tree. It must print the values in the tree's postorder traversal as a single line of space-separated values.
Input Format
Our hidden tester code passes the root node of a binary tree to your postOrder function.
Output Format
Print the tree's postorder traversal as a single line of space-separated values.
Sample Input
1
\2
\5
/\
3 6
\4
Sample Output
436521

Link: https://www.hackerrank.com/challenges/tree-postorder-traversal/problem
Program:

Sample Input and Output:

166
23SC1202- DATA STRUCTURES

Skill Session:

1. Construct a Binary Search tree and print all the leaf nodes of the tree. If there is only root node in the tree,
consider it as leaf node.
Link:https://www.codechef.com/KRC12023/problems/BSTLEAF

Program:

Sample Input and Output:

167
23SC1202- DATA STRUCTURES

2. Deletion of Binary Search Tree:


Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node
reference (possible updated) of the BST.
Basically, the deletion can be divided in two stages:
1. Search for a node to remove.
2. If the node is found, delete the node.
Example:

Input: root = [5,3,6,2,4,null,7], key = 3.


Output: [5,4,6,2, null,7].
Explanation: Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,
null,7], shown in the above BST.
Please notice that another valid answer is [5,2,6, null,4, null,7] and it is also accepted.

Constraints:
• The number of nodes in the tree is in the range [0, 104].
• -105 <= Node.val <= 105
• Each node has a unique value.
• Root is a valid binary search tree.
• -105 <= key <= 105
Link: https://leetcode.com/problems/delete-node-in-a-bst/
Program:

168
23SC1202- DATA STRUCTURES

Sample Input and Output:

169
23SC1202- DATA STRUCTURES

3.Binary Search Trees


Today, we're working with Binary Search Trees (BSTs). Check out the Tutorial tab for learning materials and an
instructional video!
Task
The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are
given a pointer, , pointing to the root of a binary search tree. Complete the getHeight function provided in
your editor so that it returns the height of the binary search tree.
Sample Input
7
3
5
2
1
4
6
7
Sample Output
3

Link:https://www.hackerrank.com/challenges/30-binary-search-trees/problem

Program:

Sample Input and Output:

170
23SC1202- DATA STRUCTURES

4. You are given pointer to the root of the binary search tree and two values and . You need to return the
lowest common ancestor (LCA) of and in the binary search tree.

In the diagram above, the lowest common ancestor of the nodes and is the node . Node is the lowest node which has
nodes and as descendants.
Function Description
Complete the function lca in the editor below. It should return a pointer to the lowest common ancestor node of the
two values given.
lca has the following parameters:
- root: a pointer to the root node of a binary search tree
- v1: a node.data value
- v2: a node.data value
Input Format
The first line contains an integer, , the number of nodes in the tree.
The second line contains space-separated integers representing values.
The third line contains two space-separated integers, and .
To use the test data, you will have to create the binary search tree yourself. Here on the platform, the tree will be
created for you.
The tree will contain nodes with data equal to and .
Output Format
Return the a pointer to the node that is the lowest common ancestor of and .
Sample Input
6
423176
17

and .
Sample Output
[reference to node 4]
Explanation
LCA of and is , the root in this case.
Return a pointer to the node.
Link: https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-
ancestor/problem?isFullScreen=true

171
23SC1202- DATA STRUCTURES

Program:

Sample Input and Output:

172
23SC1202- DATA STRUCTURES

5. Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-
order traversal, nodes are visited level by level from left to right. Complete the function and print the values in a
single line separated by a space.
For example:
1
\
2
\
5
/ \
3 6
\
4
For the above tree, the level order traversal is .
Input Format
You are given a function,
void levelOrder(Node * root) {

}
Constraints
Nodes in the tree
Output Format
Print the values in a single line separated by a space.
Sample Input
1
\
2
\
5
/ \
3 6
\
4
Sample Output
125364
Explanation
Link: https://www.hackerrank.com/challenges/tree-level-order-traversal/problem?isFullScreen=true

Program:

173
23SC1202- DATA STRUCTURES

Sample Input and Output:

174
23SC1202- DATA STRUCTURES

6.Delete kth largest node from a BST

Given a Binary Search Tree (BST), delete the kth largest node from it and print a level order traversal of the
resulting BST.
• Your node class/struct shouldn't have any other variables other than key, and pointers to left and right node
Input Format
• The first line of contains the number of nodes in the tree, N followed by k (kth largest node to be deleted).
• In the next line there will a list of N unique numbers, which are the keys that you will use to construct
your BST The keys are given in level order fashion.
Output Format
You have to print the level-order traversal of BST obtained after deletion of the kth largest element.
*Note: The levels of the BST are printed on the same line *
Constraints
1 <= N <= 100
Sample Input
Test Case 1
51
42713
Test Case 2
65
10 8 12 7 11 9
Sample Output
Output 1
4213
Output 2
10 9 12 7 11
Link: www.hackerrank.com/week-11-ds-23sc1202-skill6

Program:

175
23SC1202- DATA STRUCTURES

Sample Input and Output:

(For Valuator’s use only)

176
23SC1202- DATA STRUCTURES

WEEK -11

Date of the Session:____/_____/____ Time of the Session: ____/_____/____


Pre requisite:
• Tree, sub-tree, parent, child-nodes
• Structure definition for a tree node
• Dynamic Memory Allocation
• Balancing Factor - {-1,0,1}
• Self-balancing tree
Pre-Lab
1. How to calculate Balance factor in AVL Tree?

2. Consider the following heap after build-heap phase. What will be its corresponding array?

3. Write the different orders of B-Tree.

4. How splay tree is preferable than AVL Tree

5. What are the operations that could be performed in O(logn) time complexity by red-black tree?

177
23SC1202- DATA STRUCTURES

In-Lab Task
1.Given n number each representing value of a node, construct a tree in the following manner: Let's say
node to be inserted has value x. If x is less than or equal to value of the current root node then insert to
the left of the current root If x is greater than the value of the current root, then insert node in the right of
this node. The above insertion will make a special tree known as Binary Search Tree. Determine whether
the tree is balanced or not. A tree is said to be balanced if the absolute difference between the depth of
left sub tree and the right sub tree of each node does not differ by more than1.

Link: www.hackerrank.com/week11-ds-23sc1202lab
Program:

Sample Input and Output:

178
23SC1202- DATA STRUCTURES

2. Implement Heapsort algorithm to sort an integer array in an ascending and try to make it faster as much as
possible.
• You are required to build the functionality of Heap Sort algorithm and use it to sort the arrays.
• You are prohibited from using the built in functions of any language
• Your Code will be Reviewed to prevent any cheating :)
Input Format
• First line: the size of the array
• Second line: the array to be sorted (numbers separated by spaces)
Output Format
output between two brackets, and each two numbers separated by comma.
Sample Input
• 6
• 193547
Sample Output
[1,3,4,5,7,9]
Link: www.hackerrank.com/week11-ds-23sc1202lab

Program:

Sample Input and Output:

179
23SC1202- DATA STRUCTURES

3. Given a list of numbers, you must sort them in non-decreasing order.


Input Format
The first line contains a single integer,
N, denoting the number of integers in the list.
The next N lines contain a single integer each, denoting the elements of the list.
Output Format
Output
N lines, containing one integer each, in non-decreasing order.
Sample Input:
5
5
3
6
7
1
Sample Output
1
3
5
6
7
Link: https://www.codechef.com/practice/course/heaps/HEAPF/problems/TSORT

Program:

Sample Input and Output:

180
23SC1202- DATA STRUCTURES

Post-Lab

1. Insert the following values into an initially empty AVL tree: 30, 20, 40, 10, 25, 35, 50, 5, 15.
• Provide the AVL tree after each insertion.
• What is the height of the node with the value 15 in the constructed AVL tree?
• If the value 30 is deleted from the AVL tree, what would be the resulting tree?
• Provide the AVL tree after the deletion.
• What is the in-order successor of the node with the value 20 in the constructed AVL tree?

181
23SC1202- DATA STRUCTURES

2. Construct a B-Tree of order 4 with the following keys:


20, 7, 90, 78, 45, 15, 5, 19, 12, 35, 41, 47, 10, 3, 6.

182
23SC1202- DATA STRUCTURES

Skill Session

1. Given the head of a singly linked list where elements are sorted in ascending order, convert it to a
height-balanced binary search tree.
Input: head = [-10, -3,0,5,9]
Output: [0, -3, 9, -10, null, 5]
Explanation: One possible answer is [0, -3, 9, -10, null,5], which represents the shown height balanced BST.
Constraints:
The number of nodes in head is in the range [0, 2 * 10^4].
-10^5 <= Node.val <= 10^5
Link: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/
Program:

183
23SC1202- DATA STRUCTURES

Sample Input and Output:

184
23SC1202- DATA STRUCTURES

2. The array heap is used for storing the values taken from the user. The array of max heap is created. The array is
divided into two halves and both the sides of array are sorted. Once both the sides are sorted, the whole array is taken
into consideration and the elements are swapped if not in correct order.
Sample Input: 5 3 9 4 5 8
Sample Output: 3 4 5 8 9
Link: https://www.hackerrank.com/week11-ds-23sc1202lab

Program:

Sample Input and Output:

185
23SC1202- DATA STRUCTURES

3. Suresh is a student of Computer Science. He is learning Trees. He does not know how to construct a B-Tree of order
m. Suresh is very eager to know. With the following set of numbers help him to construct a B-Tree of order 3(=m): 6,
10, 9, 12, 7, 4, 5, 15, 8, 3, 2, 14.

186
23SC1202- DATA STRUCTURES

4. Construct a Splay Tree with the following elements 10, 32, 45, 64, 22, 3, 9, 76, 177

187
23SC1202- DATA STRUCTURES

5. Consider the red-black tree given below and insert node 14 in it.

188
23SC1202- DATA STRUCTURES

6. Construct the red-black tree with following sequence of data 1, 7, 8, -6, 0.9, 45, 62. After construction of
the tree identify the colour of 45 element?

(For Valuator’s use only)

189
23SC1202- DATA STRUCTURES

WEEK -12
Lab Session:

Date of the Session: ___/___ /____ Time of the Session____ to____

Pre requisite:
• Non-linear data structure
• Graphs having edges and nodes
• Structure definition for nodes
• Traversals of a graph
• Shortest path algorithm

Prelab Task:
1.Build directed graph that corresponds to this adjacency matrix:

0 1 2 3

0 1 0 1 0

1 1 0 0 0

2 0 0 0 1

3 1 0 1 1

Solution:

2.Define minimal spanning tree?

3.Define adjacency Matrix of a graph?

4. In How many ways you can represent a graph?

190
23SC1202- DATA STRUCTURES

In Lab Task
1.Construct the adjacency matrix and adjacency List for given graph ?

Link: https://www.hackerearth.com/practice/algorithms/graphs/graph-representation/tutorial/

Program:

Sample Input and Output

191
23SC1202- DATA STRUCTURES

2.Construct the weighted directed graph represented by the adjacency matrix given below. A non-zero value
at [row, column] indicates that the vertex in the row is adjacent to the vertex in the column and apply DFS to
the graph

A B C D E
A 0 5 8 0 0

B 3 0 6 0 0

C 0 3 4 1 0

D 0 6 7 0 0

E 0 0 0 0 0

Solution:

192
23SC1202- DATA STRUCTURES

3. What is transitive closure? Construct transitive closure matrix for given graph?

Solution:

193
23SC1202- DATA STRUCTURES

Post-Lab Task

1.Apply Prim’s Algorithm to generate minimum Spanning Tree for the following graph?

Solution:

194
23SC1202- DATA STRUCTURES

2.The graph G(V, E) given below contains 6 vertices and 12 edges. And you will create a minimum spanning tree
T(V’, E’) for G(V, E) such that the number of vertices in T will be 6 and edges will be 5 (6-1).

Solution: -

195
23SC1202- DATA STRUCTURES

Skill Session:
1.Find the Transitive Closure for the following

Solution:

2.DFS: Given a Disconnected Graph, Find the reachability /Graph Traversal using DFS or Depth First Search
Algorithm .

Solution:

196
23SC1202- DATA STRUCTURES

3.Find Minimum Cost Spanning Tree (MST) of a given connected undirected graph using Kruskal's algorithm.

197
23SC1202- DATA STRUCTURES

4.Prim's (MST): Consider the following graph as an example for which we need to find the Minimum
Spanning Tree (MST).

Solution:

198
23SC1202- DATA STRUCTURES

5. Construct the adjacency matrix and adjacency List for graph given below?

Link: https://www.hackerearth.com/practice/algorithms/graphs/graph-representation/tutorial/

Program:

Sample Input and Output

199
23SC1202- DATASTRUCTURES

6 Find the MST and it’s total weight for the given graph using Kruskal algorithm?

Solution:

200
23SC1202- DATASTRUCTURES

(for Evaluators only)

201

You might also like