0% found this document useful (0 votes)
21 views41 pages

Tech 301 - 315 - Data Structure - SH

The document is a student handout for a course on Data Structures and Algorithms, detailing various topics and programming exercises. It covers subjects such as recursion, searching and sorting algorithms, time and space complexity, and different types of data structures like linked lists, stacks, and queues. Each module includes theoretical concepts and practical programming tasks to reinforce learning.

Uploaded by

arena.zumur03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views41 pages

Tech 301 - 315 - Data Structure - SH

The document is a student handout for a course on Data Structures and Algorithms, detailing various topics and programming exercises. It covers subjects such as recursion, searching and sorting algorithms, time and space complexity, and different types of data structures like linked lists, stacks, and queues. Each module includes theoretical concepts and practical programming tasks to reinforce learning.

Uploaded by

arena.zumur03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

DATA STRUCTURES

AND
ALGORITHMS

CODE: TECH 301 to 315


STUDENT HANDOUT
TABLE OF CONTENTS

Sl. No Code Topic Pg. No

1 TECH 301 Recursion 3-5

2 TECH 302 Searching and Sorting 6-6

3 TECH 303 Time and space complexity 7 - 10

4 TECH 304 Introduction to DataStructures 11 - 12

5 TECH 305 Doubly Linked List 13 - 15

6 TECH 306 Circular Linked List 16 - 17

7 TECH 307 Stack 18 - 22

8 TECH 308 Queue 23 - 25

9 TECH 309 Trees 26 - 27

10 TECH 310 Binary Search Trees (BST) 28 - 31

11 TECH 311 Priority Queues 32 - 33

12 TECH 312 Graphs 34 - 35

13 TECH 313 Hashmaps 36 - 37

14 TECH 314 Greedy Algorithms 38 - 39

15 TECH 315 Dynamic Programming 40 - 41

2
MODULE 1 – TECH 301 - RECURSION

THEORY CONCEPTS:

1. Principle of mathematical induction, Introduction to recursion


2. Fibonacci numbers,Recursion using arrays, Recursion using strings, Recursion using
2D arrays

PROGRAM 1:

Imagine a determined young athlete named Alex who is training for a big competition. As
part of his training, he must climb a set of n stairs to reach the top of a training tower. Each
time he practises, he can either take a single step (climb 1 stair) or take a bigger leap (climb 2
stairs). Alex is curious about how many different ways he can reach the top of the stairs based
on his climbing patterns.

Alex decides to record his attempts to find out how many unique sequences of steps he takes
to reach the top.

Task

Given an integer n representing the number of stairs, determine the number of distinct ways
Alex can reach the top.

Input Format

An integer n, the total number of stairs.

Output Format

Print the number of distinct ways to reach the top

3
Example 1:

Input: n = 1 Output: 1

Example 2:
Input: n = 2 Output: 2

Example 3:

Input: n = 4 Output: 5

4
PROGRAM 2:

A librarian has a collection of n books stacked in a special way. To find a particular book, you
must first look at the book on the top, then recursively search the rest of the stack. If you find
the book, you need to count how many books you had to look at before finding it.

Task: Write a recursive function that takes the number of books n and the position of the
target book and counts how many books were looked at.

Input Format:

Two integers: n (total books) and target (the position of the book you are looking for).

Output Format:
Print the number of books looked at.

Sample Input:
n = 5, target = 3

Sample Output:
3 (You look at 1, then 2, then 3)

5
MODULE 2 – TECH 302 - SEARCHING AND SORTING

THEORY CONCEPTS:

1. Searching - Linear & Binary


2. Sorting - Bubble, Selection

PROGRAM 1:

Anna works in a library, and she has a huge pile of books that need to be sorted by their titles.
The pile is too large for her to handle all at once, so she decides to use a strategy where she
breaks the pile into smaller stacks, sorts each stack individually, and then merges the stacks
together to form the final sorted pile. Anna uses the merge sort technique to do this.

The merge sort process works by dividing the pile of books into two halves, recursively
sorting each half, and then merging the sorted halves back together.

Problem:

Anna needs your help to implement the merge sort algorithm to sort the titles of the books.
Write a program to sort an array of book titles using the merge sort algorithm.

Input Format:

An array of n book titles (as strings) to be sorted.

Output Format:

Print the sorted list of book titles.

Input:

War and Peace, Anna Karenina, Moby Dick, Great Expectations, The Odyssey

Output:

Anna Karenina, Great Expectations, Moby Dick, The Odyssey, War and Peace

6
MODULE 3 – TECH 303 - TIME AND SPACE COMPLEXITY

THEORY CONCEPTS:

1. Time Complexity=>Notation (Big O, Big Theta, Big Omega) Analysis


Techniques->Worst-case, Best-case, Average-case. Common Time Complexities
2. Space Complexity=> Auxiliary space complexity, Stack space vs. Heap space

PROGRAM 1:

Constant Time Complexity (O(1))

#include <iostream>
using namespace std;

int getFirstElement(int arr[], int size) {


return arr[0];
}

int main() {
int arr[] = {10, 20, 30, 40};
cout << "First element: " << getFirstElement(arr, 4) << endl;
return 0;
}

7
PROGRAM 2:

Cubic Time Complexity (O(n³))

#include <iostream>
using namespace std;

void findTriplets(int arr[], int size) {


for (int i = 0; i < size - 2; i++) {
for (int j = i + 1; j < size - 1; j++) {
for (int k = j + 1; k < size; k++) {
if (arr[i] + arr[j] + arr[k] == 0) {
cout << "Triplet found: " << arr[i] << ", " << arr[j] << ", " << arr[k] << endl;
}
}
}
}
}

int main() {
int arr[] = {0, -1, 2, -3, 1};
int size = sizeof(arr) / sizeof(arr[0]);
findTriplets(arr, size);
return 0;
}

8
PROGRAM 3:

Linear Time complexity: O(n)

#include <iostream>
using namespace std;

void reverseArray(int arr[], int size) {


int left = 0;
int right = size - 1;

while (left < right) {


swap(arr[left], arr[right]);
left++;
right--;
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);

reverseArray(arr, size);

cout << "Reversed array: ";


for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

9
PROGRAM 4:

O(n2)

void insertionSort(int arr[], int size) {


for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

10
MODULE 4 – TECH 304 -INTRODUCTION TO DATA
STRUCTURES

THEORY CONCEPTS:

1. Introduction to DS
2. Linked List -Definition and types,Advantages and disadvantages compared to
arrays,Single Linked ListBasic Operations=>insertion,deletion,Traversal

PROGRAM 1:

In a community garden, a gardener keeps track of various plants. Each plant is represented
by its ID in a linked list. The gardener notices that the plants are listed in reverse order and
wants to swap the positions of two specific plants.

Input Format:

The first line contains the number of plants Ls(n)L_s(n)Ls​(n).

The second line contains nnn plant IDs (space-separated).

The last line contains two plant IDs aaa and bbb that need to be swapped.

Output Format:

Print the modified list of plant IDs after reversing and swapping.

Input:
6
101 102 105 103 104 106
105 106

Output:

106 104 103 105 102 101

11
ADDITIONAL QUESTION

PROGRAM 2:

Shashwath works for a healthcare company that collects patient information from various
sources. As part of a data preprocessing task, he has been assigned to handle a dataset
containing patient IDs stored in an unsorted linked list. Due to the merging of multiple
databases, there's a possibility of having duplicate patient IDs in the list. His task is to
develop a program to eliminate these duplicates from the linked list before further processing.
Help to solve the problem

Input:
The input for the program will be the unsorted linked list containing patient IDs.

Output:
The output will be the modified linked list with duplicate patient IDs removed.

Sample input:
Patient IDs: 1001, 1002, 1003, 1002, 1004, 1003

Sample output:
Unique Patient IDs: 1001, 1002, 1003, 1004

12
MODULE 5 – TECH 305 - DOUBLY LINKED LIST

THEORY CONCEPTS:

1. Introduction to doubly Linked Lists


2. Basic Operations, Applications

PROGRAM 1:

A book rental system allows users to browse through available books and keep track of
borrowed books. The system keeps the books in a doubly linked list, where each node
represents a book with its title and ID. A user can insert a book into the list, delete a book,
and also browse books in forward and backward directions.
You are required to implement this book rental system using a doubly linked list.

Input Format:
The first line contains the number of books n.
The next n lines contain each book's ID and title.
You need to perform the following operations:
Insert a new book (title, ID).
Remove a book by ID.
Traverse the book list forward.
Traverse the book list backward.

Output Format: Print the updated list after each operation.

Input Example:
4
101 "C++ Programming"
102 "Data Structures"
103 "Algorithms"

13
104 "Operating Systems"
Insert: 105 "Machine Learning"
Delete: 102

Output Example:
After insertion:
101 "C++ Programming" -> 103 "Algorithms" -> 104 "Operating Systems" -> 105 "Machine
Learning"
After deletion:
101 "C++ Programming" -> 103 "Algorithms" -> 104 "Operating Systems" -> 105 "Machine
Learning"

14
PROGRAM 2:

A software development team is working on a library management system. They have an


array of book titles, and they need to convert this array into a doubly linked list for efficient
insertion and deletion of books. Each book title in the array is represented as a string. The
team needs your help to implement the conversion and provide a function to display the titles
in both forward and backward order.

Task:

Write a C++ program to:

1. Convert an array of book titles to a doubly linked list.


2. Implement functions to display the titles in forward and backward order.

Input:
string books[] = {"C++ Programming", "Data Structures", "Algorithms", "Operating
Systems"};

Output:
Books in forward order: C++ Programming -> Data Structures -> Algorithms -> Operating
Systems
Books in backward order: Operating Systems -> Algorithms -> Data Structures -> C++
Programming

15
MODULE 6 – TECH 306 - CIRCULAR LINKED LIST

THEORY CONCEPTS:

1. Introduction to Circular Linked Lists


2. Basic Operations,Applications

PROGRAM 1:

A hospital manages patients in a circular queue. Each patient is assigned a unique ID. The
queue allows adding new patients, deleting served patients, and printing the current list
starting from any given patient.

Input Format:
1. First line contains the number of patients n.
2. Next n lines contain patient IDs.
3. Perform operations: Add a new patient, delete a patient by ID, print the list starting
from any given patient.

Example Input:
3
1
2
3
Add: 4
Delete: 2
Start from: 3

Example Output:

Queue: 3 -> 4 -> 1

16
PROGRAM 2:

A software development team is working on a fitness application that tracks users' workout
sessions. Each workout session is represented as a node in a circular linked list, with each
node containing the workout ID and duration. The team needs to implement a function that
finds the middle workout session in the circular linked list. This functionality will help users
quickly access their average workout session details.

Task:

Write a C++ program to implement a circular linked list and a function that finds the middle
node. If the number of workout sessions is even, the function should return the second of the
two middle nodes.

Input Format:

The first line contains the number of workout sessions nnn.

The next nnn lines contain the workout session details (ID and duration).

Example Input:

5
1 30
2 45
3 25
4 60
5 50

Expected Output:

Middle Workout ID: 3, Duration: 25

17
MODULE 7 – TECH 307 - STACK

THEORY CONCEPTS:

1. Introduction to Stacks, Stack Operations

PROGRAM 1:

Plate Management in a Cafe

In a café, plates are stacked one on top of the other. Each time a new customer arrives, a plate
is placed on top of the stack. When the café runs out of plates, the chef needs to know by
checking if the stack is empty. Using a linked list as the underlying structure:

Push a plate onto the stack when it's clean and ready for use.

Pop a plate when a customer takes one.

Write a function to check if the plate stack is empty.

Input:

The program prompts the user for a choice of operations (push, pop, or check if stack is
empty) and asks for a plate number if needed.

Output:

The program responds based on the user's action, either adding or removing a plate, or
checking the stack status.

18
PROGRAM 2:

In an online coding platform like HackerRank, LeetCode, or a real-time code editor, users
often write programs in various languages such as C++, Java, or Python. One of the most
common syntax mistakes is forgetting to properly close parentheses, braces, or brackets ((),
{}, []). This results in syntax errors and makes the code unable to compile or run.

To help users avoid such issues, the online platform provides a tool that automatically checks
whether the parentheses in the user's code are balanced as they write. If the parentheses are
unbalanced, the tool highlights the error in real-time and prevents the code from being
compiled.

The goal is to develop a function that checks whether an expression or piece of code has
balanced parentheses, ensuring that every opening parenthesis/bracket/brace has a
corresponding closing one, and they are properly nested.

Input:
s = “[()]{}{[()()]()}”

Output:
true

Input:
s = “[(])”

Output:
false

19
PROGRAM 3:

Imagine you are developing a simple game where players receive points for completing tasks.
Each player logs their score after each task. Players are curious to know how long they will
have to wait until they achieve a higher score in the future.

You need to create a system that allows players to find out the next greater score after each
task they complete.

Given an array of scores representing points scored by a player after completing tasks in
order, your task is to determine for each score the next score that is greater. If no future score
is higher, return -1 for that score.

Input:
arr[] = [ 4 , 5 , 2 , 25 ]

Output:
4 –> 5
5 –> 25
2 –> 25
25 –> -1

20
PROGRAM 4:

Imagine you are developing a simple web browser, and you need to manage the user's
browsing history. Every time a user visits a new webpage, you want to keep track of it. The
user can go back to the previous page by pressing a "Back" button, which should retrieve the
most recently visited webpage from the history.

Problem Description:

You will implement a stack using an array to manage the browsing history. The following
operations should be supported:

Push (visit a page): When the user visits a new webpage, push the URL onto the
stack.

Pop (go back): When the user clicks the "Back" button, pop the URL from the stack
to go back to the previous webpage.

Peek (current page): The user wants to know the currently active webpage without
navigating away from it.

isEmpty (check history): Check if the browsing history is empty, indicating that the
user hasn't visited any pages yet.

Input:

Commands to operate on the stack:

"push <URL>": Simulates visiting a webpage.

"pop": Simulates going back to the previous page.

"peek": Retrieves the current page without removing it.

"isEmpty": Checks if the browsing history is empty.

"exit": Ends the input session.

Output:

The output will indicate the result of the operations, such as the current page after a peek, or a
message confirming that the user has gone back after a pop.

21
Example:

Welcome to the Browser History Manager!

Commands: push <URL>, pop, peek, isEmpty, exit

> push google.com

Visited: google.com

> push facebook.com

Visited: facebook.com

> peek

Current page: facebook.com

> pop

Going back from: facebook.com

> push twitter.com

Visited: twitter.com

> isEmpty

History has pages.

> pop

Going back from: twitter.com

> pop

Going back from: google.com

> pop

No pages in history to go back to.

> exit

22
MODULE 8 – TECH 308 – QUEUE

THEORY CONCEPTS:

1. Introduction to queue, Queue Operations


2. Implement a queue using an array with the following operations: enqueue, dequeue,
front, and isEmpty
3. Implement a queue using a linked list

PROGRAM 1:

As part of a computer science competition, participants are given a task to manipulate queues
efficiently. One of the challenges is to reverse the order of the first K elements in a queue.
The participants are required to implement a solution that achieves this task using a queue and
basic programming concepts.

Implement a function reverseFirstK that takes a queue and an integer K as input and reverses
the order of the first K elements in the queue. The remaining elements in the queue should
maintain their original order.

Input:
Queue: {1, 2, 3, 4, 5}
K: 3

Output:
Modified Queue: {3, 2, 1, 4, 5}

23
PROGRAM 2:

The school library is organising a book fair, and the librarian wants to rearrange the books in
the fiction section. To create a fresh look, the librarian plans to reverse the order of the books
in the fiction queue. However, due to the large number of books, manually rearranging them
would be time-consuming. As a solution, the librarian decides to write a program to automate
the process.

Input:
Queue: {Harry Potter, Lord of the Rings, Chronicles of Narnia, Game of Thrones}

Output:
Reversed Queue: {Game of Thrones, Chronicles of Narnia, Lord of the Rings, Harry Potter}

24
PROGRAM 3:

In a grocery store, customers are waiting in a queue to check out their items. The store
manager wants to analyse the average number of items each customer has in their cart. To
facilitate this analysis, the manager needs a program that can calculate the average number of
items in the queue efficiently. Implement a function queueAverage that takes a queue of
integers as input and returns the average of the elements in the queue.

Input:
Enter the size of the queue: 6
Enter the elements of the queue:
345278

Output:
Average Number of Items: 4.83333

25
MODULE 9 – TECH 309 TREES

THEORY CONCEPTS:

1. Introduction to Trees, Basic terminology, Examples of trees in real-life and computing


contexts
2. Binary Trees - Definition and properties of binary trees, Types of binary trees,
Operations and traversal techniques, Applications of binary trees

PROGRAM 1:

Imagine you are building a warehouse inventory system. In the warehouse, every item is
stored in a hierarchical structure, where each section of the warehouse can have multiple
subsections. This hierarchy can be represented as a binary tree where each node holds the
item quantity of that section. Your task is to find the maximum item quantity in the entire
warehouse.

To solve this problem, you need to traverse the entire binary tree and return the maximum
value from all the nodes.

Question:

Write a C++ program to find the maximum item quantity stored in the binary tree, where each
node contains an integer value representing the quantity of items in that section of the
warehouse.

Use the following operations:

insert() – Insert a new section with its item quantity in the binary tree.

findMax() – Traverse the tree and find the maximum quantity.

26
ADDITIONAL QUESTION

PROGRAM 2:

Imagine you are a software developer working for a park management system. The park
consists of various gardens, each represented by a node in a binary tree. Every garden in the
park can either have sub-gardens (children nodes) or no sub-gardens. If a garden doesn't have
any sub-gardens, it is called a leaf garden (or a leaf node in binary tree terms).

Your task is to find out how many leaf gardens there are in the park. In other words, you need
to count the number of leaf nodes in the binary tree representation of the park.

Question:

Write a C++ program to count the number of leaf nodes in a binary tree, where each node
represents a garden. A leaf node is a garden that has no sub-gardens (no children).

The program should:

insert() – Insert a new garden (node) into the binary tree.

countLeafNodes() – Count and return the number of leaf gardens (leaf nodes) in the binary
tree.

27
MODULE 10 – TECH 310 - BINARY SEARCH TREE (BST)

THEORY CONCEPTS:

1. Definition and properties of BST


2. Operations: search, insert, delete,traversal

PROGRAM 1:

You are working for an estate management company that manages a collection of properties.
The company maintains a database of property prices in the form of a Binary Search Tree
(BST), where each node represents a property, and the value stored in the node is the
property's price.

The estate manager often needs to retrieve the Kth largest property price from the database
for reports and analysis. For example, they might want to find the second largest property
price (k=2) or the third largest property price (k=3).

Your task is to write a program that, given a property price tree (BST) and a value of K,
returns the Kth largest property price without modifying the tree.

Question:

Write a C++ program to find the Kth largest element in a Binary Search Tree (BST)
representing property prices. The program should implement:

1. insert() – Insert a new property price (node) into the BST.


2. KthLargest() – Find the Kth largest property price in the BST.

28
ADDITIONAL QUESTION

PROGRAM 2:

You've been brought onto a project focused on optimising data processing algorithms for a
financial analytics platform. One of the key functionalities involves managing financial data
efficiently, which is organised in a Binary Search Tree (BST) format. As part of this project,
you're tasked with implementing an algorithm to find the minimum element within the BST.
This functionality is crucial for various financial calculations and risk assessments. Your task
is to devise an algorithm that can efficiently locate the minimum element in the BST while
considering factors such as algorithmic complexity, resource utilisation, and scalability.

Task:

Design an algorithm to find the minimum element in a Binary Search Tree (BST) efficiently.

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
using namespace std;

struct node {
int data;
struct node* left;
struct node* right;
};

struct node* newNode(int data)


{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;

29
node->right = NULL;
return (node);
}

struct node* insert(struct node* node, int data)


{
if (node == NULL)
return (newNode(data));
else {
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
return node;
}
}

void inorder(struct node* node, vector<int>& sortedInorder)


{
if (node == NULL)
return;
inorder(node->left, sortedInorder);
sortedInorder.push_back(node->data);
inorder(node->right, sortedInorder);
}

int main()
{
struct node* root = NULL;
int n;
cout << "Enter the number of nodes in the BST: ";
cin >> n;

30
cout << "Enter the values of the nodes: ";
for (int i = 0; i < n; ++i) {
int val;
cin >> val;
root = insert(root, val);
}

vector<int> sortedInorder;
inorder(root, sortedInorder);

if (!sortedInorder.empty())
cout << "\nMinimum value in BST is: " << sortedInorder[0] << endl;
else
cout << "\nBST is empty!" << endl;

getchar();
return 0;
}

Output:
Enter the number of nodes in the BST: 4 3 8 2 1
Enter the values of the nodes:
Minimum value in BST is: 1

31
MODULE 11 – TECH 311 - PRIORITY QUEUE

THEORY CONCEPTS:

1. Introduction to Priority Queues


2. Heap Data Structure
3. Types of Priority Queues:Min-Heap,Max-Heap
4. Heap Operations

PROGRAM 1:

There is an exam room with n seats in a single row labelled from 0 to n - 1.

When a student enters the room, they must sit in the seat that maximises the distance to the
closest person. If there are multiple such seats, they sit in the seat with the lowest number. If
no one is in the room, then the student sits at seat number 0.

Design a class that simulates the mentioned exam room.


Implement the ExamRoom class:
ExamRoom(int n) Initialises the object of the exam room with the number of the seats n.
int seat() Returns the label of the seat at which the next student will set.
void leave(int p) Indicates that the student sitting at seat p will leave the room. It is
guaranteed that there will be a student sitting at seat p.

Example 1:

Input
["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"]
[[10], [], [], [], [], [4], []]

Output
[null, 0, 9, 4, 2, null, 5]

32
ADDITIONAL QUESTION:

PROGRAM 2:

You are part of a university admissions office and need to keep track of the kth highest test
score from applicants in real-time. This helps to determine cut-off marks for interviews and
admissions dynamically as new applicants submit their scores.

You are tasked to implement a class which, for a given integer k, maintains a stream of test
scores and continuously returns the kth highest test score after a new score has been
submitted. More specifically, we are looking for the kth highest score in the sorted list of all
scores.

Implement the KthLargest class:

KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of test
scores nums.
int add(int val) Adds a new test score val to the stream and returns the element representing
the kth largest element in the pool of test scores so far.

Example 1:
Input:
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]

Output:
[null, 4, 5, 5, 8, 8]

33
MODULE 12 – TECH 312 - GRAPHS

THEORY CONCEPTS:

1. Introduction to graphs: definitions, types (directed, undirected, weighted),


representations (adjacency matrix, adjacency list)
2. Graph traversal algorithms: Depth-First Search (DFS), Breadth-First Search (BFS)

PROGRAM 1:

You are developing a search engine and need to analyze the web graph, where each web page
is represented as a node and hyperlinks between pages are represented as directed edges.
Given the adjacency list of web pages, count the total number of indexed web pages and the
total number of hyperlinks connecting them.

Question: Given an adjacency list representing a web graph, how many web pages are
indexed, and how many directed hyperlinks connect them?

Example:
Input:
{
{0, 1, 1, 0, 0},
{0, 0, 1, 0, 0},
{1, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
{0, 0, 0, 0, 0}
};

Output:
Number of web pages: 5
Number of hyperlinks: 6

34
ADDITIONAL QUESTION

PROGRAM 2:

There are n rooms labelled from 0 to n - 1 and all the rooms are locked except for room 0.
Your goal is to visit all the rooms. However, you cannot enter a locked room without having
its key.

When you visit a room, you may find a set of distinct keys in it. Each key has a number on it,
denoting which room it unlocks, and you can take all of them with you to unlock the other
rooms.

Given an array of rooms where rooms[i] is the set of keys that you can obtain if you visited
room i, return true if you can visit all the rooms, or false otherwise.

Example 1:
Input:
rooms = [[1],[2],[3],[]]

Output:
true

Example 2:
Input:
rooms = [[1,3],[3,0,1],[2],[0]]

Output:
false

35
MODULE 13 – TECH 313 -HASHMAPS

THEORY CONCEPTS:

1. Introduction to Hash Maps


2. Basic Operations with unordered_map
3. Basic Operations with unorder_set

PROGRAM 1:

Advith is developing a program to manage memberships for a local gym. Each member has a
unique ID number, and Advith have two lists: one containing the IDs of all current gym
members, and another containing the IDs of members who have signed up for a special class.
Advith task is to determine whether all the members who signed up for the class are already
existing gym members. Help Advith to solve this problem using a hashing technique.

Sample Input:
Number of existing gym members: 6
Number of members signed up for the special class: 4
List of existing gym members: 11 1 13 21 3 7
List of members signed up for the special class: 11 3 7 1

Sample Output:
Subset

36
PROGRAM 2:

Count the frequency of alphabetical characters in the given string using hashing technique.
Special characters and white spaces are not taken into account. Make sure that time
complexity of your code does not exceed O(N). Where, N is the length of the string. Capital
and small alphabets are treated the same.

Example
Input
APple

Output
a-1
e-1
l-1
p-2

37
MODULE 14 – TECH 314 -GREEDY ALGORITHM

THEORY CONCEPTS:

1. Greedy Algorithm, Characteristics of Greedy method, Components of Greedy


Algorithm
2. Activity Selection Problem
3. Minimum Number of Coins
4. Job Sequencing Problem

PROGRAM 1:

You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker
where:

difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with
difficulty at most worker[j]).

Every worker can be assigned at most one job, but one job can be completed multiple times.

For example, if three workers attempt the same job that pays $1, then the total profit will be
$3. If a worker cannot complete any job, their profit is $0.
Return the maximum profit we can achieve after assigning the workers to the jobs.

Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100

Example 2:
Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]
Output: 0

38
ADDITIONAL QUESTION

PROGRAM 2:

Policeman Catch Thieves


You are given an array containing n elements where each element is either a policeman ('P')
or a thief ('T'). Each policeman can catch only one thief, and a policeman cannot catch a thief
who is more than K units away from him. Your task is to find the maximum number of
thieves that can be caught by the policemen.

Input
The first line contains an integer n, the size of the array.
The second line contains the integer K, the maximum distance a policeman can catch a thief.
The third line contains a string of length n containing characters 'P' and 'T' (e.g., "PTTPPT").

Output
A single integer representing the maximum number of thieves that can be caught.

Input:
7
2
PTPTPTP

Output:
4

39
MODULE 15 – TECH 315 - DYNAMIC PROGRAMMING

THEORY CONCEPTS:

1. Introduction to Dynamic Programming


2. Types of Dynamic Programming Approaches

PROGRAM 1:

Two authors are working on a joint book project. Each author has written their drafts
separately, and they want to identify sections of text that are similar between the two drafts.
To facilitate their collaboration, they aim to find the longest common subsequence of their
writings, which will help them identify shared themes and avoid duplicating content.

Question:
Given two sequences (strings) representing the authors' drafts, implement a C++ function to
find the length of the longest subsequence present in both drafts using dynamic programming.

Example:
Input:
Enter first sequence: ABCDGH
Enter second sequence: AEDFHR

Output:
Length of Longest Common Subsequence: 3
Common Subsequence: ADH

40
PROGRAM 2:

A travel blogger is preparing for an upcoming trip and can only take a limited number of
items due to baggage restrictions. Each item has a specific weight and value based on its
importance to the trip. To maximise the value of the items in their bag, the blogger needs an
algorithm to determine which items to take without exceeding the weight limit of their
luggage.

Question:
Given weights and values of items and the maximum capacity of the knapsack, implement a
C++ function that determines the maximum value that can be obtained with the given
capacity using dynamic programming.

Example:
Input:
Enter the number of items: 4
Enter the weights of the items: 1 2 3 2
Enter the values of the items: 20 5 10 40
Enter the maximum capacity of the knapsack: 5

Output:
Maximum value in the knapsack: 60
Items included in the knapsack:
Item 1 - Weight: 2, Value: 5
Item 2 - Weight: 3, Value: 10
Item 3 - Weight: 2, Value: 40

41

You might also like