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

Ap Lab-Ii Course File

The document outlines the course file for an Advanced Programming Lab-II course. It includes sections on the university and department vision and mission, program educational objectives, program outcomes, student outcomes, syllabus, list of experiments, procedures, question papers, assessment, best practices, and recommendations.

Uploaded by

manoj.e17121
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)
47 views

Ap Lab-Ii Course File

The document outlines the course file for an Advanced Programming Lab-II course. It includes sections on the university and department vision and mission, program educational objectives, program outcomes, student outcomes, syllabus, list of experiments, procedures, question papers, assessment, best practices, and recommendations.

Uploaded by

manoj.e17121
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/ 90

Department of Computer Science & Engineering

SUBJECT: Advanced Programming Lab-II


(21CSP-351)

BATCH: B.E. CSE (2021-2025)

B.E. III Year – VI Semester

ACADEMIC SESSION (JAN-JUNE 2024)

Course File

Chandigarh University

Gharuan, Mohali

Prepared By: Verified By: HOD Sign:


Table of Contents

Sr.No Particulars
1 University-Vision and Mission
2 Department-Vision and Mission
3 PEO
4 PO
5 PSO
6 Course Objectives
7 Course Outcomes
8 Mapping of COs/POs/PSOs
9 Syllabus (As approved in BOS) ---(If Any Changes required, Approval Copy from
DAA)
10 List of Experiment’s (Mapped with Cos)
Experiment 1…10
Aim
Objective
Input/Apparatus Used
11 Procedure/Algorithm/Code
Observations/Outcome
Discussion
Question: Viva Voce
LAB MST
Question Paper (Mapped with COs)
Scheme of Evaluation
12 Sample Answer Sheets
CO-Wise Mark Sheets
List of Slow Learners and Advance Learners
Action Taken
13 Best Practices Adopted
14 Final Award Sheet
15 List of Slow Learners and Advance Learners
16 Overall Observation and Action Taken (Recommendation to BOS)
University-Vision and Mission

Vision: To be globally recognized as a Centre of Excellence for Research, Innovation,


Entrepreneurship and disseminating knowledge by providing inspirational learning to produce
professional leaders for serving the society

Mission:

Providing world class infrastructure, renowned academicians and ideal environment for Research,
Innovation, Consultancy and Entrepreneurship relevant to the society.

Offering programs & courses in consonance with National policies for nation building and meeting
global challenges.

Designing Curriculum to match international standards needs of Industry, civil society and for
inculcation of traits of Creative Thinking and Critical Analysis as well as Human and Ethical values.

Ensuring students delight by meeting their aspirations through blended learning, corporate
mentoring, professional grooming, flexible curriculum and healthy atmosphere based on co-
curricular and extra-curricular activities.

Creating a scientific, transparent and objective examination/evaluation system to ensure an ideal


certification.

Establishing strategic relationships with leading National and International corporates and
universities for academic as well as research collaborations.

Contributing for creation of healthy, vibrant and sustainable society by involving in Institutional
Social Responsibility (ISR) activities like rural development, welfare of senior citizens, women
empowerment, community service, health and hygiene awareness and environmental protection.

i
Department-Vision and Mission
Vision:

To be recognized as a leading Computer Science and Engineering department through effective


teaching practices and excellence in research and innovation for creating competent professionals
with ethics, values and entrepreneurial attitude to deliver service to society and to meet the current
industry standards at the global level.

Mission:

M1: To provide practical knowledge using state-of-the-art technological support for the experiential
learning of our students.

M2: To provide industry recommended curriculum and transparent assessment for quality learning
experiences.

M3: To create global linkages for interdisciplinary collaborative learning and research.

M4: To nurture advanced learning platform for research and innovation for students’ profound
future growth.

M5: To inculcate leadership qualities and strong ethical values through value-based education.

ii
Program Educational Objectives (PEOs)

PEO 1: Engage in successful careers in industry, academia, and public service, by applying the
acquired knowledge of Science, Mathematics and Engineering, providing technical leadership for their
business, profession and community.
PEO 2: Establish themselves as entrepreneur, work in research and development organization and
pursue higher education.
PEO 3: Exhibit commitment and engage in lifelong learning for enhancing their professional and
personal capabilities.

ii
Program Outcomes (POs)

PO1: Engineering knowledge: Apply the knowledge of Mathematics, Science, Engineering


fundamentals and computer science fundamental and strategies which have the solution of complex
computer science engineering problems.

PO2: Problem analysis: Identify, formulate, research literature, and analyze complex computer science
engineering problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex database and software
engineering problems and design system components or processes that meet the specified needs with
appropriate considerations for the public health and safety, and the cultural, societal, and
environmental considerations.

PO4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of software engineering & networking-based experiments, analysis and
Interpretation of data, and synthesis of the information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
Computer science engineering and IT tools including prediction and modeling to complex database
or software engineering activities with an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
social, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
Professional Computer Science & Engineering practice.

PO7: Environment and sustainability: Understand the impact of the professional computer science
and engineering solutions in social and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development goals.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of computer science engineering practice

PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.

iv
PO10: Communication: Communicate effectively on complex computer science engineering
activities with the engineering community like CSI society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.

PO11: Project management and finance: Demonstrate knowledge and understanding of the computer
science engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.

PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life- long learning in the broadest context of computer science engineering changes.

v
Student Outcomes
The Bachelor of Engineering is a programme offered by the Department of Computer Science &
Engineering in accordance with the Student Outcome of Computing Accreditation Commission
(CAC) and Engineering Accreditation Commission (EAC) of ABET. The Student Outcomes are as
follows:

Student Outcomes according to Computing Accreditation Commission (CAC)

SO 1. Analyze a complex computing problem and apply principles of computing and other
relevant disciplines to identify solutions.
SO 2. Design, implement and evaluate a computing-based solution to meet a given set of
computing requirements in the context of the program’s discipline.
SO 3. Communicate effectively in a variety of professional contexts.
SO 4. Recognize professional responsibilities and make informed judgments in computing
practice based on legal and ethical principles.
SO 5. Function effectively as a member or leader of a team engaged in activities appropriate to
the program’s discipline.
SO 6. Apply computer science theory and software development fundamentals to produce
computing-based solutions.

Student Outcomes according to Engineering Accreditation Commission (EAC)

SO 1. An ability to identify, formulates, and solve complex engineering problems by applying


principles of engineering, science, and mathematics
SO 2. An ability to apply engineering design to produce solutions that meet specified needs with
consideration of public health, safety, and welfare, as well as a global, cultural, social, environmental,
and economic factor
SO 3. An ability to communicate effectively with a range of audiences
SO 4. An ability to recognize ethical and professional responsibilities in engineering situations and
make informed judgments, which must consider the impact of engineering solutions in global,
economic, environmental, and societal contexts
SO 5. An ability to function effectively on a team whose members together provide leadership, create
a collaborative and inclusive environment, establish goals, plan tasks, and meet objectives.
SO 6. An ability to develop and conduct appropriate experimentation, analyze and interpret data, and
use engineering judgment to draw conclusions.
SO 7. An ability to acquire and apply new knowledge as needed, using appropriate learning
strategies.

vi
Program Specific Outcomes (PSOs)

A Graduate of Computer Science and Engineering Program will be able:

PSO1. Exhibit attitude for continuous learning and deliver efficient solutions for emerging
challenges in the computation domain.

PSO2. Apply standard software engineering principles to develop viable solutions for Information
Technology Enabled Services (ITES).

vi
Code of Ethics
Any misuse or abuse of computer equipment, programs or data will result in termination of
computer privileges and may lead to disciplinary action.

This includes:

1. Entering or exploring any area of the computer or network other than the program for the course
and the home directory where the student's data files are located. This includes attempting to
explore the Internet without permission.

2. Attempting to log on with another ID other than their own

3. Attempting to destroy or modify programs, records or data belonging to the school or another
user.

4. Accessing or modifying any desktop icons or files without instructor’ permission.

5. Computer vandalism, which includes writing on any equipment, taking mouse balls, writing on
mouse pads or copy holders, or removing anything from the classroom that belongs here.
Vandalism also includes changing computer configurations or attempting to "hack" into any
system that is not part of the curriculum.

6. Unauthorized use of computing resources for unauthorized purposes.

7. Accessing or copying programs, records or data belonging to the school or another user without
permission.

8. Attempting to breach the security of another user's account or deprive another user of access to
computing resources.

9. Using the university's computing resources for personal or financial gain.

10. Transporting copies of the university's programs, records or data to another person or site
without written authorization.

11. Cheating or computer vandalism results in referral to Admin. Cheating includes copying or
using other students' work or copying or using other students' files.

vi
Syllabus

Course TITLE OF THE COURSE L T P S C CH Course Type*


Code Advance Programming Lab – II 0 0 2 0 1 2 EE

21CSP- Course Code(s)


351/21ITP-351 21CSP-351//21ITP-351
PRE- Basics of C, C++, Data Structure
REQUISITE
CO- Data Structure
REQUISITE
ANTI- -
REQUISITE

a. Course Description
Advance programming is the course in which students will learn how to apply algorithms in order to solve
complex problems. The goal of this course is to teach students how to apply familiar algorithms to non-
intuitive problems.

b. Course Objectives
 To give students the ability to write reliable codes.
 To provide skills to the students to write compact and efficient code in a quick manner
 To provide logic building capability to the student.
 To improve the logic building of students to tackle the complex problems.
 To implement the different approaches to get appropriate solutions.

c. Course Outcomes
CO1 Understand the problem and find out a better approach to solve a particular problem.
CO2 Apply the knowledge of the programming concept to develop small programs for specific
problems.
CO3 Illustrating basic algorithmic challenges through programs, encompassing concepts such as
stacks, queues, linked lists, tree traversals, graph traversals, hashing, and the calculation of
shortest paths.
CO4 Analyze the appropriate approaches for specific problems and achieve all test cases.
CO5 Create an outcome-based mini-project or idea as a solution for society.

d. Syllabus

xi
Unit-1 Data Structures Contact Hours:15
Arrays, 1. Problem statement - Given an integer array nums, return all the triplets
Stacks, Queues [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j]
linked list + nums[k] == 0.Notice that the solution set must not contain duplicate triplets.
Problem link- https://leetcode.com/problems/3sum/
2. Problem statement - You are given a 0-indexed array of integers nums of length
n. You are initially positioned at nums[0].
Each element nums[i] represents the maximum length of a forward jump from
index i. In other words, if you are at nums[i], you can jump to any nums[i + j]
where:
0 <= j <= nums[i] and
i+j<n
Return the minimum number of jumps to reach nums[n - 1]. The test cases are

xi
generated such that you can reach nums[n - 1].
Problem link- https://leetcode.com/problems/jump-game-ii/
3. Problem statement - Given a string path, which is an absolute path (starting
with a slash '/') to a file or directory in a Unix-style file system, convert it to the
simplified canonical path.
In a Unix-style file system, a period '.' refers to the current directory, a double
period '..' refers to the directory up a level, and any multiple consecutive slashes
(i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods
such as '...' are treated as file/directory names.
The canonical path should have the following format:
The path starts with a single slash '/'.
Any two directories are separated by a single slash '/'.
The path does not end with a trailing '/'.
The path only contains the directories on the path from the root directory to the
target file or directory (i.e., no period '.' or double period '..')
Return the simplified canonical path.
Problem link- https://leetcode.com/problems/simplify-path/
4. Problem statement - 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.
Problem link- https://leetcode.com/problems/implement-queue-using-
stacks/
5. Problem statement - You are given the heads of two sorted linked lists list1 and
list2.Merge the two lists into one sorted list. The list should be made by splicing
together the nodes of the first two lists. Return the head of the merged linked list.
Problem link- https://leetcode.com/problems/merge-two-sorted-lists/
6. Problem statement - Given the head of a sorted linked list, delete all nodes that
have duplicate numbers, leaving only distinct numbers from the original list. Return
the linked list sorted as well.
Problem link- https://leetcode.com/problems/remove-duplicates-from-
sorted-list-ii/

String Matching 1. Problem statement - Given two strings s and goal, return true if and only if s
can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost
position.
For example, if s = "abcde", then it will be "bcdea" after one shift.
Problem link- https://leetcode.com/problems/rotate-string/
2. Problem statement - Given two strings needle and haystack, return the index
of the first occurrence of needle in haystack, or -1 if needle is not part of
haystack.
Problemlink-https://leetcode.com/problems/find-the-index-of-the-first-
occurrence-in-a-string/
3. Problem statement - Given an array of strings queries and a string pattern,
return a boolean array answer where answer[i] is true if queries[i] matches
pattern, and false otherwise.

xi
A query word queries[i] matches pattern if you can insert lowercase English letters
pattern so that it equals the query. You may insert each character at any position
and you may not insert any characters.
Problem link- https://leetcode.com/problems/camelcase-matching/
4. Problem statement - Given two strings a and b, return the minimum number of
times you should repeat string a so that string b is a substring of it. If it is impossible
for b to be a substring of a after repeating it, return -1.
Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2
times is "abcabc".
Problem link- https://leetcode.com/problems/repeated-string-match/
5. Problem statement - A string is called a happy prefix if is a non-empty prefix
which is also a suffix (excluding itself).
Given a string s, return the longest happy prefix of s. Return an empty string "" if
no such prefix exists.
Problem link- https://leetcode.com/problems/longest-happy-prefix/
Heap model 1. Problem statement - Design a class to find the kth largest element in a stream.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums) Initializes the object with the integer k and the
stream of integers nums.
int add(int val) Appends the integer val to the stream and returns the element
representing the kth largest element in the stream.
Problem link-https://leetcode.com/problems/kth-largest-element-in-a-
stream/
2. Problem statement – You are given an array of integers stones where stones[i]
is the weight of the ith stone.
We are playing a game with the stones. On each turn, we choose the heaviest two
stones and smash them together. Suppose the heaviest two stones have weights x
and y with x <= y. The result of this smash is:
If x == y, both stones are destroyed, and
If x != y, the stone of weight x is destroyed, and the stone of weight y has new
weight y - x.
At the end of the game, there is at most one stone left.
Return the weight of the last remaining stone. If there are no stones left, return 0.
Problem link- https://leetcode.com/problems/last-stone-weight/
3. Problem statement - There are n cities connected by some number of flights.
You are given an array flight where flights[i] = [fromi, toi, pricei] indicates that
there is a flight from city fromi to city toi with cost pricei.

You are also given three integers src, dst, and k, return the cheapest price from src
to dst with at most k stops. If there is no such route, return -1.
Problem link- https://leetcode.com/problems/cheapest-flights-within-k-
stops/
4. Problem statement –In a warehouse, there is a row of barcodes, where the ith
barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may
return any answer, and it is guaranteed an answer exists.
Problem link- https://leetcode.com/problems/distant-barcodes/
5. Problem statement – You are given an integer array height representing the
heights of buildings, some bricks, and some ladders.
You start your journey from building 0 and move to the next building by possibly

xi
using bricks or ladders.
While moving from building i to building i+1 (0-indexed),
If the current building's height is greater than or equal to the next building's
height, you do not need a ladder or bricks.
If the current building's height is less than the next building's height, you can
either use one ladder or (h[i+1] - h[i]) bricks.
Return the furthest building index (0-indexed) you can reach if you use the given
ladders and bricks optimally.
Problem link-https://leetcode.com/problems/furthest-building-you-can-
reach/

Hashing 1. Problem statement – Given an array nums containing n distinct numbers in the
range [0, n], return the only number in the range that is missing from the array.
Problem link- https://leetcode.com/problems/missing-number/
2. Problem statement – Given a pattern and a string s, find if s follows the same
pattern.Here follow means a full match, such that there is a bijection between a
letter in pattern and a non-empty word in s.
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Problem link - https://leetcode.com/problems/word-pattern/
3. Problem statement –
Problem link - https://leetcode.com/problems/longest-substring-without-
repeating-characters/
4. Problem statement – Given a string s, find the length of the longest
Substring without repeating characters.
Input: s = "abcabcbb"
Output: 3
Problem link - https://leetcode.com/problems/longest-duplicate-substring/
5. Problem statement – You are given a string s. You can convert s to a
Palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.
Input: s = "aacecaaa"
Output: "aaacecaaa"
Problem link - https://leetcode.com/problems/shortest-palindrome/

Unit-2 Advanced Data Structures Contact Hours:15


Trees 1. Problem statement- Given the roots of two binary trees p and q, write a
function to check if they are the same or not.Two binary trees are considered the
same if they are structurally identical, and the nodes have the same value.
Problem link- https://leetcode.com/problems/same-tree/
2. Problem statement- Given the root of a binary tree, check whether it is a
mirror of itself (i.e., symmetric around its center).
Problem link- https://leetcode.com/problems/symmetric-tree/
3. Problem statement- Given a binary tree, determine if it is
height-balanced.
Problem link- https://leetcode.com/problems/balanced-binary-tree/
4. Problem statement- Given the root of a binary tree and an integer targetSum,
return true if the tree has a root-to-leaf path such that adding up all the values along
the path equals targetSum.
A leaf is a node with no children.
Problem link- https://leetcode.com/problems/path-sum/
xi
5. Problem statement- Given the root of a complete binary tree, return the number
of the nodes in the tree. According to Wikipedia, every level, except possibly the
last, is completely filled in a complete binary tree, and all nodes in the last level
are as far left as possible. It can have between 1 and 2h nodes inclusive at the last
level h. Design an algorithm that runs in less than O(n) time complexity.
Problem link- https://leetcode.com/problems/count-complete-tree-nodes/
6. Problem statement- 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 (possibly
updated) of the BST. Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Problem link- https://leetcode.com/problems/delete-node-in-a-bst/
7. Problem statement- Given the root of a binary tree, return the length of the
diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two
nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges
between them.
Problem link- https://leetcode.com/problems/diameter-of-binary-tree/

Graph 1. Problem statement- There is an undirected graph with n nodes, where each
node is numbered between 0 and n - 1. You are given a 2D array graph, where
graph[u] is an array of nodes that node u is adjacent to. More formally, for each v
in graph[u], there is an undirected edge between node u and node v. The graph has
the following properties:
There are no self-edges (graph[u] does not contain u).
There are no parallel edges (graph[u] does not contain duplicate values).
If v is in graph[u], then u is in graph[v] (the graph is undirected).
The graph may not be connected, meaning there may be two nodes u and v such
that there is no path between them.
A graph is bipartite if the nodes can be partitioned into two independent sets A and
B such that every edge in the graph connects a node in set A and a node in set B.
Return true if and only if it is bipartite.
Problem link- https://leetcode.com/problems/is-graph-bipartite/
2. Problem statement- An n-bit gray code sequence is a sequence of 2n integers
where:Every integer is in the inclusive range [0, 2n - 1],
The first integer is 0,
An integer appears no more than once in the sequence,
The binary representation of every pair of adjacent integers differs by exactly one
bit, and
The binary representation of the first and last integers differs by exactly one bit.
Given an integer n, return any valid n-bit gray code sequence.
Problem link- https://leetcode.com/problems/gray-code/
3. Problem statement- There are n people that are split into some unknown
number of groups. Each person is labeled with a unique ID from 0 to n - 1.
You are given an integer array groupSizes, where groupSizes[i] is the size of the
group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be
in a group of size 3.
Return a list of groups such that each person i is in a group of size groupSizes[i].
Each person should appear in exactly one group, and every person must be in a
group. If there are multiple answers, return any of them. It is guaranteed that there

xi
will be at least one valid solution for the given input.
Problem link- https://leetcode.com/problems/group-the-people-given-the-
group-size-they-belong-to/
4. Problem statement- A city's skyline is the outer contour of the silhouette
formed by all the buildings in that city when viewed from a distance. Given the
locations and heights of all the buildings, return the skyline formed by these
buildings collectively.The geometric information of each building is given in the
array buildings where buildings[i] = [lefti, righti, heighti]:
lefti is the x coordinate of the left edge of the ith building.
righti is the x coordinate of the right edge of the ith building.
heighti is the height of the ith building.
You may assume all buildings are perfect rectangles grounded on an absolutely
flat surface at height 0.
The skyline should be represented as a list of "key points" sorted by their x-
coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of
some horizontal segment in the skyline except the last point in the list, which always
has a y-coordinate 0 and is used to mark the skyline's termination where the
rightmost building ends. Any ground between the leftmost and rightmost buildings
should be part of the skyline's contour.
Problem link- https://leetcode.com/problems/the-skyline-problem/
5. Problem statement- You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a
random position.
Return the letter that was added to t.
Problem link- https://leetcode.com/problems/find-the-difference/
6. Problem statement- You are given an integer array nums. Two players are
playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the
game with a score of 0. At each turn, the player takes one of the numbers from
either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the
size of the array by 1. The player adds the chosen number to their score. The game
ends when there are no more elements in the array.
Return true if Player 1 can win the game. If the scores of both players are equal,
then player 1 is still the winner, and you should also return true. You may assume
that both players are playing optimally.
Problem link- https://leetcode.com/problems/predict-the-winner/
Divide and 1. Problem statement- The count-and-say sequence is a sequence of digit strings
conquer defined by the recursive formula:
countAndSay(1) = "1"
countAndSay(n) is the way you would "say" the digit string from countAndSay(n-
1), which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of
substrings such that each substring contains exactly one unique digit. Then for each
substring, say the number of digits, then say the digit. Finally, concatenate every
said digit.
Problem link- https://leetcode.com/problems/count-and-say/
3. Problem statement- We have two special characters:
The first character can be represented by one bit 0.
The second character can be represented by two bits (10 or 11).
Given a binary array bit that ends with 0, return true if the last character must be a
one-bit character.
Problem link- https://leetcode.com/problems/1-bit-and-2-bit-characters/
xi
4. Problem statement- You're given strings jewels representing the types of
stones that are jewels, and stones representing the stones you have. Each character
in stones is a type of stone you have. You want to know how many of the stones
you have are also jewels.
Letters are case sensitive, so "a" is considered a different type of stone from "A".
Problem link- https://leetcode.com/problems/jewels-and-stones/
5. Problem statement- You are given an n x n integer matrix board where the cells
are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of
the board (i.e. board[n - 1][0]) and alternating direction each row.
You start on square 1 of the board. In each move, starting from square curr, do the
following:
Choose a destination square next with a label in the range [curr + 1, min(curr + 6,
n2)].
This choice simulates the result of a standard 6-sided die roll: i.e., there are always
at most 6 destinations, regardless of the size of the board.
If next has a snake or ladder, you must move to the destination of that snake or
ladder. Otherwise, you move to next.
The game ends when you reach the square n2.
A board square on row r and column c has a snake or ladder if board[r][c] != -1.
The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have
a snake or ladder.
Note that you only take a snake or ladder at most once per move. If the destination
to a snake or ladder is the start of another snake or ladder, you do not follow the
subsequent snake or ladder.
Problem link- https://leetcode.com/problems/snakes-and-ladders/
6. Problem statement- You are given two jugs with capacities jug1Capacity and
jug2Capacity liters. There is an infinite amount of water supply available.
Determine whether it is possible to measure exactly targetCapacity liters using
these two jugs.
If targetCapacity liters of water are measurable, you must have targetCapacity
liters of water contained within one or both buckets by the end.
Operations allowed:
Fill any of the jugs with water.
Empty any of the jugs.
Pour water from one jug into another till the other jug is completely full, or the
first jug itself is empty.
Problem link- https://leetcode.com/problems/water-and-jug-problem/
7. Problem statement- You are given a 0-indexed string s that you must perform
k replacement operations on. The replacement operations are given as three 0-
indexed parallel arrays, indices, sources, and targets, all of length k.
To complete the ith replacement operation:
Check if the substring sources[i] occurs at index indices[i] in the original string
s.If it does not occur, do nothing.
Otherwise, if it does occur, replace that substring with targets[i].
Problem link- https://leetcode.com/problems/find-and-replace-in-string/
UNIT-3 Advanced Data Structures Contact Hours:15
Greedy 1. Problem statement- There are n children standing in a line. Each child is
assigned a rating value given in the integer array ratings.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
Return the minimum number of candies you need to have to distribute the candies
xi
to the children.
Problem link- https://leetcode.com/problems/candy/
2. Problem statement-
Problem link- https://leetcode.com/problems/best-time-to-buy-and-sell-
stock-ii/
3. Problem statement- Given a string s, remove duplicate letters so that every
letter appears once and only once. You must make sure your result is the smallest
in lexicographical order among all possible results.
Input: s = "bcabc"
Output: "abc"
Problem link- https://leetcode.com/problems/remove-duplicate-letters/
4. Problem statement- You have a long flowerbed in which some of the plots are
planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty
and 1 means not empty, and an integer n, return true if n new flowers can be
planted in the flowerbed without violating the no-adjacent-flowers rule and false
otherwise.
Problem link- https://leetcode.com/problems/can-place-flowers/
5. Problem statement- Assume you are an awesome parent and want to give
your children some cookies. But you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that
the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we
can assign the cookie j to the child i, and the child i will be content. Your goal is
to maximize the number of your content children and output the maximum
number.
Problem link- https://leetcode.com/problems/assign-cookies/
6. Problem statement- You are given an array arr which consists of only zeros and
ones, divide the array into three non-empty parts such that all of these parts
represent the same binary value.If it is possible, return any [i, j] with i + 1 < j, such
that: arr[0], arr[1], ..., arr[i] is the first part,
arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and
arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.
All three parts have equal binary values.
If it is not possible, return [-1, -1].
Note that the entire part is used when considering what binary value it represents.
For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed,
so [0,1,1] and [1,1] represent the same value.
Problem link- https://leetcode.com/problems/three-equal-parts/
Backtracking 1. Problem statement- A binary watch has 4 LEDs on the top to represent the
hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED
represents a zero or one, with the least significant bit on the right.
For example, the below binary watch reads "4:51". Given an integer turnedOn
which represents the number of LEDs that are currently on (ignoring the PM),
return all possible times the watch could represent. You may return the answer in
any order. The hour must not contain a leading zero.
For example, "01:00" is not valid. It should be "1:00".
The minute must consist of two digits and may contain a leading zero.
For example, "10:2" is not valid. It should be "10:02".
Problem link- https://leetcode.com/problems/binary-watch/
2. Problem statement- We are given n different types of stickers. Each sticker
has a lowercase English word on it.
You would like to spell out the given string target by cutting individual letters
xi
from your collection of stickers and rearranging them. You can use each sticker
more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target. If the task
is impossible, return -1.

Note: In all test cases, all words were chosen randomly from the 1000 most
common US English words, and target was chosen as a concatenation of two
random words.
Problem link- https://leetcode.com/problems/stickers-to-spell-word/
3. Problem statement- Given a directed acyclic graph (DAG) of n nodes labeled
from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in
any order.
The graph is given as follows: graph[i] is a list of all nodes you can visit from node
i (i.e., there is a directed edge from node i to node graph[i][j]).
Problem link- https://leetcode.com/problems/all-paths-from-source-to-
target/
4. Problem statement- A transformation sequence from word beginWord to word
endWord using a dictionary wordList is a sequence of words beginWord -> s1 ->
s2 -> ... -> sk such that:
Every adjacent pair of words differs by a single letter.
Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in
wordList.
sk == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return all
the shortest transformation sequences from beginWord to endWord, or an empty
list if no such sequence exists. Each sequence should be returned as a list of the
words [beginWord, s1, s2, ..., sk].
Problem link- https://leetcode.com/problems/word-ladder-ii/
5. Problem statement- Given an integer array nums of unique elements, return all
possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any
order.
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Problem link- https://leetcode.com/problems/subsets/
6. Problem statement- Given two integers n and k, return all possible
combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Problem link- https://leetcode.com/problems/combinations/
Dynamic 1. Problem statement- You are given an array prices where prices[i] is the price
Programming of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and
choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot
achieve any profit, return 0.
Problem link- https://leetcode.com/problems/best-time-to-buy-and-sell-
stock/
2. Problem statement- A message containing letters from A-Z can be encoded
into numbers using the following mapping:
'A' -> "1"
xi
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back
into letters using the reverse of the mapping above (there may be multiple ways).
For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F'
since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
The test cases are generated so that the answer fits in a 32-bit integer.
Problem link- https://leetcode.com/problems/decode-ways/
3. Problem statement- We can scramble a string s to get a string t using the
following algorithm:
If the length of the string is 1, stop.
If the length of the string is > 1, do the following:
Split the string into two non-empty substrings at a random index, i.e., if the string
is s, divide it to x and y where s = x + y.
Randomly decide to swap the two substrings or to keep them in the same order.
i.e., after this step, s may become s = x + y or s = y + x.
Apply step 1 recursively on each of the two substrings x and y.
Given two strings s1 and s2 of the same length, return true if s2 is a scrambled
string of s1, otherwise, return false.
Problem link- https://leetcode.com/problems/scramble-string/
4. Problem statement- You are climbing a staircase. It takes n steps to reach the
top. Each time you can either climb 1 or 2 steps. In how many distinct ways can
you climb to the top?
Problem link- https://leetcode.com/problems/climbing-stairs/
5. Problem statement- Given an integer array nums, find the subarray
with the largest sum, and return its sum.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Problem link- https://leetcode.com/problems/maximum-subarray/
6. Problem statement- Given a string s, return the longest Palindromic substring
in s.
Input: s = "babad"
Output: "bab"
Problem link- https://leetcode.com/problems/longest-palindromic-
substring/
7. Problem statement- You are a professional robber planning to rob houses along
a street. Each house has a certain amount of money stashed. All houses at this place
are arranged in a circle. That means the first house is the neighbor of the last one.
Meanwhile, adjacent houses have a security system connected, and it will
automatically contact the police if two adjacent houses were broken into on the
same night.
Given an integer array nums representing the amount of money of each house,
return the maximum amount of money you can rob tonight without alerting the
police.
Problem link- https://leetcode.com/problems/house-robber-ii/

xi
e. References

1. “Introduction to Algorithms” by Thomas H. Cormen, Charles E. Leiserson, Ronald


L.Rivest, and Clifford Stein.
2. Algorithms Unlocked” byThomas H. Cormen
3. “Data Structures and Algorithms Made Easy: Data Structures and AlgorithmicPuzzles”by
Narasimha Karumanchi.
4. “Grokking Algorithms: An illustrated guide for programmers and other curious
people”by Aditya Bhargava

f. Assessment Pattern - Internal and External


The performance of students is evaluated as follows:

Theory

Components Continuous Semester End


Internal Examination
Assessment (SEE)
(CAE)

Marks 60 40

Total Marks 100

g. Internal Evaluation Component

Sr. No. Type of Weightage of actual Frequency of Final Weightage in Remarks


Assessment conduct Task Internal
Assessment
1 Conduct 10 Marks per Practical 1 per 60 Marks per course
practical
2 Report 10 Marks per Practical 1 per
practical
3 Viva- Voce 20 Marks per Course 1 per Course

h. Relationship between the Course Outcomes (COs) and Program Outcomes (POs)

Mapping Between COs and POs


SN Course Outcome (CO) Mapped Programme Outcome (PO)

1 CO1 PO1, PO6, PO10, PSO1

xi
2 CO2 PO1, PO2, PO4, PO5, PO10
3 CO3 PO2, PO4, PSO1
4 CO4 PO2, PO4, PO5, PO9, PO12
5 CO5 PO3,PO8, PO11, PO12

g. CO-PO Mapping

Course
PO1 PO PO PSO PS
Outco PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9
0 11 12 1 O2
me
CO1 3 - - - - 2 - - - 1 - - 2 -
CO2 3 3 - 2 3 - - - - 2 - - - -
CO3 - 3 - 3 - - - - - - - - 2 -
CO4 - 3 - 2 3 - - - 2 - - 2 - -
CO5 - - 2 - - - - 1 - - 3 3 - -
AVG 3 3 2 2.3 3 2 - 1 2 1.5 3 2.5 2 -

PSO1
PSO2
PO1 PO1 PO1
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 0 1 2
Course Course Name 1 2 3 4 5 6 7 8 9 1 1 12
Code 0 1
21CSP- Advance 3 3 2 2.3 3 2 - 1 2 1.5 3 2.5 -
351/21ITP Programming 2
-351 Lab – II

xi
xi
List of Experiments

Experiment No Experiment Topic Experiment Name Mapped with CO

Experiment 1 Arrays, Queues and To implement the concept of CO1, CO2


Stack and Linked Arrays, Queues and Stack and
List Linked List
Problem1: Implement Jump
Game
Probem2: Remove the
duplicate elements from list
Experiment 2 String Matching To demonstrate the concept of CO1, CO2
String-Matching algorithms
Problem1: Rotate string
Problem2: Repeated string
match
Experiment 3 Heap Model To demonstrate the concept of CO1, CO2
Heap model
Problem1: Last stone weight
Problem2: Cheapest flights
with k shops
Experiment 4 Hashing To demonstrate the concept of CO3
Hashing
Problem1: Missing Number
Problem2: Longest
duplicate substring
Experiment 5 Trees To demonstrate the concept of CO3
Trees
Problem1: Balanced binary tree
Problem2: Path sum
Experiment 6 Graphs To demonstrate the concept of CO3
Graph
Problem1: Find the difference
Problem2: Predict the
winner
Experiment 7 Divide and conquer To demonstrate the concept of CO4
Divide and Conquer
Problem1: Count and Say
Problem2: Water and Jug

x
Experiment 8 Greedy To demonstrate the concept of CO4
Greedy approach
Problem1: Remove Duplicate
letters
Problem2: Assign cookies
Experiment 9 Backtracking To demonstrate the concept of CO5
Backtracking
Problem1: Binary Watch
Problem2: Word Letter II
Experiment 10 Dynamic To demonstrate the concept of CO5
Programming Dynamic Programming
Problem1: Best time to buy and
sell the stock
Problem2: Climbing Stairs

x
Experiments
Experiment 1

Experiment Topic: Arrays, Queues and Stack and Linked List


AIM: To implement the concept of Arrays, Queues and Stack and Linked List
Problem1: Implement Jump Game
https://leetcode.com/problems/jump-game-ii/
Probem2: Remove the duplicate elements from list
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Objective: 1. To learn about Array, Queue, Stack and linked list Data Structure
2. To learn different approaches to remove the duplicate elements from list.

Theory: Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value. To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should store: string a [4].

A stack is an abstract data type that holds an ordered, linear sequence of items. In contrast to a
queue, a stack is a last in, first out (LIFO) structure. A real-life example is a stack of plates: you
can only take a plate from the top of the stack, and you can only add a plate to the top of the stack.

A linked list is a collection of nodes that contain a data part and a next pointer that contains the
memory address of the next element in the list. The last element in the list has its next pointer set
to NULL, thereby indicating the end of the list. The first element of the list is called the Head.

Requirement Analysis: - Google Chrome.


Hackerrank Platform
Online Compiler

Hardware Requirement: - Computer.


Windows Power Supply.

Problem statement: -
You are given a 0-indexed array of integers nums of length n. You are initially positioned
at nums[0].
Each element nums[i] represents the maximum length of a forward jump from index i. In other
words, if you are at nums[i], you can jump to any nums[i + j] where:
 0 <= j <= nums[i] and

1
 i+ j< n
Return the minimum number of jumps to reach nums [n - 1]. The test cases are generated such that
you can reach nums[n - 1].

Example 1:
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index
0 to 1, then 3 steps to the last index.

Example 2:
Input: nums = [2,3,0,1,4]
Output: 2
Constraints:
 1 <= nums.length <= 104
 0 <= nums[i] <= 1000

Solution:
Approach: Greedy
Imagine that you are at index i in the array, the element in your current position defines the
maximum distance that you can jump. Therefore, your next step will fall somewhere in the range
[start, end], where start is the place right next to you and end is i + nums[i]. Then the question is,
where to jump?

Figure 1. How to choose where to jump.

2
To answer this question, let's think about it in the following way. Our next move will fall
somewhere between [start: end] and to find the minimum number of jumps to reach the end of the
array, we must determine which place will take us the farthest in the next jump.

Figure 2. Choose the one that leads us farther.


As you may notice, we are using a greedy approach: always jump to the place that will take us the
farthest. Greedy algorithms always make locally optimal decisions, which may or may not lead to
the globally optimal solution. Therefore, we must test our greedy algorithm to see if we can prove
that it leads to the globally optimal solution.
We will use proof by contradiction to verify that the greedy algorithm is correct. Our statement
is if at any step, we make a different choice than what our greedy algorithm would make, we can
find a better solution to the problem.

Figure 3. Proof of correctness for our greedy approach.

3
As shown in Figure 3, consider two people A and B, where A follows our greedy strategy
and B follows the optimal solution. The number at each index defines the maximum jump
distance. Let's assume that until this point, their decisions have been identical, and this is
when the disagreement happens.
Note that the choice they make for this jump will define the subarray for the next jump.
The greedy solution always picks the largest subarray. Thus, A will always have a larger
subarray than B. Henceforth, it's not possible to beat the greedy algorithm at any step and
reach the end of the array in fewer jumps; this contradicts our statement.

Algorithm
 Initialize three integer variables: jumps to count the number of jumps, current Jump End to
mark the end of the range that we can jump to, and farthest to mark the farthest place that
we can reach. Set each variable to zero.
 Iterate over nums. Note that we exclude the last element from our iteration because as soon
as we reach the last element, we do not need to jump anymore.
o Update farthest to i + nums[i] if the latter is larger.
o If we reach currentJumpEnd, it means we finished the current jump, and can begin
checking the next jump by setting currentJumpEnd = farthest.
 Return jumps.

Code:
class Solution {
public int jump(int[] nums) {
int jumps = 0, currentJumpEnd = 0, farthest = 0;
for (int i = 0; i < nums.length - 1; i++) {
// we continuously find the how far we can reach in the current jump
farthest = Math.max(farthest, i + nums[i]);
// if we have come to the end of the current jump,
// we need to make another jump
if (i == currentJumpEnd) {
jumps++;
currentJumpEnd = farthest;
}
}

4
return jumps;
}
}

Complexity Analysis
 Time Complexity: O(N)O(N)O(N) because there are NNN elements in the array and we
visit each element in the array only once.
 Space Complexity: O(1)O(1)O(1) because we don't use any additional data structures.

Problem 2 Solution:
Remove Duplicates from Sorted List II
Difficulty level: Medium
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only
distinct numbers from the original list. Return the linked list sorted as well.

Example 1:

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


Output: [1,2,5]

5
Example 2:

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


Output: [2,3]

Constraints:
 The number of nodes in the list is in the range [0, 300].
 -100 <= Node.val <= 100
 The list is guaranteed to be sorted in ascending order.

Solution Problem 2:

Let's start from the most challenging situation: the list head is to be removed.

Figure 1. The list head is to be removed.

6
The standard way to handle this use case is to use the so-called Sentinel Node. Sentinel nodes
are widely used for trees and linked lists as pseudo-heads, pseudo-tails, etc. They are purely
functional and usually don't hold any data. Their primary purpose is to standardize the situation
to avoid edge case handling.
For example, let's use here pseudo-head with zero value to ensure that the situation "delete the
list head" could never happen, and all nodes to delete are "inside" the list.
Delete Internal Nodes
The input list is sorted, and we can determine if a node is a duplicate by comparing its value to
the node after it in the list. Step by step, we could identify the current sub list of duplicates.
Now it's time to delete it using pointer manipulations. Note that the first node in the duplicates
sub list should be removed as well. That means that we have to track the predecessor of
duplicates sub list, i.e., the last node before the sub list of duplicates.

Figure 2. The sentinel head, the predecessor, and the sub list of duplicates to delete.

Having predecessor, we skip the entire duplicate sub list and make predecessor to point to the
node after the sub list.

7
Figure 2. Delete the sub list of duplicates.
Viva voce:

1. What are the different technical and real-life applications of array?


2. Give the different approaches to reverse the element in Array.
3. Can a Negative number be passed in Arraysize?
4. What is the time complexity for performing basic operations in an array?
5. What will happen if you do not initialize an Array?
6. How do I convert a Queue into the Stack?
7. What is complexity of push and pop for a Stack implemented using a Linked
List?

8
Experiment 2
Experiment Topic: String Matching
AIM: To demonstrate the concept of String-Matching algorithms
Problem1: Rotate string
https://leetcode.com/problems/rotate-string/
Probem2: Repeated string match
https://leetcode.com/problems/repeated-string-match/

Objective: 1. To learn about String-Matching algorithms.


2. To learn different approaches to rotate the string.

Theory: String matching algorithms have greatly influenced computer science and play an
essential role in various real-world problems. It helps in performing time-efficient tasks in multiple
domains. These algorithms are useful in the case of searching a string within another string. String
matching is also used in the Database schema, Network systems.

Requirement Analysis: - Google Chrome.


Hacker rank Platform
Online Compiler

Hardware Requirement: - Computer.


Windows Power Supply.

Problem statement: -
Given two strings s and goal, return true if and only if s can become goal after some number
of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.
 For example, if s = "abcde", then it will be "bcdea" after one shift.

Example 1:
Input: s = "abcde", goal = "cdeab"
Output: true

Example 2:
Input: s = "abcde", goal = "abced"
Output: false

9
Constraints:
 1 <= s.length, goal.length <= 100
 s and goal consist of lowercase English letters.

Approach #1: Brute Force [Accepted]


Intuition
For each rotation of A, let's check if it equals B.
Algorithm
More specifically, say we rotate A by s. Then, instead of A[0], A[1], A[2], ..., we have A[s],
A[s+1], A[s+2], ...; and we should check that A[s] == B[0], A[s+1] == B[1], A[s+2] == B[2], etc.

Code:
class Solution {
public boolean rotateString(String A, String B) {
if (A.length() != B.length())
return false;
if (A.length() == 0)
return true;
search:
for (int s = 0; s < A.length(); ++s) {
for (int i = 0; i < A.length(); ++i) {
if (A.charAt((s+i) % A.length()) != B.charAt(i))
continue search;
}
return true;
}
return false;
}}

Complexity Analysis

10
 Time Complexity: O(N2)O(N^2)O(N2), where NNN is the length of A. For each
rotation s, we check up to NNN elements in A and B.
 Space Complexity: O(1)O(1)O(1). We only use pointers to elements of A and B.

Problem 2: Repeated string match


Difficulty level: Medium
Problem Statement:
Given two strings a and b, return the minimum number of times you should repeat string a so
that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it,
return -1.
Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times
is "abcabc".
Example 1:
Input: a = "abcd", b = "cdabcdab"
Output: 3
Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of
it.
Example 2:
Input: a = "a", b = "aa"
Output: 2
Constraints:
1 <= a.length, b.length <= 104
a and b consist of lowercase English letters.

Code: -

int repeatedStringMatch(string A, string B) {


string s="";
int count = 0;
while(s.size()<B.size())
{
s+=A;
count++;
}
if(s.find(B)!=string::npos)
return count;
s+=A;
count++;

11
if(s.find(B)!=string::npos)
return count;

return -1;

}
};

Viva Voce:

1. Give the different string operations.


2. What are the applications of String?
3. What is string and its method?
4. How we can declare the String
5. How to fine duplicate characters in a string?

12
Experiment 3
Experiment Topic: Heap Model
Experiment Name: To demonstrate the concept of Heap model
Problem1: Last stone weight
https://leetcode.com/problems/last-stone-weight/
Probem2: Cheapest flights with k shops
https://leetcode.com/problems/cheapest-flights-within-k-stops/
Objective: 1. To learn about Heap model.
2. To learn different approaches to find the cheapest flights with k shops.

Theory: A heap is a useful data structure when it is necessary to repeatedly remove the object
with the highest (or lowest) priority, or when insertions need to be interspersed with removals of
the root node. A common implementation of a heap is the binary heap, in which the tree is a binary
tree.

Requirement Analysis: - Google Chrome.


Hacker rank Platform
Online Compiler

Hardware Requirement: - Computer.


Windows Power Supply.

Problem statement: -
You are given an array of integers stones where stones[i] is the weight of the ith stone.
We are playing a game with the stones. On each turn, we choose the heaviest two stones and
smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The
result of this smash is:
 If x == y, both stones are destroyed, and
 If x! = y, the stone of weight x is destroyed, and the stone of weight y has new weight y -
x.
At the end of the game, there is at most one stone left.
Return the weight of the last remaining stone. If there are no stones left, return 0.

13
Example 1:
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
Example 2:
Input: stones = [1]
Output: 1
Constraints:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue <Integer> maxheap=new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < stones.length ; i++) {
maxheap.add(stones[i]);
}
while (maxheap.size()!=1){
int x=maxheap.poll();
int y=maxheap.poll();
if(x!=y){
maxheap.add(x-y);
}
else if(x==y){
maxheap.add(0);
}
}
return maxheap.poll();
}
}

14
Probem2: Cheapest flights with k shops

There are n cities connected by some number of flights. You are given an array flight
where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi
with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at
most k stops. If there is no such route, return -1.

Example 1:

Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1


Output: 700

Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 =
700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.

Example 2:

15
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200

Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 =
200.

Example 3:

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0


Output: 500

Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.

Constraints:
 1 <= n <= 100
 0 <= flights.length <= (n * (n - 1) / 2)
 flights[i].length == 3

 0 <= fromi, toi < n


 fromi != toi
 1 <= pricei <= 104

16
 There will not be any multiple flights between two cities.
 0 <= src, dst, k < n
 src != dst

Algorithm
1. Create an adjacency list where adj[X] contains all the neighbors of node X and the
corresponding price it takes to move to a neighbor.
2. Initialize dist. array, storing the minimum price to reach a node from the src node. Initialize
it with large values.
3. Initialize a queue storing {node, distance} pairs. Initially, the queue should have only {src,
0}.
4. Create a variable called stops and set its value to 0.
5. Perform BFS until the queue is empty or stops > k:
 Iterate over all the nodes at a particular level. This will be done by starting a nested
loop and visiting all the nodes currently present in the queue.
 At each pair {node, distance}, iterate over all the neighbors of node. For each
neighbor, check if dist[neighbor] is less than distance + the price of the edge. If it
is, then update dist[neighbor] and push {neighbor, dist[neighbor]} onto the queue.
 After iterating over all the nodes in the current level, increase stops by one. We've
visited all the nodes at a particular level and are ready to visit the next level of
nodes.
6. Once we reach a condition where either the queue is empty or stops == k, we have our
answer as dist[dst]. If dist[dst] hasn't changed from the initial large value, then we never
reached it, so return -1.
Below is a visual example of how the algorithm works. The left side arrays represent the previous
level and the right-side arrays represent the current level.

Code:
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
vector<vector<pair<int, int>>> adj(n);
for (auto& e: flights) {
adj[e[0]].push_back({e[1], e[2]});

17
}
vector<int> dist(n, numeric_limits<int>::max());
queue<pair<int, int>> q;
q.push({src, 0});
int stops = 0;
while (stops <= k && !q.empty()) {
int sz = q.size();
// Iterate on current level.
while (sz--) {
auto [node, distance] = q.front();
q.pop();
// Iterate over neighbors of popped node.
for (auto& [neighbour, price] : adj[node]) {
if (price + distance >= dist[neighbour]) continue;
dist[neighbour] = price + distance;
q.push({neighbour, dist[neighbour]});
}}
stops++;
} return dist[dst] == numeric_limits<int>::max() ? -1 : dist[dst];
}};

Viva voce:

1. Which algorithm is best for searching and sorting?


2. What is the worst-case complexity of Heap sort?
3. Discuss the complexity of Binary Search.
4. In what situations count sort is used?
5. Discuss merge sort. Discuss the complexity of merge sort in worst case.

18
Experiment 4
Experiment Topic: Hashing
AIM: To demonstrate the concept of Hashing
Problem1: Missing Number
https://leetcode.com/problems/missing-number/
Probem2: Longest duplicate substring
https://leetcode.com/problems/longest-duplicate-substring/
Objective: 1. To learn about hashing algorithms.
2. To learn different approaches to find the missing number from sequence.

Theory: If you observe carefully, in a balanced binary search tree, if we try to search, insert or
delete any element then the time complexity for the same is O(logn). Now there might be a
situation when our applications want to do the same operations in a faster way i.e., in a more
optimized way and here hashing comes into play. In hashing, all the above operations can be
performed in O(1) i.e. constant time. It is important to understand that the worst case time
complexity for hashing remains O(n) but the average case time complexity is O(1).

Requirement Analysis: - Google Chrome.


Hacker rank Platform
Online Compiler

Hardware Requirement: - Computer.


Windows Power Supply.

Problem statement: -
Missing Number
Given an array nums containing n distinct numbers in the range [0, n], return the only number in
the range that is missing from the array.
Example 1:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the
missing number in the range since it does not appear in nums.

19
Example 2:
Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the
missing number in the range since it does not appear in nums.

Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the
missing number in the range since it does not appear in nums.
Constraints:
 n == nums.length
 1 <= n <= 104
 0 <= nums[i] <= n
 All the numbers of nums are unique.
Code:
class Solution {
public:
int missingNumber(vector<int>& nums) {
int c=0,n=nums.size();
int sum=n*(n+1)/2;
for(int i=0;i<nums.size();i++){
sum=sum-nums[i];
}
return sum;
}};

20
Longest Duplicate Substring
Difficulty level: Hard
Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or
more times. The occurrences may overlap.
Return any duplicated substring that has the longest possible length. If s does not have a
duplicated substring, the answer is "".
Example 1:
Input: s = "banana"
Output: "ana"
Example 2:
Input: s = "abcd"
Output: ""
Constraints:
 2 <= s.length <= 3 * 104
 s consists of lowercase English letters.

Code:
class Solution {

long long base = 31, MOD=1e11+19;

public:
string longestDupSubstring(string s) {

int n = s.size();
int l=0, r=n;
int mx=0,idx=0;

while(l<r){
int mid = l+ceil((r-l)/(2*1.0));
unordered_set<long long> currHash;
long long hash=0, d=1;
bool found = false;
for(int i=0; i<n; i++){
hash = (hash*base + s[i]-'a'+1)%MOD;
if(i>=mid){
hash = (MOD + hash - d*(s[i-mid]-'a'+1)%MOD)%MOD;
}else{

21
d = d*base%MOD;
}

if(i>=mid-1){
if(currHash.count(hash)){
idx = i-mid+1;
found = true;
break;
}
currHash.insert(hash);
}
}

if(!found)
r = mid-1;
else l = mid;
}
string ans = "";

for(int i = idx; i<(idx+l); i++){


ans += s[i];
}return ans;
}};

Viva voce:

1. What is a hash table?


2. If several elements are competing for the same bucket in the hash table, what
is it called?
3. What is a hash function?
4. What is direct addressing?
5. What is the search complexity in direct addressing?

22
Experiment 5
Experiment Topic: Trees
Experiment Name: To demonstrate the concept of Trees
Problem1: Balanced binary tree
https://leetcode.com/problems/balanced-binary-tree/
Probem2: Path sum
https://leetcode.com/problems/path-sum/
Objective: 1. To learn about the concept of Trees.
2. To learn different approaches to Balance the binary tree.

Theory: Trees belong to the class of non-linear data structures. Unlike linear data structures, such
as stacks or lists, where elements are stored in linear order, non-linear data structures store elements
hierarchically. Thus, the traversal of a tree or graph cannot be completed in a single run.

Requirement Analysis: - Google Chrome.


Hacker rank Platform
Online Compiler

Hardware Requirement: - Computer.


Windows Power Supply.

Problem statement: -
Problem1: Balanced binary tree
Given a binary tree, determine if it is height-balanced.

Example 1:

Input: root = [3,9,20, null,null,15,7]

23
Output: true

Example 2:

Input: root = [1,2,2,3,3,null,null,4,4]


Output: false

Example 3:
Input: root = []
Output: true
Constraints:
 The number of nodes in the tree is in the range [0, 5000].
 -104 <= Node.val <= 104
Code:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
return heightOfBT(root)!=-1;
}
int heightOfBT(TreeNode *root){

24
if(root==NULL)
return false;
if(root->left==NULL && root->right==NULL)
return true;

int lh=heightOfBT(root->left);
if(lh==-1)
return -1;

int rh=heightOfBT(root->right);
if(rh==-1)
return -1;

if(abs(lh-rh)>1)
return -1;

return max(lh,rh)+1;
}
};

Probem2: Path sum


https://leetcode.com/problems/path-sum/
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-
leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22


Output: true
Explanation: The root-to-leaf path with the target sum is shown.

25
Example 2:

Input: root = [1,2,3], targetSum = 5


Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.

Example 3:
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.

Constraints:
 The number of nodes in the tree is in the range [0, 5000].
 -1000 <= Node.val <= 1000
 -1000 <= targetSum <= 1000

Code:
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum)
{
if(root == NULL)
{
return false;
}
if(root->left == NULL && root->right == NULL && root->val - targetSum == 0)
{
return true;
}

bool left = hasPathSum(root->left,targetSum - root->val);


bool right = hasPathSum(root->right,targetSum - root->val);

return left || right;


}
};

26
Viva voce:

1. Discuss the applications of Tree Data structure.


2. What are the different tree operations?
3. Discuss different types of trees.
4. What is B tree? Discuss the applications of B tree.
5. What are AVL trees? Discuss the RR, LL rotation.

27
Experiment 6
Experiment Topic: Graphs
Experiment Name: To demonstrate the concept of Graph
Problem1: Find the difference
https://leetcode.com/problems/find-the-difference/
Probem2: Predict the winner
https://leetcode.com/problems/predict-the-winner/
Objective: 1. To learn about the concept of Graph.
2. To learn different approaches to find the difference.

Theory: A Graph is a non-linear data structure consisting of vertices and edges. The vertices are
sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in
the graph. More formally a Graph is composed of a set of vertices ( V ) and a set of edges( E ).
The graph is denoted by G (E, V).

Requirement Analysis: - Google Chrome.


Hacker rank Platform
Online Compiler

Hardware Requirement: - Computer.


Windows Power Supply.

Problem statement: -
Problem1: Find the difference
You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random
position.
Return the letter that was added to t.

Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.

Example 2:

28
Input: s = "", t = "y"
Output: "y"

Constraints:
0 <= s.length <= 1000
t.length == s.length + 1
s and t consist of lowercase English letters.
class Solution {
public:
char findTheDifference(string s, string t)
{
for(int i=0;i<s.size();i++)
t[i+1]+=t[i]-s[i]; //Passing the diff: (t[i]-s[i]) to t[i+1]
return t[t.size()-1]; //The diff will be carried over to the last element eventually
}
};
Probem2: Predict the winner
You are given an integer array nums. Two players are playing a game with this array: player 1
and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a
score of 0. At each turn, the player takes one of the numbers from either end of the array
(i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player
adds the chosen number to their score. The game ends when there are no more elements in the
array.
Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is
still the winner, and you should also return true. You may assume that both players are playing
optimally.
Example 1:
Input: nums = [1,5,2]
Output: false
Explanation: Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then
player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.

29
Hence, player 1 will never be the winner and you need to return false.

Example 2:
Input: nums = [1,5,233,7]
Output: true
Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter
which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing
player1 can win.

Constraints:
 1 <= nums.length <= 20
 0 <= nums[i] <= 107

Code:
public class Solution {
public boolean PredictTheWinner(int[] nums) {
return winner(nums, 0, nums.length - 1, 1) >= 0;
}
public int winner(int[] nums, int s, int e, int turn) {
if (s == e)

30
return turn * nums[s];
int a = turn * nums[s] + winner(nums, s + 1, e, -turn);
int b = turn * nums[e] + winner(nums, s, e - 1, -turn);
return turn * Math.max(turn * a, turn * b);
}
}

Viva voce:

1. What are the real-life applications of Graph?


2. What is BFS? Discuss the applications of DFS.
3. What is DFS? Discuss the applications of DFS.
4. Discuss the graph representation techniques?
5. What is the difference between Tree and Graph?

31
Experiment 7
Experiment Topic: Divide and Conquer
Experiment Name: To demonstrate the concept of Divide and Conquer
Problem1: Count and Say
https://leetcode.com/problems/count-and-say/
Probem2: Water and Jug Problem
https://leetcode.com/problems/water-and-jug-problem/
Objective: 1. To learn about the concept of divide and conquer approach.
2. To learn different approaches to solve the water and jug problem.

Theory: A typical Divide and Conquer algorithm solves a problem using following three steps:

Divide: This involves dividing the problem into smaller sub-problems.


Conquer: Solve sub-problems by calling recursively until solved.
Combine: Combine the sub-problems to get the final solution of the whole problem.

Requirement Analysis: - Google Chrome.


Hacker rank Platform
Online Compiler

Hardware Requirement: - Computer.


Windows Power Supply.

Problem statement: -
Problem1: Count and Say
Difficulty level: Medium
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
 countAndSay(1) = "1"
 countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1),
which is then converted into a different digit string.
To determine how you "say" a digit string, split it into the minimal number of substrings such
that each substring contains exactly one unique digit. Then for each substring, say the number of
digits, then say the digit. Finally, concatenate every said digit.
For example, the saying and conversion for digit string "3322251":

32
Given a positive integer n, return the nth term of the count-and-say sequence.

Example 1:
Input: n = 1
Output: "1"
Explanation: This is the base case.
Example 2:
Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

Constraints:
 1 <= n <= 30

33
Probem2: Water and Jug Problem
You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite
amount of water supply available. Determine whether it is possible to measure exactly target
Capacity liters using these two jugs.
If target Capacity liters of water are measurable, you must have target Capacity liters of water
contained within one or both buckets by the end.
Operations allowed:
 Fill any of the jugs with water.
 Empty any of the jugs.
 Pour water from one jug into another till the other jug is completely full, or the first jug
itself is empty.

Example 1:
Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
Output: true
Explanation: The famous Die Hard example

Example 2:
Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
Output: false

Example 3:
Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
Output: true

Constraints:
 1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106

34
Solution:
class Solution {
public:
bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
int x=jug1Capacity,y=jug2Capacity,z=x+y;
int steps[]={x,-x,-y,y}; //STEPS THAT CAN BE PERFORMED
queue<int> q;
vector<int> vis(z+1,0); // VISITED ARRAY TO KEEP NOT ITERATING THE SAME
VALUES OVER AND OVER AGAIN
q.push(0);
vis[0]=1;
while(!q.empty())
{
int node=q.front();
q.pop();

if(node==targetCapacity)
{
return true; // WHEN WE FIND THE TARGET CAPACITY ACHIEVED
}
for(int i=0;i<4;i++)
{
int newNode=node+steps[i];
if(newNode>=0 && newNode<=z && vis[newNode]==0) //BOUNDARY CHECKS
{
q.push(newNode);
vis[newNode]=1;
}
}
}
return false; // IF TARGET CAPACITY CAN NEVER BE ACHIVED
}
};

Viva voce:

1. What is the basic principle of divide and conquer?


2. Is divide and conquer always recursive?
3. What are the phases of divide and conquer?
4. Which algorithm does not follow divide and conquer?
5. What is the time complexity of divide and conquer?

35
Experiment 8
Experiment Topic: Greedy Approach
Experiment Name: To demonstrate the concept of Greedy approach
Problem1: Remove Duplicate letters
https://leetcode.com/problems/remove-duplicate-letters/
Probem2: Assign Cookies
https://leetcode.com/problems/assign-cookies/
Objective: 1. To learn about the concept of greedy approach.
2. To learn different approaches to remove the duplicates letters.

Theory: A Greedy algorithm is an approach to solving a problem that selects the most appropriate
option based on the current situation. This algorithm ignores the fact that the current best result
may not bring about the overall optimal result. Even if the initial decision was incorrect, the
algorithm never reverses it.

Requirement Analysis: - Google Chrome.


Hacker rank Platform
Online Compiler

Hardware Requirement: - Computer.


Windows Power Supply.

Problem statement: -
Problem1: Remove Duplicate letters
Given a string s, remove duplicate letters so that every letter appears once and only once. You
must make sure your result is

the smallest in lexicographical order


among all possible results.

Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:

36
Input: s = "cbacdcbc"
Output: "acdb"

Constraints:
 1 <= s.length <= 104
 s consists of lowercase English letters.
Approach:
We can use the stack to solve. When traversing the string s from left to right, we decide which
characters can be deleted. Use a dictionary to record the number of occurrences of each character.
When traversing to the i-th character, we can look at the previous character of i, assuming it is the
j-th character, if s[i]<s[j], and there is s[j] after i, then s[j] can be deleted
It should be noted here that if the string is bcab, the best answer is bca, and the last b should be
deleted, which seems to contradict the above discussion. Therefore, we need to use a stack to record
the characters we saved. After each character is deleted, a new s will be generated, and then in this
new string s, j=i-1. i.e. i and j are adjacent, the only way to ensure that s[j] deletes without throwing
an error. For example, bcabc, when traversing to a, the adjacent c can be deleted. At this time, babc
is formed. At this time, it is a new string a, and b can be deleted. When the string is bcab, when
traversing to a, the previous b is not adjacent to a, so it cannot be deleted.
class Solution {
public:
string removeDuplicateLetters(string s) {
int len = s.size();
string res = "";
unordered_map<char, int> M;
unordered_map<char, bool> V;
stack<int> S;
for (auto c : s) {
if (M.find(c) == M.end()) M[c] = 1;
else M[c]++;
}
for (unordered_map<char, int>::iterator iter=M.begin(); iter!=M.end(); iter++) V[iter->first]
= false;
cout<<M.size()<<V.size()<<endl;
for (int i=0; i<len; i++) {
M[s[i]]--;
if (V[s[i]] == true) continue;

while (!S.empty() and s[i] < s[S.top()] and M[s[S.top()]] > 0) {


V[s[S.top()]] = false;
S.pop();

37
}
S.push(i);
V[s[i]] = true;
}
while (!S.empty()) {
res = s[S.top()] + res;
S.pop();
}
return res;
}
};
Analysis
Time complexity O(n)
space complexity O(n)

Probem2: Assign Cookies


Assume you are an awesome parent and want to give your children some cookies. But, you should
give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be
content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child
i, and the child i will be content. Your goal is to maximize the number of your content children
and output the maximum number.

Example 1:
Input: g = [1,2,3], s = [1,1]
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child
whose greed factor is 1 content.
You need to output 1.

Example 2:
Input: g = [1,2], s = [1,2,3]
Output: 2
Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.

38
Constraints:
 1 <= g.length <= 3 * 104
 0 <= s.length <= 3 * 104
 1 <= g[i], s[j] <= 231 - 1

Code:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s);
};
int Solution::findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int sizeG = g.size(), sizeS = s.size(), i, j, lastJ=0, count=0,found;
for(i = 0; i < sizeG; ++i) {
for(j = lastJ, found=0; j < sizeS; ++j) {
if (s[j] >= g[i]) {
++count;
lastJ=j+1;
found = 1;
break;
}
}
if(found == 0) {
break;
}
}
return count;
}

Time complexity: O( n.log(n) )


Space complexity: O(1)

39
Viva voce:

1. Do you approach greedy problems?


2. What Are Greedy Algorithms Used For?
3. What are the different applications of greedy Approach?
4. Discuss the applications of Branch and Bound Approach.
5. Is branch and bound BFS or DFS?
6. What are the advantages of branch and bound?
7. What is the difference between Branch & bound and backtracking?
8. What is FIFO branch and bound algorithm?

40
Experiment 9
Experiment Topic: Backtracking
To demonstrate the concept of Backtracking
Problem1: Binary Watch
https://leetcode.com/problems/binary-watch/
Problem2: Word Letter II
https://leetcode.com/problems/word-ladder-ii/

Problem1: Binary Watch


A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to
represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on
the right.
 For example, the below binary watch reads "4:51".

Given an integer turnedOn which represents the number of LEDs that are currently on (ignoring
the PM), return all possible times the watch could represent. You may return the answer in any
order.
The hour must not contain a leading zero.
 For example, "01:00" is not valid. It should be "1:00".

41
The minute must consist of two digits and may contain a leading zero.
 For example, "10:2" is not valid. It should be "10:02".
Example 1:
Input: turnedOn = 1
Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"]

Example 2:
Input: turnedOn = 9
Output: []

Constraints:
 0 <= turnedOn <= 10
Solution:
char ** readBinaryWatch(int turnedOn, int* returnSize){
char** final_arr = (char**)malloc(190*sizeof(char*));
int count =0;
for (int k=0;k<720;k++){ // 720 hours a day
unsigned char h = k/60; // unsigned char from 0 to 255
unsigned char m = k%60;
int count_bit = 0;
while(h>0){
if (h%2==1){
count_bit++;
}
h>>=1;
}
while (m>0){
if (m%2==1){
count_bit++;
}
m>>=1;
}
if (count_bit==turnedOn){
final_arr[count]= (char*)malloc(8*sizeof(char));
snprintf(final_arr[count],8,"%d:%02d",k/60,k%60);
count++;
}
}
*returnSize = count;
return final_arr;}

42
Problem2: Word Letter II

A transformation sequence from word beginWord to word endWord using a


dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
 Every adjacent pair of words differs by a single letter.
 Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be
in wordList.
 sk == endWord

Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest
transformation sequences from beginWord to endWord, or an empty list if no such sequence exists.
Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].

Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
Explanation: There are 2 shortest transformation sequences:
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
"hit" -> "hot" -> "lot" -> "log" -> "cog"
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: []
Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation
sequence.

Constraints:
 1 <= beginWord.length <= 5
 endWord.length == beginWord.length
 1 <= wordList.length <= 500
 wordList[i].length == beginWord.length
 beginWord, endWord, and wordList[i] consist of lowercase English letters.
 beginWord != endWord
 All the words in wordList are unique.
 The sum of all shortest transformation sequences does not exceed 105.

Solution:

class Solution {
private:
void dfs(string word,string beginWord,vector<string> &sequence,vector<vector<string>>
&ans,unordered_map<string,int> &mp){
if(word==beginWord){
ans.push_back(sequence);

43
return;
}

int steps=mp[word];
int wordSize=beginWord.size();
for(int i=0;i<wordSize;i++){
char origChar=word[i];
for(char c='a';c<='z';c++){
word[i]=c;
if(mp[word]+1==steps){
sequence.push_back(word);
dfs(word,beginWord,sequence,ans,mp);
sequence.pop_back();
}
}
word[i]=origChar;
}

}
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>&
wordList) {
unordered_set<string> st(wordList.begin(),wordList.end());
unordered_map<string,int> mp;
mp[beginWord]=1;
queue<string> q;
q.push(beginWord);
st.erase(beginWord);
vector<vector<string>> ans;
int wordSize=beginWord.size();
//doing bfs
while(!q.empty()){
string word=q.front();
int steps=mp[word];
q.pop();
if(word==endWord)
break;
// traverse
for(int i=0;i<wordSize;i++){
char origChar=word[i];
for(char c='a';c<='z';c++){
word[i]=c;
if(st.find(word)!=st.end()){
st.erase(word);
mp[word]=steps+1;

44
q.push(word);
}
}
word[i]=origChar;
}
}

if(mp[endWord]!=0){
vector<string> sequence;
sequence.push_back(endWord);
dfs(endWord,beginWord,sequence,ans,mp);
int ansSize=ans.size();
for(int i=0;i<ansSize;i++){
reverse(ans[i].begin(),ans[i].end());
}
}
return ans;
}
};

Viva voce:

1. What is the central principle of backtracking?


2. What are the applications of Backtracking approach?
3. What is the time complexityof backtracking?
4. What type of problems can be solved with Backtracking?
5. Which data structure is used in backtracking?
6. Is backtracking same as recursion?

45
Experiment 10
Experiment Topic: Dynamic Programming
Experiment Name: To demonstrate the concept of Dynamic Programming
Problem1: Best time to buy and sell the stock
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Probem2: Climbing Stairs
https://leetcode.com/problems/climbing-stairs/

Problem1: Best time to buy and sell the stock


You are given an array price where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing
a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve anyprofit,
return 0.

Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you
sell.

Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
 1 <= prices.length <= 105
 0 <= prices[i] <= 104

46
Solution:
We need to find out the maximum difference (which will be the maximum profit) between two
numbers in the given array. Also, the second number (selling price) must be larger than the first
one (buying price).
In formal terms, we need to find max⁡(prices[j]−prices[i])\max(\text{prices[j]} -
\text{prices[i]})max(prices[j]−prices[i]), for every iii and jjj such that j>ij > ij> i.
public class Solution {
public int maxProfit(int prices[]) {
int maxprofit = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
if (profit > maxprofit)
maxprofit = profit;
}
}
return maxprofit;
}
}

Complexity Analysis
 Time complexity: O(n2)O(n^2)O(n2). Loop runs n(n−1)2\dfrac{n (n-1)}{2}2n(n−1)
times.
 Space complexity: O(1)O(1)O(1). Only two variables
- maxprofit\text{maxprofit}maxprofit and profit\text{profit}profit are used.

47
Probem2: Climbing Stairs
https://leetcode.com/problems/climbing-stairs/
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Constraints:
 1 <= n <= 45
Solution:
This is the most basic dynamic programming problem

Approach
Simple DP
Complexity
 Time complexity:
O(n)
 Space complexity:
O(n)

48
Code
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n+10);
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
for (int i = 4; i <= n; ++i) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}};

Viva voce:

1. What are the three steps of dynamic programming?


2. Is merge sort dynamic programming?
3. What are the applications of Dynamic Programming?
4. What is the time complexity of dynamic programming?
5. Is dynamic programming the same as recursion?
6. Is dynamic programming used in real life?
7. What are the steps to be followed in solving a problem using dynamic
programming technique?
8. Which algorithm uses dynamic programming approach?

49
LAB MST

Time allowed: 60mins Maximum Marks: 15

Note: Perform any one of the following (Marks: 15)

Program 1: Array (Compare the triplets)


https://www.hackerrank.com/challenges/compare-the
triplets/problem?isFullScreen=true (CO4)

Program 2: Stack and Queue (Truck tour problem)


https://www.hackerrank.com/challenges/truck-tour/problem?isFullScreen=true (CO4)

Program 3: Linked List (Whether a linked list contains a cycle)


https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-
cycle/problem?isFullScreen=true (CO5)

Program 4: Graph (Quickest way up)


https://www.hackerrank.com/challenges/the-quickest-way-up/problem?isFullScreen=true
(CO5)

Scheme of Evaluation
Worksheet Conduct Viva
6 4 5

51
Sample Answer Sheets
NA

LAB MST Marks

NA

Action Taken

NA

52
Complex Problems for Fast Learners

Problem Name Mapped with CO

Problem 1: Trapping rainwater problem: Find CO3, CO4


the maximum amount of water that can be
trapped within a given set of bars where each
bar’s width is 1 unit.

Problem 2: You are given a 0-indexed integer CO5


array stations of length n, where stations[i]
represents the number of power stations in the
ith city. Each power station can provide power
to every city in a fixed range. In other words,
if the range is denoted by r, then a power
station at city i can provide power to all cities
j such that |i - j| <= r and 0 <= i, j <= n - 1. Note
that |x| denotes absolute value. For example,
|7 - 5| = 2 and |3 - 10| = 7. The power of a city
is the total number of power stations it is being
provided power from. The government has
sanctioned building k more power stations,
each of which can be built in any city, and
have the same range as the pre- existing ones.

Given the two integers r and k, return the


maximum possible minimum power of a city,
if the additional power stations are built
optimally.

Note that you can build the k power stations in


multiple cities.

Problem 3: You are given two strings s and t. CO4,CO5


You are allowed to remove any number of
characters from the string t. The score of the
string is 0 if no characters are removed from
the string t, otherwise: Let left be the minimum
index among all removed characters. Let right
be the maximum index among all removed
characters. Then the score of the string is right
- left + 1. Return the minimum possible score
to make t a subsequence of s.
A subsequence of a string is a new string that
is formed from the original string by deleting

57
some (can be none) of the characters without
disturbing the relative positions of the
remaining characters. (i.e., "ace" is a
subsequence of "abcde" while "aec" is not).

Problem 4: You are given two 0-indexed CO4,CO5


arrays nums1 and nums2 and a 2D array
queries of queries. There are three types of
queries: For a query of type 1, queries[i] = [1,
l, r]. Flip the values from 0 to 1 and from 1 to
0 in nums1 from index l to index r. Both l and
r are 0-indexed.
For a query of type 2, queries[i] = [2, p, 0]. For
every index 0 <= i< n, set nums2[i] = nums2[i]
+ nums1[i] * p. For a query of type 3,
queries[i] = [3, 0, 0]. Find the sum of the
elements in nums2.Return an array containing
all the answers to the third type queries.

Problem 5: You are given an integer array CO5


nums and two integers min K and max K. A
fixed-bound subarray of nums is a subarray
that satisfies the following conditions: The
minimum value in the subarray is equal to
minK. The maximum value in the subarray is
equal to maxK. Return the number of fixed-
bound subarrays.A subarray is a contiguous
part of an array.

58
Problem 1: Trapping rainwater problem: Find the maximum amount of water that can
be trapped within a given set of bars where each bar’s width is 1 unit.

For example: -

Input: An array containing height of bars {7, 0, 4 , 2 , 5 , 0 , 6 ,4 , 0 , 5}

The maximum amount of water that can be trapped is 25, as shown below (blue).

59
Problem 2:You are given a 0-indexed integer array stations of length n, where stations[i]
represents the number of power stations in the ith city. Each power station can provide
power to every city in a fixed range. In other words, if the range is denoted by r, then a
power station at city i can provide power to all cities j such that |i - j| <= r and 0 <= i, j <=
n - 1.Note that |x| denotes absolute value. For example, |7 - 5| = 2 and |3 - 10| = 7.The power
of a city is the total number of power stations it is being provided power from. The
government has sanctioned building k more power stations, each of which can be built in
any city, and have the same range as the pre-existing ones.

Given the two integers r and k, return the maximum possible minimum power of a city,
if the additional power stations are built optimally.

Note that you can build the k power stations in multiple cities.

Example 1:

Input: stations = [1,2,4,5,0], r = 1, k = 2

Output: 5

Example 2:

Input: stations = [4,4,4,4], r = 0, k = 3

Output: 4

Constraints:n == stations. Length

1 <= n <= 105

0 <= stations[i] <= 105

0 <= r <= n - 1

0 <= k <= 109

Problem 3: You are given two strings s and t. you are allowed to remove any number of
characters from the string t. The score of the string is 0 if no characters are removed from
the string t, otherwise: Let left be the minimum index among all removed characters. Let
right be the maximum index among all removed characters. Then the score of the string
is right - left + 1. Return the minimum possible score to make t a subsequence of s.
A subsequence of a string is a new string that is formed from the original string by
deleting some (can be none) of the characters without disturbing the relative positions of
the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).
Example 1:
Input: s = "abacaba", t = "bzaa"
Output: 1
Example 2:
Input: s = "cde", t = "xyz"

60
Output: 3
Constraints:
1 <= s.length, t.length<= 105
s and t consist of only lowercase English letters.

Problem 4: You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries
of queries. There are three types of queries: For a query of type 1, queries[i] = [1, l, r].
Flip the values from 0 to 1 and from 1 to 0 in nums1 from index l to index r. Both l and r
are 0-indexed.
For a query of type 2, queries[i] = [2, p, 0]. For every index 0 <= i< n, set nums2[i] =
nums2[i] + nums1[i] * p. For a query of type 3, queries[i] = [3, 0, 0]. Find the sum of the
elements in nums2.Return an array containing all the answers to the third type queries.
Example 1: Input: nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]]
Output: [3]
Example 2:
Input: nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]]
Output: [5]
Constraints:
1 <= nums1.length,nums2.length<= 105
nums1.length = nums2.length
1 <= queries.length<= 105
queries[i].length = 3
0 <= l <= r <= nums1.length - 1
0 <= p <= 106
0 <= nums1[i] <= 1
0 <= nums2[i] <= 109

Problem 5: You are given an integer array nums and two integers minK and maxK. A
fixed-bound subarray of nums is a subarray that satisfies the following conditions: The
minimum value in the subarray is equal to minK. The maximum value in the subarray is
equal to maxK. Return the number of fixed-bound subarrays.A subarray is a contiguous
part of an array.
Example 1:
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Example 2:
Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
Constraints:
2 <= nums.length<= 105
1 <= nums[i], minK, maxK<= 106

61
Basic Problems for Slow Learners

Problem Name Mapped with CO

Problem 1: Given a sorted array A of size N. CO1


Find number of elements which are less than
or equal to given element X.

Problem 2: Given a sorted array of size CO1


N and an integer K, find the position (0- based
indexing) at which K is present in the array
using binary search

Problem 3: The task is to complete the


CO1, CO2
insert () function which is used to implement
Insertion Sort.

Problem 4: Given a linked list of N nodes.


CO1, CO2
The task is to reverse this list.

Problem 1: Given an sorted array A of size N. Find number of elements which are less
than or equal to given element X.
Example 1:

Input:
N=6
A[] = {1, 2, 4, 5, 8, 10}
X=9
Output:
5

62
Example 2:

Input:
N=7
A[] = {1, 2, 2, 2, 5, 7, 9}
X=2
Output:
4

Your Task:

You don't need to read input or print anything. Your task is t o c o m p l e t e t h e


function countOfElements() which takes the array A[], its size N and an integer X as inputs
and returns the number of elements which are less than or equal to given element.

Constraints:
1 <= N <= 105
1 <= Ai <= 105
0 <= X <= 105

Problem 2: Given a sorted array of size N and an integer K, find the position (0-based
indexing) at which K is present in the array using binary search.

Example 1:

Input:
N=5
arr[] = {1 2 3 4 5}
K=4
Output: 3
Explanation: 4 appears at index 3.

Example 2:

Input:
N=5
arr[] = {11 22 33 44 55}

63
K = 445
Output: -1
Explanation: 445 is not present.

Your Task:
You dont need to read input or print anything. Complete the function binarysearch() which
takes arr[], N and K as input parameters and returns the index of K in the array. If K is not
present in the array, return -1.

Expected Time Complexity: O(LogN)


Expected Auxiliary Space: O(LogN) if solving recursively and O(1) otherwise.

Constraints:

 1 <= N <= 105


 1 <= arr[i] <= 106
 1 <= K <= 106

Problem 3: The task is to complete the insert() function which is used to implement
Insertion Sort.

Example 1:

Input:
N=5
arr[] = { 4, 1, 3, 9, 7}
Output:
13479

Example 2:

Input:
N = 10
arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
Output:
70
1 2 3 4 5 6 7 8 9 10

Your Task:
You don't have to read input or print anything. Your task is to complete the
function insert() and insertionSort() where insert() takes the array, it's size and an index i and
insertionSort() uses insert function to sort the array in ascending order using insertion sort
algorithm.

Expected Time Complexity: O(N*N).


Expected Auxiliary Space: O(1).

Constraints:
1 <= N <= 1000
1 <= arr[i] <= 1000

Problem 4: Given a linked list of N nodes. The task is to reverse this list.

Example 1:

Input:
LinkedList: 1->2->3->4->5->6
Output: 6 5 4 3 2 1
Explanation: After reversing the list,
elements are 6->5->4->3->2->1.

Example 2:

Input:
LinkedList: 2->7->8->9->10
Output: 10 9 8 7 2
Explanation: After reversing the list,
elements are 10->9->8->7->2.

71
Your Task:
The task is to complete the function reverseList() with head reference as the only argument
and should return new head after reversing the list.

Expected Time Complexity: O(N).


Expected Auxiliary Space: O(1).

Constraints:
1 <= N <= 104

72
Best Practices Adopted
1. Week wise extra problems are allocated to students for Practice
2. Mini Projects are allocated to students

73
Final Award sheet

NA

List of Slow Learners and Advance Learners

NA

Overall Observation and Action Taken (Recommendation to BOS)

NA

74
Action Taken Report for Grievance

NA

75

You might also like