Tech 301 - 315 - Data Structure - SH
Tech 301 - 315 - Data Structure - SH
AND
ALGORITHMS
2
MODULE 1 – TECH 301 - RECURSION
THEORY CONCEPTS:
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
Output Format
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:
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:
Output Format:
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:
PROGRAM 1:
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40};
cout << "First element: " << getFirstElement(arr, 4) << endl;
return 0;
}
7
PROGRAM 2:
#include <iostream>
using namespace std;
int main() {
int arr[] = {0, -1, 2, -3, 1};
int size = sizeof(arr) / sizeof(arr[0]);
findTriplets(arr, size);
return 0;
}
8
PROGRAM 3:
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, size);
return 0;
}
9
PROGRAM 4:
O(n2)
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 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:
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:
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.
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:
Task:
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:
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:
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 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:
17
MODULE 7 – TECH 307 - STACK
THEORY CONCEPTS:
PROGRAM 1:
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.
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:
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:
Visited: google.com
Visited: facebook.com
> peek
> pop
Visited: twitter.com
> isEmpty
> pop
> pop
> pop
> exit
22
MODULE 8 – TECH 308 – QUEUE
THEORY CONCEPTS:
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:
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.
insert() – Insert a new section with its item quantity in the binary tree.
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).
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:
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:
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;
};
29
node->right = NULL;
return (node);
}
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:
PROGRAM 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.
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.
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:
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:
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:
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:
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:
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