Collated Mock Questions
Collated Mock Questions
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple
peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly
greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5
where the peak element is 6.
Constraints:
• 1 <= nums.length <= 1000
• -231 <= nums[i] <= 231 - 1
• nums[i] != nums[i + 1] for all valid i.
----------------------------------------------------------------------------
2.Given a 0-indexed string s, permute s to get a new string t such that:
• All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length
such that s[i] is a consonant, then t[i] = s[i].
• The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of
indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value
than t[j].
Return the resulting string.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all
letters that are not vowels.
Example 1:
Input: s = "lEetcOde"
Output: "lEOtcede"
Explanation: 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted
according to their ASCII values, and the consonants remain in the same places.
Example 2:
Input: s = "lYmpH"
Output: "lYmpH"
Explanation: There are no vowels in s (all characters in s are consonants), so we return "lYmpH".
Constraints:
• 1 <= s.length <= 105
• s consists only of letters of the English alphabet in uppercase and lowercase.
----------------------------------------------------------------------------
3.
Given a string s, find the length of the longest substring without duplicate characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
--------------------------------------------------------------------------------------------
4.Given an integer array nums, find a subarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Constraints:
--------------------------------------------------------------------------------------------------------------
5.Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example 1:
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer
approach, which is more subtle.
------------------------------------------------------------------------------------------------------------------------------
6.Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
Example 1:
--------------------------------------------------------------------------------------
9.
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for
the current day.
The span of the stock's price in one day is the maximum number of consecutive days (starting from that day
and going backward) for which the stock price was less than or equal to the price of that day.
For example, if the prices of the stock in the last four days is [7,2,1,2] and the price of the stock today is 2, then
the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4
consecutive days.
Also, if the prices of the stock in the last four days is [7,34,1,2] and the price of the stock today is 8, then the
span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive
days.
Implement the StockSpanner class:
StockSpanner() Initializes the object of the class.
int next(int price) Returns the span of the stock's price given that today's price is price.
Example 1:
Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output
[null, 1, 1, 1, 2, 1, 4, 6]
Explanation
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or
equal to today's price.
stockSpanner.next(85); // return 6
--------------------------------------------------------------------------------------------------------------
10.Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([])"
Output: true
________________________________________________________________________________________
11.Once upon a time in a small village, a wise king wanted to attend as many village festivals as possible in one
day. Each festival had a start and end time, and the king could only attend one at a time. His advisor suggested
picking only the festivals that ended the earliest, so he could fit more in. The king followed this advice, selecting
the next festival that started after the last one ended. By the end of the day, he had enjoyed the most
celebrations possible without any overlaps. The villagers were amazed at his perfect schedule, and the king
declared it a royal strategy for future festivals.
Examples:
Input: start[] = [1, 3, 0, 5, 8, 5], finish[] = [2, 4, 6, 7, 9, 9]
Output: 4
Explanation: A person can attend 4 functions. The maximum set of functions that can be attended is {0, 1, 3, 4}
(These are indexes in start[] and finish[])
Input:
start[] = [1, 1, 1], finish[] = [4, 3, 2]
Output: 1
___________________________________________________________________________________________
__
12. In the bustling kingdom of AlgoLand, there lived a clever merchant named Riya who ran a workshop
offering special services. Every day, clients came to her with unique jobs — each with a deadline and a reward
(profit) for completing it. However, each job took exactly one full day, and Riya could only handle one job per
day. She quickly realized that if she wasn’t careful, she’d miss out on valuable profits by picking the wrong jobs.
One evening, she sat down and looked at all the job requests. Each had a deadline (by when it must be done)
and an offered payment. She knew that to maximize her gain, she couldn’t just pick the highest-paying job —
she had to balance deadlines and profits wisely. Riya decided to sort the jobs by profit and then schedule the
most rewarding ones first, fitting them in the latest day before their deadline if available.
By doing this smart scheduling, she managed to complete the highest number of jobs possible before their
deadlines and earned the greatest total profit. Her strategy became famous throughout AlgoLand, and people
started calling her the "Queen of Optimization.". Help Riya to complete the program to get maximum profit.
Examples :
Explanation: Job1 and Job3 can be done with maximum profit of 60 (20+40).
Input: deadline[] = [2, 1, 2, 1, 1], profit[] = [100, 19, 27, 25, 15]
Constraints:
1 ≤ deadline[i] ≤ deadline.size()
1 ≤ profit[i] ≤ 500
_______________________________________________________________________________________
_
13.In the quiet village of Splitville, there was a wise elder named Mira who had a magical pouch full of coins,
each with different values. One day, she challenged the village children: “Pick the fewest number of coins from
this pouch such that their total value is greater than the value of all the coins left behind.” The children were
puzzled — grabbing more coins meant winning, but they had to be smart.
One clever child sorted the coins from largest to smallest and picked them one by one, keeping a running
total. She stopped as soon as her sum became greater than what remained in the pouch. Mira clapped in joy
— the child had cracked the puzzle using logic, not greed. From then on, this became a famous brain game in
Splitville known as the “Heavier Half.”
Test Cases:
Constraints:
1 <= arr.size() <= 105
1 <= arr[i] <= 104
________________________________________________________________________________________
14. In the hilly kingdom of Altaria, each village was built on a tower of different height. The king wanted to even
out the landscape as much as possible, so that no tower looked too tall or too short compared to others. To do
this, he ordered the builders to either raise or lower every tower’s height by exactly K meters — no exceptions!
But there was a rule: no tower could be made shorter than zero. The royal architect, Mira, studied the towers
carefully. She realized that by strategically increasing some towers and decreasing others, she could bring
their heights closer together. Her goal was to minimize the difference between the tallest and shortest
towers after these adjustments.
She tested different combinations and figured out the perfect plan: sort the tower heights first, then consider
the highest and lowest possible new heights, and make adjustments while keeping all towers non-negative.
After a day of calculations, she presented the best possible layout to the king. Delighted, he declared Mira the
“Balancer of Towers,” and her technique was taught to architects across Altaria.
Examples :
Output: 5
Explanation: The array can be modified as {1+k, 5-k, 8-k, 10-k} = {3, 3, 6, 8}.The difference between the
largest and the smallest is 8-3 = 5.
Output: 11
Explanation: The array can be modified as {3+k, 9+k, 12-k, 16-k, 20-k} -> {6, 12, 9, 13, 17}.The difference
between the largest and the smallest is 17-6 = 11.
-----------------------------------------------------------------------------------------------------------------------------------------------------
-------------
15.In the land of Lexiconia, the royal scribe was tasked with writing a magical scroll using a string of letters. But
the scroll had one sacred rule: no two identical letters could be written side by side, or the spell would fail. The
scribe was handed strings like "aaabc" and "aaabb" and had to rearrange them so that no two adjacent
characters were the same.
He carefully counted how many times each letter appeared. If any letter appeared more than half the
length of the string (rounded up), he knew it would be impossible to arrange without breaking the rule.
Otherwise, he placed the most frequent letters at alternating positions and filled in the rest.
The king marveled as the scrolls lit up in magical light, proving the arrangements were perfect. The method
was passed down for generations as the "Non-Adjacent Rune Rule."
Test Cases:
Input: s = "aaabc"
Output: 1
Explanation: Rearranged as "abaca" or "acaba" — no adjacent duplicates.
Input: s = "aaabb"
Output: 1
Input: s = "aaaabc"
Output: 0
Explanation: Too many 'a's — cannot rearrange without adjacent duplicates.
16. In the merchant city of Greedonia, a young trader named Elric was setting off on a journey with a
magical knapsack. This bag could carry only a limited weight, but there was a twist — Elric could break any
item and take a fraction of it if needed. Each item in his inventory had a value and a weight.
His goal? Maximize the value of what he could carry without exceeding the knapsack’s capacity. So Elric
sorted all his items by their value-to-weight ratio, starting with the most valuable per kilogram. He packed
full items as long as the bag allowed, and when he reached the limit, he sliced off just enough of the next
most valuable item to fit perfectly.
With a bag filled to the brim and value maximized, Elric set off richer than ever before. The townsfolk
called this clever method “The Fractional Knapsack Strategy,” and it became a treasured algorithm in the
Guild of Traders.
Test Cases:
Input:
val = [60, 100, 120]
wt = [10, 20, 30]
capacity = 50
Output: 240.000000
Explanation: Take items 1, 2 completely and 2/3 of item 3.
Input:
val = [60, 100]
wt = [10, 20]
capacity = 50
Output: 160.000000
Explanation: Total weight is 30 < 50, take both fully.
Input:
val = [10, 20, 30]
wt = [5, 10, 15]
capacity = 100
Output: 60.000000
Explanation: Take all items; combined weight = 30 < 100.
Constraints:
1 <= val.size=wt.size <= 105
1 <= capacity <= 109
1 <= val[i], wt[i] <= 104
----------------------------------------------------------------------------------------------------------------------------------------------
-------
17.There are n houses and p water pipes in rebels Colony. Every house has at most one pipe going into it
and at most one pipe going out of it. Rebel needs to install pairs of tanks and taps in the colony according
to the following guidelines.
1. Every house with one outgoing pipe but no incoming pipe gets a tank on its roof.
2. Every house with only one incoming and no outgoing pipe gets a tap.
The Rebel council has proposed a network of pipes where connections are denoted by three input values:
ai, bi, di denoting the pipe of diameter di from house ai to house bi.
Find a more efficient way for the construction of this network of pipes. Minimize the diameter of pipes
wherever possible.
Note: The generated output will have the following format. The first line will contain t, denoting the total
number of pairs of tanks and taps installed. The next t lines contain three integers each: house number of
tank, house number of tap, and the minimum diameter of pipe between them.
Example 1:
Input:
n = 9, p = 6
a[] = {7,5,4,2,9,3}
b[] = {4,9,6,8,7,1}
d[] = {98,72,10,22,17,66}
Output:
2 8 22
3 1 66
5 6 10
Explanation:
Connected components are
Input:
n = 5, p = 3
a[] = {1, 2, 4}
b[] = {2, 3, 5}
Output:
138
4 5 12
Input:
n = 6, p = 4
a []= {1, 2, 5, 6}
b[] = {2, 3, 6, 4}
Output:
1 3 30
5 4 25
Constraints:
1<=n<=20
1<=p<=50
1<=a[i],b[i]<=20
1<=d[i]<=100
----------------------------------------------------------------------------------------------------------------------------------------------
-------------------
18.In the kingdom of Arraya, there lived a wizard who loved symmetry — especially in the form of non-
increasing sequences. One day, he stumbled upon a magical scroll with numbers that danced out of order.
The scroll read: {3, 1, 2, 1}. This bothered him, as the numbers weren't steadily decreasing or staying the
same.
To restore harmony, the wizard could use his magic to either increase or decrease any number, but he
wanted to use the least amount of magic possible. So he cast spells to gently lower numbers that
disrupted the order, ensuring each number was not greater than the one before it.
Sometimes, only a single spell was needed. Other times, when a number spiked too high, he had to use
several spells. His goal was simple: bring order to chaos using minimum effort.
And so, his technique became known across Arraya as the "Descending Order Charm."
Test Cases:
Input:
N = 4, array = [3, 1, 2, 1]
Output: 1
Explanation: Decrease 2 to 1 → new array: [3, 1, 1, 1]
Input:
N = 4, array = [3, 1, 5, 1]
Output: 4
Explanation: Decrease 5 to 1 → 4 steps
Input:
Output: 2
Constraints:
1 <= n <= 10^4
1 <= a[i] <= 10^4
19.In the twin cities of Numeria, two teams — Team A and Team B — were preparing for a grand
partner dance. Each dancer in Team A had to be paired with a dancer from Team B. But there was a
rule: the more different their dance styles (represented by numbers), the more awkward the dance —
and the higher the cost in energy.
The elders wanted the total awkwardness (the sum of absolute differences in style between all pairs) to be
as low as possible. A wise mathematician stepped in and gave a clever solution: sort both teams by their
style levels and pair them in order.
By doing this, the differences between each pair were minimized. The dance went smoothly, the crowd
cheered, and the method became known as the “Minimum Awkward Pairing” strategy — a dance of logic
and balance.
Test Cases:
Input:
N = 4, A = [4, 1, 8, 7], B = [2, 3, 6, 5]
Output: 6
Explanation: Sorted A = [1, 4, 7, 8], B = [2, 3, 5, 6]
Sum = |1-2| + |4-3| + |7-5| + |8-6| = 1 + 1 + 2 + 2 = 6
Input:
N = 3, A = [4, 1, 2], B = [2, 4, 1]
Output: 0
Explanation: Sorted A = [1, 2, 4], B = [1, 2, 4]
Sum = |1-1| + |2-2| + |4-4| = 0
Input:
N = 5 ,A = [10, 20, 30, 40, 50] , B = [12, 18, 35, 38, 52]
Output: 14
Constraints:
1 <= N <= 105
0 <= A[i] <= 109
0 <= B[i] <= 109
Sum of N over all test cases doesn't exceeds 106
----------------------------------------------------------------------------------------------------------------------------------------------
---------------------
20.In the city of Timetron, schedules were sacred. Every citizen had a list of time intervals when they
needed access to the magical gates of transit. But chaos broke out — people’s time slots overlapped, and
arguments erupted over who reserved what.
The wise Scheduler stepped in. She laid out all the intervals on a grand timeline and sorted them by their
start times. One by one, she merged overlapping time slots into larger blocks, ensuring no overlap
remained — but no time was lost either.
Soon, everyone had clean, non-overlapping windows. Conflicts vanished, the gates flowed smoothly, and
the process became known as the “Time Merge Protocol”, essential in all future scheduling.
Test Cases:
Input:
arr = [[1,3], [2,4], [6,8], [9,10]]
Output: [[1,4], [6,8], [9,10]]
Explanation: [1,3] and [2,4] overlap → merged to [1,4].
Input:
arr = [[6,8], [1,9], [2,4], [4,7]]
Output: [[1,9]]
Explanation: All intervals overlap with [1,9], so they merge into one.
Input:
Constraints:
1 ≤ arr.size() ≤ 105
0 ≤ starti ≤ endi ≤ 105
----------------------------------------------------------------------------------------------------------------------------------------------
-------
21.On a rainy Saturday afternoon, best friends Aarav and Meera were holed up inside, the thunder rumbling
in the distance. With no power and their usual gadgets dead, they turned to an old pastime—brain games."I
have a challenge," Aarav said, grinning as he grabbed a notebook. "Let’s play a game: find the longest
palindromic substring from a random sentence., now our task is to find the longest substring which is a
palindrome. If there are multiple answers, then return the first appearing substring.
Examples:
Input: s = “noonracecar”
Output: “racecar”
Explanation: There are several possible palindromic substrings like “noon”, “oo”, “racecar” etc. But the
substring “racecar” is the longest among all.
Input: s = “samantha”
Output: “ama”
Input: s = “rebecca”
Output: “ebe”
Input: s = “madam”
Output: “madam”
----------------------------------------------------------------------------------------------------------------------------- ------------
22. On a breezy summer afternoon, two best friends, Riya and Kabir, sat under the shade of a big banyan
tree in Riya’s backyard. School was out, their phones were tucked away, and boredom was beginning to
creep in.“Let’s play a word game,” Kabir said . Riya perked up. “What kind of game?”Kabir grinned. “A
palindrome challenge. We take turns giving each other strings. the task is to remove or delete the minimum
number of characters from the string so that the resultant string is a palindrome.
Examples :
Input : s = “aebcbda”
Output : 2
Explanation: Remove characters ‘e’ and ‘d’. Resultant string will be “abcba” which is a palindromic string
Input : s = “sumadamer”
Output : 4
23. In the quiet village of Sumridge, two curious friends, Arya and Rohan, were known for their love of
puzzles and challenges. One sunny afternoon, while rummaging through Arya’s attic, they found an old
wooden box filled with ancient coins of different values 1, 2, 5.. units.
“To claim the treasure of Sumridge, find all the ways to make the number N using these coins.”
Our task is to help them and the total Number of combinations are possible using these coins?”
Note: Assume that you have an infinite supply of each type of coin.
Examples:
Input: sum = 4, coins[] = [1, 2, 3]
Output: 4
Explanation: There are four solutions: [1, 1, 1, 1], [1, 1, 2], [2, 2] and [1, 3]
Input: sum = 10, coins[] = [2, 5, 3, 6]
Output: 5
Explanation: There are five solutions:
[2, 2, 2, 2, 2], [2, 2, 3, 3], [2, 2, 6], [2, 3, 5] and [5, 5]
Input: sum = 10, coins[] = [10]
Output: 1
Explanation: The only is to pick 1 coin of value 10.
Input: sum = 5, coins[] = [4]
Output: 0
Explanation: We cannot make sum 5 with the given coins
-----------------------------------------------------------------------------------------------------------------------------------------------
----------------
24. In the enchanted land of Arithmia, two young adventurers, Mira and Taran, discovered a hidden map
while exploring the ruins of an old wizard’s tower. The map led to the legendary Vault of Efficiency, said to
hold the secrets of making anything with the least effort—and the least gold. At the vault’s entrance, they
found a glowing tablet with an inscription:
“Only those who can find the path with least gold coins to treasure may enter”
Our task is to help the friends to solve the puzzle and find the Minimum gold coins required to enter.
If it is not possible to form the Taget using the given gold coins, return -1.
Examples:
Input: goldcoins[] = [25, 10, 5], Target= 30
Output: 2
Explanation : Minimum 2 goldcoins needed, 25 and 5
Input: goldcoins[] = [9, 6, 5, 1], sum = 19
Output: 3
Explanation: 19 = 9 + 9 + 1
Input: goldcoins[] = [5, 1], sum = 0
Output: 0
Explanation: For 0 sum, we do not need a coin
Input: goldcoins[] = [4, 6, 2], sum = 5
Output: -1
Explanation: Not possible to make the given Target.
----------------------------------------------------------------------------------------------------------------------------- ------------------
--------------------
25. Given a string s, the task is to find the minimum number of cuts needed for palindrome partitioning of
the given string. A partitioning of the string is a palindrome partitioning if every sub-string of the partition is
a palindrome.
Examples:
Input: s = “frfeek”
Output: 2
Explanation: We need to make minimum 2 cuts, i.e., “frf | ee | k”.
Input: s= “aaaa”
Output: 0
Explanation: The string is already a palindrome.
Input: s = “ababbbabbababa”
Output: 3
Explanation: We need to make minimum 3 cuts, i.e., “aba | bb | babbab | aba”.
----------------------------------------------------------------------------------------------------------------------------- ------------------
------
26. Given a string s of length n, the task is to count number of palindromic subsequence (need not
necessarily be distinct) present in the string s.
Example:
Input: s = “abcd”
Output: 4
Explanation: Palindromic subsequence are : “a” ,”b”, “c” ,”d”
Input: s = “aab”
Output: 4
Explanation: palindromic subsequence are :”a”, “a”, “b”, “aa”
Input: s = “anna”
Output:9
Explanation: palindromic subsequence are :“a” ,”n” ,”n” ,”a” ,”nn” ,”aa” ,”ana” ,”ana” ,”anna”
---------------------------------------------------------------------------------- -------------------------------------------------------------
27.Given two strings s1 and s2, the task is to find the length of the shortest string that has both s1 and s2 as
subsequences.
Examples:
Input: s1 = “geek”, s2 = “eke”
Output: 5
Explanation: String “geeke” has both string “geek” and “eke” as subsequences.
Input: s1 = “AGGTAB”, s2 = “GXTXAYB”
Output: 9
Explanation: String “AGXGTXAYB” has both string “AGGTAB” and “GXTXAYB” as subsequences.
-----------------------------------------------------------------------------------------------------------------------------------------------
--------
28. In the Super village of Coding, two curious friends, riya and ronak, were known for their love of puzzles
and challenges.here is the challenge for them an array of positive integers arr[] and a value sum, determine
if there is a subset of arr[] with sum equal to given sum.
Examples:
Output: true
Output: false
Output: true
----------------------------------------------------------------------------------------------------------------------------- ------------------
------
29. In the bustling village of NutriVille, Chef Nia was famous for preparing perfectly balanced meals. One day,
she received a royal request:
“Prepare a meal divided into two plates, each with the same total nutritional value, using only the
ingredients from this basket.”
She wondered:“Can I divide these into two groups so that each group adds up to the same total nutrient
value?”
Chef Nia opened the basket and found ingredients with different nutrient points:
[3, 1, 5, 9, 12]---(12+3),(1+5+9)
Examples:
Input: arr[] = [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11]
Input: arr[] = [1, 5, 3]
Output: false
Explanation: The array cannot be partitioned into equal sum sets.
30. In the valley of Numatia, a young adventurer named Lina set out to climb the Mountain of Numbers. The
mountain wasn't made of rocks—it was made of stepping stones, each marked with a number. Some were
tall, some small, all laid out in a straight path.
Lina could only step forward, and only onto a stone with a higher number than the one she was currently on.
She couldn’t go back or jump sideways. Her goal was to climb using the longest increasing path possible.
Lina began her journey.She stepped on 3, then jumped to 10, skipped 2 and 1 (they were too low), and
finally reached 20.
Examples:
Input: [10, 20, 3, 40]
Output : 10 20 40
Explanation: The length of path is 3 and the path is [10, 20, 40]
Given an integer array nums[], find the maximum product that can be achieved from any non-empty
subset of the array.
A subset of an array is a set that can be formed by removing zero or more elements without changing
the order of remaining elements. The product of a subset is the multiplication of all its elements.
Input Format:
• The first line contains an integer N — the number of elements in the array.
• The second line contains N space-separated integers representing the array elements.
Output Format:
• Print a single integer — the maximum product of any non-empty subset. For example,
Case#1:
Input:
-6 4 -5 8 -10 0 8
Output:
15360
Problem Statement:
Given a sorted array of distinct positive integers, print all triplets in the array that form a Geometric
Progression (GP) with an integral common ratio.
A triplet (a,b,c) is said to form a geometric progression if there exists a positive integer r such that
b=a⋅r and c=b⋅r.
Input Format:
• The first line contains an integer N — the number of elements in the array.
• The second line contains N space-separated distinct positive integers in sorted order.
Output Format:
Input:
1 2 6 10 18 54
Output:
2 6 18
6 18 54
Given an array where each element indicates the time required by a customer at a ticket counter,
and only one customer can be served at a time in sequence, determine the minimum total waiting
time achievable by scheduling the customers optimally
Input Format:
A single line of space-separated integers, where each integer denotes the time required by a
customer.
Output Format:
Input:
32126
Output:
17
4. Job Sequencing with Deadlines
Problem Statement:
You are given n jobs. Each job has the following properties:
• A unique ID
Each job takes exactly 1 unit of time to complete. Your task is to schedule the jobs to maximize total
profit, ensuring no two jobs overlap and each job finishes within its deadline.
Input Format:
Output Format:
• A list of selected job IDs (in order of execution) and the total profit obtained. Case#1:
Input:
A 2 100
B 1 19
C 2 27
D 1 25
Output:
5. Candy Distribution
Problem Statement:
There are n children standing in a line, each with a rating value. Each child must receive at least one
candy. Additionally, any child with a higher rating than their immediate neighbor must receive more
candies than that neighbor. The objective is to distribute candies to minimize the total number given.
Input:
An array ratings of length n where ratings[i] represents the rating of the i-th child.
Output:
Case#1:
Input:
ratings = [1, 0, 2]
Output:
Hint:
• Left to right, ensure each child has more candies than the left neighbor if rating is higher.
• Right to left, ensure the same condition holds relative to the right neighbor.
Problem Statement:
Given a string representing a queue of tasks where each character is a lowercase letter denoting a
task type, reorder the tasks so that no two identical tasks are scheduled consecutively. If no such
arrangement exists, return an empty string.
Input:
Output:
A reordered string with no two adjacent characters the same, or an empty string "" if rearrangement
is impossible.
Constraints:
• 1 ≤ tasks.length ≤ 500
Case#1:
Input: "aaabb"
Output: "ababa"
Given a rod of length n and an array of prices where the price at index i represents the selling price of
a rod of length i+1, determine the maximum revenue obtainable by cutting the rod into smaller
pieces and selling them.
Input Format :
length[]: an array representing possible rod lengths [1, 2, ..., n] price[]: an array where price[i] is the
price for rod length length[i] n: the total length of the rod to be cut
Output:
Case#1:
Input:
length[] = [1, 2, 3, 4, 5, 6, 7, 8]
Rod length: 4
Output:
Maximum Profit: 10
Given a binary string pattern containing some wildcard characters ?, generate all possible binary
strings by replacing each ? with either 0 or 1.
Input:
Output:
Case#1: Input:
1?11?00?1?
1011000011
1011000110
1011000111
1011100010
1011100011
1011100110
1011100111
1111000010
1111000011
1111000110
1111000111
1111100010
1111100011
1111100110
1111100111
Given an N x N chessboard and a knight placed at a starting position, print all possible sequences of
knight moves such that the knight visits every square exactly once (a Knight’s Tour).
Details:
• The knight moves in an "L" shape: two squares in one direction and one square
perpendicular.
• The board is numbered with move order, starting from 1 at the initial position.
Approach
• Maintain a board matrix to mark visited squares and the move number.
• At each step:
o If all squares are visited (move number = N*N), print or store the tour.
Given a string s, find the length of the longest subsequence of s that is a palindrome. A subsequence
is a sequence that can be derived from the original string by deleting some or no characters without
changing the order of the remaining characters.
This differs from the longest palindromic substring problem where the characters must be
contiguous. Here, characters can be taken from anywhere in the string as long as their relative order
is preserved.
Input Format:
Output Format:
Print a single integer denoting the length of the longest palindromic subsequence in s.
Constraints:
Case#1:
Input:
ABBDCACB
Output:
5
Problem Statement:
Given a square binary matrix consisting of 0's and 1's, find the size of the largest plus sign formed
only by 1's.
A plus sign is defined as a center cell with arms extending up, down, left, and right — all consisting of
continuous 1's — of equal length. The size of the plus is the total number of cells it covers, including
the center and the arms.
For example, a plus with arm length 2 looks like this (where 1 represents a cell in the plus and
0 elsewhere):
Input Format:
• The first line contains an integer n, the size of the square matrix.
• The next n lines each contain n integers (either 0 or 1), representing the matrix rows.
Output Format:
• Print a single integer representing the size of the largest plus sign formed by 1's in the matrix.
Constraints:
Case#1:
Input:
1 0101
11111
10101
11111
10101
Output:
17
Problem Statement: Given a directed graph with V vertices (numbered from 0 to V-1) and a list of E
edges, you are to perform a Depth-First Search (DFS) traversal of the graph starting from vertex 0.
During the traversal, record the arrival time and departure time of each vertex.
• The arrival time of a vertex is the time when it is visited (entered) for the first time during
DFS.
• The departure time of a vertex is the time when DFS finishes exploring all its neighbors and is
about to backtrack.
If the graph has disconnected components, DFS should continue to run from the next unvisited
vertex (in increasing order of vertex number).
Input Format:
• First line contains two integers: V (number of vertices) and E (number of edges).
• Next E lines each contain two integers u and v, representing a directed edge from vertex u to
vertex v.
Output Format:
• For every vertex from 0 to V-1, output its arrival and departure times in the format: Vertex v:
Arrival = a, Departure = d
Constraints:
• 1 ≤ V ≤ 10⁴
• 0 ≤ E ≤ 10⁵
• 0 ≤ u, v < V
Case#1:
Input:
67
01
02
13
14
25
35
45
Output:
Given a N x N chessboard and the starting and ending positions of a knight, find the minimum
number of steps the knight must take to reach the destination from the source.
A knight moves in an "L" shape: it can move two squares in one direction and then one square
perpendicular to that direction.
You need to determine the shortest path from the source to the destination using Breadth-First
Search (BFS), which is ideal for finding shortest paths in unweighted graphs like this one.
Input Format:
• The first line contains a single integer N, the size of the chessboard.
• The second line contains two integers sx and sy, the knight's starting coordinates (0- based
index).
• The third line contains two integers dx and dy, the knight's destination coordinates.
Output Format:
• Output a single integer representing the minimum number of steps required by the knight to
reach the destination from the source.
Constraints:
• 1 ≤ N ≤ 1000
Case#1: Input:
70
07
Output:
14. Construct the Longest Palindrome by Reordering or Deleting Characters Problem Statement:
Given a string S, construct the longest possible palindromic string that can be made by
You may reorder the characters and delete any number of them. The goal is to build the
If there are multiple answers with the same length, print any one of them.
Input Format:
Output Format:
• A single line containing the longest palindrome that can be formed by reordering or deleting
characters from S.
Constraints:
• 1 ≤ |S| ≤ 10⁵
Case#1:
Case#2:
You are managing a hotel and need to serve N guests. Each guest has a happiness value Cᵢ, which is
the time at which they prefer to be served.
However, you can serve only one guest at a time, and each guest takes exactly one unit of time to be
served. The serving times start from x = 1 and increase incrementally (1, 2, 3, ..., N).
Your task is to determine the minimum total unhappiness if the guests are optimally scheduled.
Input Format:
• The second line contains N integers: C₁, C₂, ..., Cₙ — the happiness values of the guests.
Output Format:
• 1≤N≤103
• 1≤ Ci ≤N
Case #1:
Input:
12345
Output:
Case#2:
Input:
51324
Output 4
Alex has a rectangular blanket with dimensions H × W (H = height, W = width). Alex wants to pack it
into a box that can only fit a blanket of size H1 × W1.
To do this, Alex folds the blanket in a series of steps. Each fold must be exactly parallel to one of the
edges (either horizontally or vertically), and the resulting dimensions after each fold must remain
whole numbers.
Your task is to find the minimum number of folds required to reduce the blanket from its original size
H × W to fit into the target size H1 × W1.
Input Format
• The first line contains a long integer H – the initial height of the blanket.
• The second line contains a long integer W – the initial width of the blanket.
Constraints
• 1 ≤ H, W, H1, W1 ≤ 10¹⁵
• H1 ≤ H
• W1 ≤ W
Output Format
Case #1:
Input:
Output:
Explanation:
Alex folds the blanket once along the width to reduce it from 3 to 2. The height is already acceptable,
so only one fold is required.
You are given an array A of size N and an integer K. You are allowed to swap at most one pair of
elements such that the distance between their indices is at most K (i.e., |i - j| ≤ K).
Your task is to return the lexicographically smallest array possible after such a swap (or no swap, if
the array is already optimal).
Definition: An array X is lexicographically smaller than array Y if at the first index i where they differ,
X[i] < Y[i].
Input
...
Output
N lines, each with one integer — the elements of the resulting array.
Constraints
• 1 ≤ N ≤ 10^5
• 1 ≤ A[i] ≤ 10^5
• 1≤K≤N
Case#1:
Input:
Output:
Alice has a string S of length N, and Bob gives her another string C of length M.
Bob challenges Alice to modify her string S such that the string C appears at most once as a
subsequence in S.
To help her do this, Bob gives an array A of size N, where A[i] is the cost to delete the character S[i].
Alice wants to achieve the goal with the minimum possible total cost.
Find the minimum total cost to delete characters from S such that C appears at most once
as a subsequence of S.
Input Format:
N → Length of string S
M → Length of string C
S → Alice’s string
C → Bob’s string
A[0] A[1] ... A[N-1] → Array of N integers representing deletion cost of each character in S
Output Format:
Single integer: the minimum cost to ensure C appears at most once as a subsequence of
S.
Constraints:
• 1 ≤ N, M ≤ 10⁵
• 1 ≤ A[i] ≤ 10⁵
Case#1: Input:
abcabc abc
123456
Output:
10
Problem Statement: Given N people and K days, each day is represented by an array of N numbers
indicating the order in which people arrived at the theatre. The task is to determine the size of the
largest group of people who arrive in the same relative order on all K days.
Input Format:
• The first line contains two integers N and K separated by a space — the number of people
and the number of days.
• The next K lines each contain N integers — the arrival order of people on each day.
Output Format:
• A single integer — the size of the largest group of people who arrive in the same relative
order on all K days.
Constraints:
• 1 ≤ N ≤ 1000
• 1 ≤ K ≤ 10
• 1 ≤ a[i][j] ≤ N
Case#1:
Input:
N = 4, K = 3
Day 1: [1, 3, 2, 4]
Day 2: [1, 3, 2, 4]
Day 3: [1, 4, 3, 2]
Output:
Explanation: The group consisting of people {1, 3, 2} appears in the same order on all days.
20. Maximum Number of Valid Triplets Formed From an Array Under Limit M
Problem Statement:
Given an array of size N and an integer limit M, determine the maximum number of triplets that can
be formed under these conditions:
Constraints:
• 1 ≤ N ≤ 10^5
• 1 ≤ M ≤ 10^4
• 1 ≤ arr[i] ≤ M
Input Format:
• Print a single integer — the maximum number of valid triplets that can be formed.
Case#1:
Input:
42
1222
Output:
Q1.
A new deadly virus has infected large population of a planet. A brilliant scientist has discovered a
new strain of virus which can cure this disease. Vaccine produced from this virus has various strength
depending on midichlorians count. A person is cured only if midichlorians count in vaccine batch is
more than midichlorians count of person. A doctor receives a new set of report which contains
midichlorians count of each infected patient and stores all vaccine doctor has and their midichlorians
count. You need to determine if doctor can save all patients with the vaccines he has. The number of
vaccines and patients are equal.
N :: INTEGER
The first line contains an integer, N, denoting the number of patients / vaccines count. N :: 1<N<15
Second line contains N integers (where 0<=i<N) describing the strength of each vaccine(midichlorians
count).
VacStrength[i]:: 1 to 10^4
Third line contains N integers (where 0<=i<N) describing the midichlorians count of each patient.
PatMid [i]:: 1 to 10^4
Output Format
Input:
5
123 146 454 542 456
Output:
No
Case#: 2
Input
Output:
Yes
Case#:3
Input
Output:
No
Q2.
The "Shades" Television Channel organizes a fun-filled event named "Best Couple 2025", where
married couples are invited and given many tasks and activities. Based on some criteria decided by
the jury, the best couple will be chosen.
N couples registered for the event, and each couple was given a registration number (same ID for
both). One of the specific couple's registration ID got missed. The event coordinators wanted your
help in finding the missing ID.
Write a program that takes an array of registration numbers as input and outputs the missing
registration ID.
Parameters:
N::INTEGER
The first line of the input contains the number of couples N who registered for the event. 1<=N<=5
Arr::INTEGER ARRAY
The second line of input contains 2xN-1 registration IDs of each of the couples, separated by a space
as one of the specific couple’s ID is missing.
1<=Arr[i]<=10
Case#: 1
Input:
131
Output:
Case#: 2
1527271
Output:
Case#:3 5
519216952
Output:
Q3.
Sherland State University has a mini library in the hostel, where N students can use it, but only one at
a time. A timetable is set to avoid conflicts:
• The 2nd student starts at A1 and must finish by A2, and so on.
Determine how many students can finish reading within their assigned time slots.
Parameters:
N:INTEGER
The first line input contains a single integer N denoting the number of students. T: INTEGER ARRAY
The second line of input contains N space-separated integers A1, A2, ..., and AN denoting the
moments of time by which the corresponding student should finish reading.
D: INTEGER ARRAY
The third line of input contains N space-separated integers B1, B2, ..., and BN denoting the time
required for each of the students to read.
Case#:1
Input:
1 10 15
1 10 3
Output:
2
Explanation:
N = 3 students, with the schedule [1, 10, 15] and reading times [1, 10, 3].
• Student 3: Needs 3 units, starts at 10, finishes by 13 (before 15) → (Can read). Total students
able to read: 2.
Case#:2
Input
10 20 30 45 50 51
15 5 20 12 4 1
Output: 4
Case#:3
Input
10 20 30 45 50 51 76
15 5 20 12 4 1 13
Output:
Case#:4
Input
15 20 30 45 50 51 60 70
14 5 9 12 4 1 8 8
Output:
8
Case#:5
Input
10
78 54 12 36 96 85 74 12 36 41
14 25 36 74 85 94 17 39 55 42
Output :
Case#:6
Input
10 20 20 40 50
5 10 15 10 5
Output: 4
Q4.
Given a non-empty array nums[] of integers of length N, find the top k elements that have the
highest frequency in the array. If two numbers have the same frequencies, then the larger number
should be given more preference.
Example 1:
Input:
N=6
nums = {1,1,1,2,2,3}
k=2
Output: 1 2
Example 2:
Input:
N=8
nums = {1,1,2,2,3,3,3,4}
k=2
Output: 3 2
Explanation:
Elements 1 and 2 have the same frequency ie. 2. Therefore, in this case, the answer includes the
element 2 as 2 > 1.
Parameters:
N:INTEGER
The first line of input consists of an integer N, the number of elements in the array. 1 ≤ N ≤ 25
The second line of input consists of N integers separated by spaces, representing the elements of the
array.
Case#:1
Input
111223
Output
12
Case#:2
Input
11223334
Output
32
Case#:3
Input
15
128976116576194
Output
169
Case#:4
Input
10
1289761166
Output
61
Q5.
You are given an array of integers nums, there is a sliding window of size k which is moving from the
very left of the array to the very right. You can only see the k numbers in the window. Each time the
sliding window moves right by one position.
Example 1:
Input: n=8
nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Example 2:
Input:n=1
nums = [1], k = 1
Output: [1]
Parameters:
N: INTEGER
The first line contains an integer n, the number of elements in the array. 1 ≤ N ≤ 100
The second line contains N space-separated integers, representing the elements of the array ARR.. 1
≤ ARR[i] ≤ 10000
K: INTEGER
The third line contains an integer K, the size of the sliding window. 1 ≤ K ≤ N
Case#:1
Input
1 3 -1 -3 5 3 6 7
Output
335567
Case#:2
Input
1 3 -1 -3 5 3 6 7
Output
335567
Q6.
Partition an unsorted array of positive integers in such a way that the absolute difference between
the sums of the two resulting sub-arrays is minimum. The index at which partitioning is to be done
should be considered to be part of the first sub-array.
Example
Input:
12345
Output:
Explanation:
Process:
• Index 4: Left sum = 1+2+3+4+5 = 15, Right sum = 0, Difference = 15 The minimum difference
occurs at index 2.
Parameters:
N: INTEGER
The first line contains an integer N, representing the number of elements in the array. 1 <= N <= 50
The second line contains N space-separated integers, representing the elements of the array. 1 <= N
<= 50
0<=ARR[i]<=100
Case#1:
Input
12345
Output
Case#:2
Input
10 20 30 40
Output
Case#:3
Input
15
5 10 2 8 15 4 3 9 7 12 20 11 6 1 16
Output 8
Q7.
Michael is celebrating his 20th birthday and he wishes to arrange a party for all his classmates. But
there are n tough guys in his class who are weird. They thought that this was the best occasion to
test their friendship with him. They put up conditions before Michael that they will break the
friendship unless he gives them a grand party on their chosen day. Formally, ith friend will break his
friendship if he does not receive a grand party on d th day.
Michael is not a lavish spender and can give at most one grand party daily. Also, he wants to invite
only one person in a party. So he just wonders what the maximum number of friendships he can
save. Please help Michael with this difficult task.
Parameters:
N: INTEGER
The first line will contain a single integer denoting N describing count of tough guys. 1<=N<=10
d: INTEGER ARRAY
The second line will contain n space-separated integers where ith integer corresponds to the day d th
Output Format
The output prints a single line corresponding to the maximum number of friendships Michael can
save.
Case#:1
Input
41335
Output
Case#:2
Input
10
9999888887
Output
Case#:3
Input
11
10 9 8 9 6 5 4 2 3 1 4
Output
Q8.
Mr.John is one of the old fashioned guys and he doesn't like the new smart phones with full keypads
and still uses the old keypads which require you to tap a key multiple times to type a single letter. For
example, if the keyboard has two keys, one with the letters "adef" and the other one with the letters
"zyx", then typing 'a' requires one keystroke, typing 'f' requires four keystrokes, typing 'y' requires
He recently moved to a new country where the language is such that his keypad is not the most
efficient. In every language some characters occur more often than others. He wants to create a
specific keyboard for this language that uses N different letters. He has a large body of text in this
language, and has already analyzed it to find the frequencies of all N letters of its alphabet.
You are given an array 'frequencies' with N elements. Each element of frequencies is the number of
times one of the letters in the new language appears in the text John has. Each element of
frequencies will be strictly positive. (I.e., each of the N letters occurs at least once.)
You are also given an array keySize. The number of elements of keySize is the number of keys on the
keyboard. Each element of keySize gives the maximal number of letters that maybe put on one of the
keys.
Find an assignment of letters to keys that minimizes the number of keystrokes needed to type the
entire text. Output that minimum number of keystrokes. If there is not enough room on the keys and
some letters of the alphabet won't fit, Output -1 instead.
Parameters:
N: INTEGER
The first line will contain a number 'N' that specifies the size of 'frequencies' array 1<=N<=50
The second line will contain N numbers that form the frequencies array
1<=FREQ[i]<=1000 K: INTEGER
The third line contains a number 'K' that specifies the size of the 'keySize' array 1<=K<=50
The fourth line contains K numbers that form the keySize array 1<=keySize[i]<=50
Case#:1
Input
7341
22
Output
19
Explanation
The foreign language has four letters. Let us call them W, X, Y and Z. John's text contains seven Ws,
three Xs, four Ys, and one Z. The keyboard has two keys, each of them may contain at most two
letters. One optimal solution is to use the keys "WZ" and "YX". We can then type each W and each Y
using a single keystroke, and we need two keystrokes for each X and each Z. Therefore, the total
number of keystrokes when typing the entire text will be 7x1 + 3x2 + 4x1 + 1x2 = 19.
Case#:2
Input
33842
212
Output
25
Case#:3
Input
3384215
233
Output
36
Q9.
Since each drone can only carry capacity items per trip, it might have to make multiple trips to
restock a single shelf. For operational planning, the system needs to compute the total number of
trips required to complete the entire restocking operation.
Parameters:
N : INTEGER
The first line contains an Integer N — number of shelves in the warehouse. 1 ≤ N ≤ 10⁵
The second line contains n space-separated integers — number of items needed per shelf. 1 ≤
ShelfCap[i] ≤ 10⁶
DroneCap: INTEGER
The third line Integer DroneCap — number of items a drone can carry in one trip. 1 ≤ Capacity ≤ 10⁴
Output Format:
Case#:1
Input
5 10 15 20 10
10
Output
Explanation:
Input
20 10 15 40 30 5 35
8
Output
22
Q10
A tech company is testing a smart reservation system in a high-tech movie theater. The theater has
several rows of seats, and each row's status is tracked using a binary array — 0 for an available seat,
1 for a booked seat.
When a group of friends wants to sit together, the system checks all rows to find any row with a
contiguous block of empty seats large enough to accommodate them. Due to social preferences and
proximity sensors, the group must sit together in a single row, without gaps.
Your job is to simulate this system and determine which rows have at least one continuous segment
of group_size or more empty seats.
***If none of the rows found with required number of contiguous empty seats, then return “-1”.
Parameters:
R, C : 2 INTEGERS
The first line of input will contain 2 Integers R and C describing number of rows and no:of seats in
each row.
Arr[R,C]: From 2nd line of input, R rows each with C values separated by space having 0 for empty, 1
for booked.
Group_size: INTEGER
The last line of input contains an integer, representing the size of the group fetching for contiguous
seats in the same row.
Case#:1
Input
35
10001
00100
11111
Output
0
Case#:2
Input
35
10101
01101
11111
Output
-1
Case#:3
Input
46
010001
110010
000010
001111
Output
02
Q11.
John and Bobby are brave soldiers in World War 2. They have spotted an enemy troop which is
planting bombs. They sent message to the command centre containing characters W and B where W
represents a wall and B represents a Bomb. They asked command to tell them how many walls will
be destroyed if all bombs explode at once. One bomb can destroy 2 walls on both sides.
S: STRING
First line of input contains a single string which contains two type of chars 'W' and 'B'.
Constraints
1<=LEN(S)<=1000
Case#:1
Input
WWBWWBW
Output
Case#:2
Input
BWWWBWBWW
Output
Output
Q12.
A jail has a number of prisoners and a number of treats to pass out to them. Their jailer decides the
fairest way to divide the treats is to seat the prisoners around a circular table in sequentially
numbered chairs. A chair number will be drawn from a hat. Beginning with the prisoner in that chair,
one candy will be handed to each prisoner sequentially around the table until all have been
distributed.
The jailer is playing a little joke, though. The last piece of candy looks like all the others, but it tastes
awful. Determine the chair number occupied by the prisoner who will receive that candy.
Example n=4
m=6 s=2
There are 4 prisoners, 6 pieces of candy and distribution starts at chair 2. The prisoners arrange
themselves in seats numbered 1 to 4. Prisoners receive candy at positions 2,3,4,1,2,3. The prisoner to
be warned sits in chair number 3.
Parameters:
The first line of input contains 3 integers describing the number of prisoners, the number of candies,
and the chair number to start passing out treats at.
1<=n<=10^5
1<=m<=10^5
1<=s<=n
Case#:1
Input
521
Output
Case#:2
Input
522
Output
Case#:3
Input
7 19 2
Output
Case#:4
Input
373
Output
3
Q13.
There are x number of girls and they rolled a dice in turns one after another.
If the number on the dice is 6, then the dice will be rolled again until she gets a number other than 6.
Since you know the sequence of numbers which the dice shows when rolled each time, you have to
find what is the total number of girls or if the sequence is invalid.
Parameters:
S : STRING
A single line that contains a string denoting the sequence of numbers the dice rolls on written as
string.
Constraints
1<|len(S)|<100000
Output Format
If the sequence is valid print the number of girls If the sequence is invalid print -1
Output
Explanation 0
The second person rolls the dice 3 times so the number of people will be 5.
Output
-1
Output
4
Case#:4 Input 62166844
Output
-1
Q14.
The little Monk loves to play with strings. One day he was going to a forest. On the way to the forest
he saw a Big Tree(The magical tree of the forest). The magic of the tree was that, every leaf of the
tree was in the format of string(having some value). Monk wants to have these type of leaves. But he
can take only one. Help Monk to choose the most valuable leaf.
a+b+c-d+c+d-x-y+x , i.e. it contains a string holding a mathematical expression, and the value of
Parameters:
L: INTEGER
The first line contains an integer L, describing the number of leaves on the tree Arr: INTEGER ARRAY
From 2nd line of input onwards, L lines contain a string representing expression in STRING format.
Constraints
Output Format
Case#:1
Input
4+2-5+3+2-4
1+2+3+4+5
-9+5+5
Output
15
Case#:2
Input
5+2-4+6-1-1
7-5+1
2+6+0
8-2+3
1+1+1+1
Output
Case#:3
Input
8-6+2+4+3-6+1
1+1+1+1
2+3+6+8-9
2+7+1-6
Output
10
Q15.
Given two arrays of integers, find which elements in the second array are missing from the first array.
Example
Arr=[7,2,5,3,5,3]
Brr=[7,2,5,4,6,3,5,3]
The Brr array is the original list. The numbers missing are [4,6]
Notes
• If a number occurs multiple times in the lists, you must ensure that the frequency of that
number in both lists is the same. If that is not the case, then it is also a missing number.
• The difference between the maximum and minimum numbers in the original list is less than
or equal to 100.
Parameters:
N : INTEGER
The first line of input contains an Integer, representing the size of first array Arr 1<=N<=100
The second line of input contains N space separated integer values for array Arr. 1<=Arr[i]<=10^4
M : INTEGER
The third line of input contains an Integer, representing the size of second array Brr. 1<=M<=100
The fourth line of input contains M space separated integer values for array Brr. 1<=Brr[i]<=10^4
Case#:1
Input
10
203 204 205 206 207 208 203 204 205 206
13
203 204 204 205 206 207 205 208 203 206 205 206 204
Output
Input
30 10 50 10 20
10
20 80 30 70 60 20 10 10 80 50
Output
20 80 70 60
Q16.
You have three stacks of cylinders where each cylinder has the same diameter, but they may vary in
height. You can change the height of a stack by removing and discarding its topmost cylinder any
number of times.
Find the maximum possible height of the stacks such that all of the stacks are exactly the same
height. This means you must remove zero or more cylinders from the top of zero or more of the
three stacks until they are all the same height, then return the height.
Example
h1=[1,2,1,1]
h2=[1,1,2]
h3=[1,1]
There are 4,3, and 2 cylinders in the three stacks, with their heights in the three arrays. Remove the
top 2 cylinders from h1 (heights = [1, 2]) and from h2 (heights = [1, 1]) so that the three stacks all are
2 units tall. Return 2 as the answer.
Parameters:
The first line of input contains 3 Integers, representing number of cylinders of all the 3 stacks. h1:
INTEGERS ARRAY
The second line of input contains n1 space-separated integers representing the heights of cylinders
of stack1.
The third line of input contains n2 space-separated integers representing the heights of cylinders of
stack2.
Case#:1
Input Comment
32111 h1 = [3, 2, 1, 1, 1]
432 h2 = [4, 3, 2]
1 1 4 1 h3 = [1, 1, 4, 1]
Output
Explanation
To equalize their heights, remove the first cylinder from stacks 1 and 2, and then remove the top two
cylinders from stack 3 (shown below).
1. 8-3=5
2. 9-4=5
3. 7-1-1=5
Case#:2
Input
424
1112
37
1311
Output
0
Case#:3
Input
333
444
444
444
Output
12
Case#:4
Input
542
32145
2613
55
Output
10
Q17.
Jack is working on a project to identify specific integers based on the sum of their digits. He has a
sorted list of integers and needs to find the smallest integer whose digits sum up to a given value.
Help Jack by writing a program using binary search.
Parameters:
N: INTEGER
The first line of input consists of an integer N, representing the number of elements in the list. 1 ≤ N≤
20
The second line contains N space-separated integers, representing the sorted list. 10 ≤ list elements ≤
1000
D: INTEGER
The third line contains an integer D, representing the target digit sum.
Output Format
The output prints the smallest integer whose digits sum up to D, or -1 if no such integer exists.
Case#:1
Input
12 23 30 48 56
Output
12
Case#:2
Input
23 31 45 69 71 96
15
Output
69
Case#:3
Input
5
23 45 67 68 95
17
Output
-1
Case#:4
Input
10 12 15 21 25 30 120 150
Output
12
Case#:5
Input
10 12 15 23 24 30 123 150
Output
15
Case#:6
Input
10 12 13 23 24 33 123 150
Output
24
Q18.
You are working as a data analyst for a company that collects user feedback scores for their products.
The feedback scores are recorded sequentially, and sometimes you need to identify specific feedback
points for analysis.
Given a list of feedback scores and a particular feedback score, your task is to find the position of the
second occurrence of this feedback score in the list. If the feedback score appears less than twice,
you need to handle that as well:
1. If the feedback score does not appear at all, print a message indicating that the score was not
found.
2. If the feedback score appears only once, print a message indicating that the score was found
only once.
3. If the feedback score appears more than once, print the position (index) of the second
occurrence.
Parameters:
N: INTEGER
The first input line contains an integer N, the number of feedback scores. 1 ≤ N ≤ 10
The second input line contains N space-separated integers, each representing a feedback score. 0 ≤
score≤ 100
X: INTEGER
The third input line contains an integer X, which is the feedback score you need to find the second
occurrence of.
0 ≤ X ≤ 100
Output Format
• The position of the second occurrence of the key in the list, or:
• "X Score not found." if the score is not present in the list, or:
• "X Score found only once." if the score appears only once.
Case#:1
Input
45 56 98 56 32
56
Output
Input
71 52 63 94
89
Output
Input
85 96 32 45
45
Output
Q19.
A smart city control system collects hourly vehicle counts from various sensors placed along a
highway. To predict traffic congestion, the system needs to determine the maximum average
number of vehicles over any continuous window of k hours. This will help planners schedule signal
timings and manage flow.
Given an array vehicles[] representing the number of vehicles detected every hour, and an integer k,
return the maximum average of any contiguous subarray of length k.
Parameters:
n: INTEGER
The first line of input contains an integer, n, that describes the number of hours Vehicles: INTEGERS
ARRAY
The second line of input contains n space-separated integer values, describing vehicles count per
hour
Output:
Case#:1
Input:
10 20 30 40 50 10 70 80
Output:
53.33
Explanation:
Case#:2
Input
10 20 30 40 50 60 70
Output
60.00
Case#:3
Input
6
1 12 -5 -6 50 3
Output
12.75
Case#:4
Input
Output
300.00
Q20.
You are a data analyst at a startup that helps small business owners flip electronics (buy and resell for
profit). A client comes to you with historical price data of a popular smartphone over the past few
days. The client wants to buy one unit of the smartphone on one day and sell it on a later day to
maximize their profit.
You have to write a program that determines the maximum profit that can be earned by making at
most one transaction (buy one and sell one product).
Constraints:
Parameters:
N: INTEGER
The first line of input contains an integer, N, describes number of days. Prices: INTEGER ARRAY
The second line of input contains N space separated integers representing price of smartphones for N
days.
Case#:1
Input
715364
Output
Explanation
Case#:2
Input
76431
Output
Case#:3
Input
12345
Output
Q21.
You're working with a logistics company that operates a fleet of trucks to transport goods across
multiple warehouses. Each day, a truck records the number of boxes loaded. You are given an array
of integers where each element represents the boxes loaded on the truck on day i.
The operations team wants to identify the longest streak of consecutive days during which the total
number of boxes loaded is exactly K. This will help them understand optimal loading patterns.
Write a function to find the length of the longest subarray (i.e., streak of consecutive days) where the
total number of boxes equals K.
Parameters:
N: INTEGER
The first line of input contains an integer, N, describes number of days. 1<=N<=50
The second line of input contains N space separated integers representing boxes loaded per day.
1<=BoxesLoad[i]<=1000
K: INTEGER
The third line of input contains an integer representing the target total load. 1<=K<=N
Case#:1
Input
1211132
Output
Case#:2
Input
11111
Output
Case#:3
Input
5
23111
Output
Case#:4
Input
12345
Output
Q22.
You're a backend engineer at an online advertising platform. Advertisers place bids (in dollars) in
real-time to secure ad space for a given keyword. Your system receives a stream of bid amounts in an
array at the end of the day, and the analytics team wants to identify the Kth highest bid to analyze
bidder competitiveness.
Your task is to implement a program that returns the Kth largest bid from the array of all bid values.
Parameters:
N: INTEGER
The second line of input contains N space separated integers representing the bids placed
throughout the day.
1<=BidValues[i]<=10000 K: INTEGER
The third line of input contains an integer that represents the position from the top in terms of bid
value.
1<=K<=N
Case#:1
Input
Ouput
300
Case#:2
Input
Output
500
Case#:3
Input
20 50 10 80 60 30 40
Output
60
Case#:4
Input
20 50 10 80 60 30 40
7
Output
10
Q23.
You are a data analyst at a SaaS company that tracks daily revenue deltas (profit or loss) for a newly
launched product. Each element in the revenue list represents the net change in revenue on that
day—it could be positive (gain) or negative (loss).
The management wants to analyze the best-performing consecutive period (could be any number of
days) that yielded the maximum net profit. Your task is to find the maximum sum of a contiguous
subarray from the revenue data.
Parameters:
N: INTEGER
The second line of input contains N space separated integers representing the revenues of each day.
1<=Revenues[i]<=10000
Case#:1
Input
3 -2 5 -1 6 -3
Output
11
Case#:2
Input
-5 -2 -1 -7
Output
-1
Case#:3
Input
2 3 -6 4 5
Output
Case#:4
Input
10 5 20 3
Output
38
Q24.
You are a civil engineer tasked with designing a rainwater harvesting system for a city with uneven
building heights. During a simulation, you’re given an array where each element represents the
height of a building in a row. After heavy rainfall, water gets trapped between the buildings
depending on their relative heights.
Your goal is to calculate how much water can be trapped between these buildings once the rain
stops.
Parameters:
N: INTEGER
Case#:1
Input
02040301
Output
Explanation: Water is trapped in the pits between taller buildings, e.g., 2 units at index 2, 2 at index
4, 2 at index 6, and 1 at index 7.
Case#:2
Input
30204
Output
Case#:3
Input
101
Output
1
Case#:4
Input
5412
Output
Q25.
You work for a social analytics startup that ranks public personalities based on their daily social
impact score. Each day, every individual is assigned a score, and your team is analyzing trends to
identify "influencers" — people whose impact score is greater than or equal to all the individuals that
appear after them in the list.
You are given a list of scores (ordered by the timeline), and you need to find all the influencer scores.
These are the scores that are not overshadowed by any future scores.
Parameters:
Parameters:
N: INTEGER
The second line of input contains N space separated integers representing the impact score of each
person.
Case#:1
Input
16 17 4 3 5 2
Output
17 5 2
Explanation:
• 17 is greater than everything to its right,
• 5 is greater than 2,
Case#:2
Input
7 10 4 6 5 2
Output
10 6 5 2
Case#:3
Input
1234
Output
Case#:4
Input
50 40 30 20 10
Output
50 40 30 20 10
Q26.
You are a data scientist at a digital marketing company that tracks user engagement scores day-by-
day after a new ad campaign. Each day, users generate engagement metrics (positive, negative, or
zero). The marketing manager wants to know how many periods (subarrays of days) had a total
engagement exactly equal to a target value K, which is considered a "conversion threshold."
Your task is to calculate how many such continuous periods exist in the data.
Parameters:
N: INTEGER
The first line of input contains a single integer, N, represents number of days 1<=N<=20
The second line of input contains N space separated integers, represents engagement score for each
day.
-1000<=SCORES[i]<=1000 K: INTEGER
The third line of input contains a single integer, K, represents the target engagement threshold.
Case#:1
Input
111
Output
Explanation: The subarrays [1,1] at indices (0,1) and (1,2) both sum to 2.
Case#:2
Input
123
Output
Case#:3
Input
3 4 7 2 -3 1 4 2
Output
Case#:4
Input
000
Output
Q27.
You’re building a feature for an online exam platform where students are allowed to answer certain
puzzle-type questions by submitting scrambled versions of words (i.e., anagrams of a target word).
To prevent cheating or misinterpretation, the system must verify that two submitted words are
indeed anagrams — meaning they contain the same characters in the same frequency, just possibly
in a different order.
Your task is to write a function that checks whether two given strings are valid anagrams of each
other.
Parameters:
S1: STRING
S2: STRING
Output:
Return True if the two strings are anagrams, otherwise False
Case#:1
Output True Case#:2 Input triangle integral Output True Case#:3 Input hello bello
ab
Output
False
Q28.
You are working on the backend of a secure messaging application. Each session generates a unique
token that should match the expected reference token. However, due to a known issue in the
message encoding system, tokens sometimes arrive in a rotated format (i.e., characters are shifted in
a circular fashion, but no characters are lost or added).
Your job is to verify whether the received token is simply a rotation of the original token. If so, it
should still be accepted for authentication.
Parameters:
T1: STRING
The first line of input contains a string, T1, that represents the original token. 1<=len(T1)<=100
T2: STRING
The second line of input contains a string, T2, that represents the received token. 1<=len(T2)<=100
Output:
Input
True Case#2: Input waterbottle erbottlewat Output True Case#3: Input rotation tationro
Output
False
Output
True
Output
False
Q29.
You are building a validation system for a secure messaging app that uses pattern-based character
substitution encryption. Every character in a plaintext message is consistently replaced with another
character to create the encrypted version. However, to maintain security, no two characters in the
original message can map to the same character in the encrypted one, and vice versa.
Your task is to verify whether a received encrypted message is a valid isomorphic transformation of
the original message. That means there must exist a one-to-one and consistent mapping between
Parameters:
T1: STRING
The first line of input contains a string, T1, that represents the actual message before encryption.
1<=len(T1)<=100
T2: STRING
The second line of input contains a string, T2, that represents the message after encryption.
1<=len(T2)<=100
Output:
title
Output
True
Explanation:
bar
aa
Output
False
Q30.
You’re working on a text analysis feature for a journaling app that identifies hidden patterns or
emotional symmetry in users' writings. A common marker is the presence of palindromic phrases —
sequences that read the same forward and backward.
Your job is to implement a feature that, given any input string, finds the longest palindromic
substring — a contiguous section of text that is a perfect mirror of itself.
Parameters:
S1: String
The first line of input contains a string S1, text which may include letters, numbers, symbols, or
spaces.
1<=len(S1)<=100
Output:
Explanation: Both "bab" and "aba" are valid — the first longest palindromic substring must be
returned.
Output
Case#:5
Input
noonmadamlevel
Output
Madam
This document contains 30 programming questions, categorized by the sample problem they were
inspired by. Each question includes a problem statement, parameter descriptions with constraints,
and three sample input/output cases with explanations.
Today you decided to visit the library to gather research material. You need to collect books whose
total page count is at least P. There are N unique books available in the library. Each of these books
has Bi pages.
You want to minimize the number of books you borrow to reach or exceed the target page count
P. Due to library policies, each unique book can only be borrowed at most 2 times.
If borrowing all available books (each twice) does not allow you to reach the target page count,
return -1.
Parameters: P :: INTEGER The first line contains an integer, P, denoting the target total page count. P
:: 1 -> 10^5
N :: INTEGER The next line contains an integer, N, denoting the number of unique books. N :: 1
-> 10^5
B :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the number of pages in the i^{th} book. B[i] :: 1 -> 10^5
pages achievable: Book 1 (3 pages) x 2 = 6 pages Book 2 (4 pages) x 2 = 8 pages Total max pages = 6 +
8 = 14. Since 14 < 15, it's not possible to reach the target. Return -1.
Case#: 3 Input: 7 3 1 2 6 Output: 2 Explanation: P = 7 Books available: [1, 2, 6] To reach 7 pages with
minimum books: Borrow book with 6 pages (1 time) = 6 pages. Remaining P = 1. Borrow book with 1
page (1 time) = 1 page. Total = 7 pages. Total books borrowed: 2.
You are planning to bake a large cake and need a total of W grams of ingredients. You visit a specialty
store that has N different types of ingredients. Each ingredient type Ii has a specific weight in grams.
You want to buy the minimum number of ingredient units such that their total weight is at least
W. The store policy dictates that you can buy at most 2 units of each unique ingredient type, as
supplies are limited.
If buying all available ingredient units (each twice) does not allow you to reach the target weight,
return -1.
Parameters: W :: INTEGER The first line contains an integer, W, denoting the target total weight in
grams. W :: 1 -> 10^5
N :: INTEGER The next line contains an integer, N, denoting the number of unique ingredient types. N
:: 1 -> 10^5
I :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the weight of the i^{th} ingredient type in grams. I[i] :: 1 -> 10^5
Total units bought: 2 (of 5g) + 1 (of 4g) + 1 (of 2g) = 4 units.
You are on a quest to collect treasures from an ancient ruin. Your goal is to accumulate a total
treasure value of at least V. There are N unique treasures scattered throughout the ruin. Each
treasure Ti has a specific value.
You want to find the minimum number of treasures you need to collect to reach or exceed the target
value V. Due to the fragile nature of the artifacts, each unique treasure can only be collected at most
2 times.
If collecting all available treasures (each twice) does not allow you to reach the target value, return -
1.
Parameters: V :: INTEGER The first line contains an integer, V, denoting the target total treasure
value. V :: 1 -> 10^5
N :: INTEGER The next line contains an integer, N, denoting the number of unique treasures. N
:: 1 -> 10^5
T :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the value of the i^{th} treasure. T[i] :: 1 -> 10^5
value Treasure 3 (12 value) x 2 = 24 value Total max value = 10 + 20 + 24 = 54 value. Since 54
< 60, it's not possible to reach the target. Return -1.
Case#: 3 Input: 5 2 1 3 Output: 2 Explanation: V = 5 Treasures available: [1, 3] To reach 5 value with
minimum treasures: Collect treasure with 3 value (1 time) = 3 value. Remaining V =
2. Collect treasure with 3 value (2nd time) = 3 value. Total = 6 value. Total treasures collected: 2.
You are working on a critical project and need to accumulate a total of P progress points to
complete it. There are N distinct tasks available, and each task Ti provides a certain amount of
progress points upon completion.
You want to determine the minimum number of tasks you have to complete such that you reach or
exceed the target progress points P. To avoid burnout, each unique task can only be completed at
most 2 times.
If completing all available tasks (each twice) does not allow you to reach the target progress points,
return -1.
Parameters: P :: INTEGER The first line contains an integer, P, denoting the target total progress
points. P :: 1 -> 10^5
N :: INTEGER The next line contains an integer, N, denoting the number of unique tasks. N :: 1
-> 10^5
T :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the progress points gained by completing the i^{th} task. T[i] :: 1 -> 10^5 Case#: 1 Input: 25
4 6 8 10 12 Output: 3 Explanation: P = 25 Tasks available: [6, 8, 10, 12] To reach 25 points with
minimum tasks: Complete task with 12 points (1 time) = 12 points.
Remaining P = 13. Complete task with 12 points (2nd time) = 12 points. Total = 24 points. Remaining
P = 1. Complete task with 6 points (1 time) = 6 points. Total = 30 points. Total tasks completed: 2 (of
12 points) + 1 (of 6 points) = 3 tasks.
Case#: 2 Input: 130 3 15 20 25 Output: -1 Explanation: P = 130 Tasks available: [15, 20, 25]
Maximum points achievable: Task 1 (15 points) x 2 = 30 points Task 2 (20 points) x 2 = 40
points Task 3 (25 points) x 2 = 50 points Total max points = 30 + 40 + 50 = 120 points. Since 120 < 130,
it's not possible to reach the target. Return -1.
Case#: 3 Input: 11 2 5 1 Output: 3 Explanation: P = 11 Tasks available: [5, 1] To reach 11 points with
minimum tasks: Complete task with 5 points (1 time) = 5 points. Remaining P = 6. Complete task with
5 points (2nd time) = 5 points. Total = 10 points. Remaining P = 1. Complete task with 1 point (1 time)
= 1 point. Total = 11 points. Total tasks completed: 2 (of 5 points) + 1
(of 1 point) = 3 tasks.
You are managing a cluster of M servers, all of which have the same processing capacity C. You have
N incoming requests, and the processing demand of the i^{th} request is Ri.
When a server with capacity C attempts to handle a request with demand Ri, one of three scenarios
can happen:
● If C > Ri: The request is successfully handled, and the server's remaining capacity decreases
by Ri.
● If C < Ri: The server becomes overloaded and is no longer able to process any more requests.
The request remains unhandled and must be processed by the next available server.
● If C = Ri: Both the server and the request are considered fully utilized/handled, and neither
can be used further.
The servers attempt to handle requests one by one in the given order (first request 1, then request 2,
and so on). It might be possible that before handling all the requests, all servers
become unavailable. To ensure that all requests are eventually handled, you want to remove some
requests from the front of the queue.
Your task is to find the minimum number of requests you need to remove from the front such that all
the remaining requests can be successfully handled by the available servers.
Note: If, in the last interaction, both a server and a request are fully utilized/handled and no more
servers or requests remain, it would still be considered a success since all the requests are handled.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of requests. N ::
1 -> 2*10^5
M :: INTEGER The next line contains an integer, M, denoting the number of servers. M :: 1 -> 2*10^5
C :: INTEGER The next line contains an integer, C, denoting the processing capacity of each server. C ::
1 -> 10^9
R :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the processing demand of the i^{th} request. R[i] :: 1 -> 10^9
1. Server 1 (C=10) attempts Request 1 (R=5). C > R. Server 1's capacity becomes 5. Request 1
handled.
2. Server 1 (C=5) attempts Request 2 (R=5). C = R. Server 1's capacity becomes 0. Server 1 fully
utilized. Request 2 handled.
3. Server 2 (C=10) attempts Request 3 (R=8). C > R. Server 2's capacity becomes 2. Request 3
handled.
4. Server 2 (C=2) attempts Request 4 (R=2). C = R. Server 2's capacity becomes 0. Server 2 fully
utilized. Request 4 handled. All requests are handled. No need to remove any requests from the
front.
○ Server 1 (C=1) attempts Request 5 (R=5). C < R. Server 1 overloaded. Request 5 remains. All
requests cannot be handled.
○ Server 1 (C=4) attempts Request 5 (R=5). C < R. Server 1 overloaded. Request 5 remains. All
requests cannot be handled.
○ Server 1 (C=8) handles Request 5 (R=5). C becomes 3. All requests are handled. The minimum
number of requests to remove is 3.
● If 0 requests removed:
○ Server 1 (C=5) attempts Request 1 (R=6). C < R. Server 1 overloaded. Request 1 remains. All
requests cannot be handled.
○ Server 1 (C=4) handles Request 3 (R=2). C becomes 2. Request 3 handled. All requests are
handled. The minimum number of requests to remove is 1.
You manage a fleet of M delivery trucks, all of which have the same cargo capacity K. You have N
pending orders, and the weight of the i^{th} order is Oi.
When a truck with capacity K attempts to deliver an order with weight Oi, one of three scenarios can
happen:
● If K > Oi: The order is successfully delivered, and the truck's remaining capacity decreases by
Oi.
● If K < Oi: The truck is unable to carry the order and becomes unavailable (e.g., due to
mechanical stress). The order remains undelivered and must be handled by the next available truck.
● If K = Oi: Both the truck and the order are considered fully utilized/delivered, and neither can
be used further.
The trucks attempt to deliver orders one by one in the given order (first order 1, then order 2, and so
on). It might be possible that before delivering all the orders, all trucks become unavailable. To
ensure that all orders are eventually delivered, you want to remove some orders from the front of
the queue.
Your task is to find the minimum number of orders you need to remove from the front such that all
the remaining orders can be successfully delivered by the available trucks.
Note: If, in the last interaction, both a truck and an order are fully utilized/delivered and no more
trucks or orders remain, it would still be considered a success since all the orders are delivered.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of orders. N :: 1 -
> 2*10^5
M :: INTEGER The next line contains an integer, M, denoting the number of trucks. M :: 1 -> 2*10^5
K :: INTEGER The next line contains an integer, K, denoting the cargo capacity of each truck. K
:: 1 -> 10^9
O :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the weight of the i^{th} order. O[i] :: 1 -> 10^9
1. Truck 1 (K=20) delivers Order 1 (O=10). K > O. Truck 1's capacity becomes 10. Order 1
delivered.
2. Truck 1 (K=10) delivers Order 2 (O=5). K > O. Truck 1's capacity becomes 5. Order 2 delivered.
3. Truck 1 (K=5) attempts Order 3 (O=15). K < O. Truck 1 unavailable. Order 3 remains.
4. Truck 2 (K=20) delivers Order 3 (O=15). K > O. Truck 2's capacity becomes 5. Order 3
delivered.
5. Truck 2 (K=5) delivers Order 4 (O=2). K > O. Truck 2's capacity becomes 3. Order 4 delivered.
6. Truck 2 (K=3) delivers Order 5 (O=3). K = O. Truck 2's capacity becomes 0. Truck 2 fully
utilized. Order 5 delivered. All orders are delivered. No need to remove any orders from the front.
Case#: 2 Input: 4 1 100 110 50 20 10 Output: 1 Explanation: We have 1 truck with capacity
○ Truck 1 (K=30) delivers Order 4 (O=10). K becomes 20. All orders are delivered. The minimum
number of orders to remove is 1.
● If 0 orders removed: Truck 1 (K=10) attempts Order 1 (O=12). K < O. Truck 1 unavailable.
Order 1 remains. All orders cannot be delivered.
○ Truck 1 (K=8) delivers Order 4 (O=3). K becomes 5. All orders are delivered. The minimum
number of orders to remove is 2.
You are leading a team of M developers, all of whom have the same coding capacity P. You have N
project tasks, and the complexity of the i^{th} task is Ti.
When a developer with coding capacity P attempts to complete a task with complexity Ti, one of
three scenarios can happen:
● If P > Ti: The task is successfully completed, and the developer's remaining capacity
decreases by Ti.
● If P < Ti: The developer is unable to complete the task and becomes exhausted (unavailable).
The task remains incomplete and must be assigned to the next available developer.
● If P = Ti: Both the developer and the task are considered fully utilized/completed, and neither
can be used further.
The developers attempt to complete tasks one by one in the given order (first task 1, then task 2, and
so on). It might be possible that before completing all the tasks, all developers become unavailable.
To ensure that all tasks are eventually completed, you want to remove some tasks from the front of
the queue.
Your task is to find the minimum number of tasks you need to remove from the front such that all
the remaining tasks can be successfully completed by the available developers.
Note: If, in the last interaction, both a developer and a task are fully utilized/completed and no more
developers or tasks remain, it would still be considered a success since all the tasks are completed.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of tasks. N :: 1 ->
2*10^5
M :: INTEGER The next line contains an integer, M, denoting the number of developers. M :: 1
-> 2*10^5
P :: INTEGER The next line contains an integer, P, denoting the coding capacity of each developer. P ::
1 -> 10^9
T :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the complexity of the i^{th} task. T[i] :: 1 -> 10^9
1. Developer 1 (P=15) attempts Task 1 (T=5). P > T. Developer 1's capacity becomes 10. Task 1
completed.
3. Developer 2 (P=15) attempts Task 3 (T=7). P > T. Developer 2's capacity becomes 8. Task 3
completed.
4. Developer 2 (P=8) attempts Task 4 (T=8). P = T. Developer 2's capacity becomes 0. Developer
2 fully utilized. Task 4 completed. All tasks are completed. No need to remove any tasks from the
front.
● If 0 tasks removed: Developer 1 (P=20) attempts Task 1 (T=25). P < T. Developer 1 exhausted.
Task 1 remains. All tasks cannot be completed.
○ Developer 1 (P=2) attempts Task 5 (T=8). P < T. Developer 1 exhausted. Task 5 remains. All
tasks cannot be completed.
● If 0 tasks removed: Developer 1 (P=5) attempts Task 1 (T=6). P < T. Developer 1 exhausted.
Task 1 remains. All tasks cannot be completed.
○ Developer 1 (P=4) completes Task 3 (T=2). P becomes 2. All tasks are completed. The
minimum number of tasks to remove is 1.
You are managing M water sources (e.g., pumps, wells), all of which have the same total water
volume W. You have N empty tanks to fill, and the capacity of the i^{th} tank is Ti.
When a water source with volume W attempts to fill a tank with capacity Ti, one of three scenarios
can happen:
● If W > Ti: The tank is successfully filled, and the water source's remaining volume
decreases by Ti.
● If W < Ti: The water source is unable to fill the tank completely and becomes depleted
(unavailable). The tank remains partially filled and must be filled by the next available water source.
● If W = Ti: Both the water source and the tank are considered fully utilized/filled, and neither
can be used further.
The water sources attempt to fill tanks one by one in the given order (first tank 1, then tank 2, and so
on). It might be possible that before filling all the tanks, all water sources become unavailable. To
ensure that all tanks are eventually filled, you want to remove some tanks from the front of the
queue.
Your task is to find the minimum number of tanks you need to remove from the front such that all
the remaining tanks can be successfully filled by the available water sources.
Note: If, in the last interaction, both a water source and a tank are fully utilized/filled and no more
water sources or tanks remain, it would still be considered a success since all the tanks are filled.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of tanks. N :: 1 ->
2*10^5
M :: INTEGER The next line contains an integer, M, denoting the number of water sources. M :: 1 ->
2*10^5
W :: INTEGER The next line contains an integer, W, denoting the total water volume of each source.
W :: 1 -> 10^9
T :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the capacity of the i^{th} tank. T[i] :: 1 -> 10^9
Case#: 1 Input: 5 3 100 50 20 10 5 15 Output: 0 Explanation: We have 3 water sources, each
1. Source 1 (W=100) fills Tank 1 (T=50). W > T. Source 1's volume becomes 50. Tank 1 filled.
2. Source 1 (W=50) fills Tank 2 (T=20). W > T. Source 1's volume becomes 30. Tank 2 filled.
3. Source 1 (W=30) fills Tank 3 (T=10). W > T. Source 1's volume becomes 20. Tank 3 filled.
4. Source 1 (W=20) fills Tank 4 (T=5). W > T. Source 1's volume becomes 15. Tank 4 filled.
5. Source 1 (W=15) fills Tank 5 (T=15). W = T. Source 1's volume becomes 0. Source 1 fully
utilized. Tank 5 filled. All tanks are filled. No need to remove any tanks from the front.
● If 0 tanks removed: Source 1 (W=50) attempts Tank 1 (T=60). W < T. Source 1 depleted. Tank
1 remains. All tanks cannot be filled.
○ Source 1 (W=35) fills Tank 4 (T=20). W becomes 15. All tanks are filled. The minimum number
of tanks to remove is 1.
● If 0 tanks removed:
○ Source 1 (W=10) attempts Tank 1 (T=12). W < T. Source 1 depleted. Tank 1 remains.
○ Source 2 (W=10) attempts Tank 1 (T=12). W < T. Source 2 depleted. Tank 1 remains. All tanks
cannot be filled.
○ Source 2 (W=7) fills Tank 5 (T=5). W becomes 2. All tanks are filled. The minimum number of
tanks to remove is 1.
You are tasked with deepening a riverbed to ensure smooth navigation. You know the current depth
of each segment of the riverbed, i.e., the i^{th} segment is Di meters deep.
You need to transform the riverbed into a strictly increasing depth profile for navigation, meaning for
each i^{th} segment where 2 \le i \le N, the resultant Di-1 < Di. To achieve this, you employ a
powerful dredging team to help you deepen the segments. On day D, the team can increase the
depth for each segment that you scheduled that day by 2^D - 1 meters each.
You are allowed to assign the team to dredge on multiple segments and/or dredge on the same
segments for multiple days.
Your task is to find the minimum number of days needed to transform the riverbed as per your
requirements.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in D.
N :: 1 -> 10^5
D :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing Di, the current depth of the i^{th} segment. D[i] :: -10^9 -> 10^9
Case#: 1 Input: 3 1 2 3 Output: 0 Explanation: The depths [1, 2, 3] are already strictly increasing. No
dredging is needed.
Case#: 2 Input: 2 5 2 Output: 3 Explanation: Initial depths: [5, 2]. We need D_final[0] < D_final[1].
Calculate target final depths: D_final[0] = D[0] = 5 D_final[1] = max(D[1], D_final[0] + 1) = max(2, 5 +
1) = max(2, 6) = 6. Target D_final = [5, 6]. Needed increases: D[0]: D_final[0] - D[0] = 5 - 5 = 0. (No
increase needed) D[1]: D_final[1] - D[1] = 6 - 2 = 4. For an increase of 4: We need to find the
minimum D such that 2^D - 1 \ge 4. 2^1 - 1 = 1 2^2 - 1 = 3 2^3 - 1 = 7 The smallest D is 3. The
maximum day needed is 3.
Case#: 3 Input: 4 10 10 5 5 Output: 4 Explanation: Initial depths: [10, 10, 5, 5]. Calculate target final
depths (D_final[i] = max(D[i], D_final[i-1] + 1)): D_final[0] = D[0] = 10 D_final[1] = max(D[1], D_final[0]
+ 1) = max(10, 10 + 1) = max(10, 11) = 11 D_final[2] = max(D[2], D_final[1]
max(5, 13) = 13 Target D_final = [10, 11, 12, 13]. Needed increases: D[0]: D_final[0] - D[0] = 10
D for 8 is 4 (2^4 - 1 = 15 \ge 8). The maximum day needed across all segments is max(0, 1, 3,
4) = 4.
You need to flatten a mountain range for a new railway line. You know the current height of each
peak, i.e., the i^{th} peak is Hi meters tall.
You need to transform the mountain range into a strictly downward sloping profile for the railway,
meaning for each i^{th} peak where 2 \le i \le N, the resultant Hi-1 > Hi. To do so, you employ a
powerful blasting team to help you reduce the height of the peaks. On day D, the team can reduce
the height for each peak that you scheduled that day by 2^D - 1 meters each.
You are allowed to assign the team to blast on multiple peaks and/or blast on the same peaks for
multiple days.
Your task is to find the minimum number of days needed to transform the mountain range as per
your requirements.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in H.
N :: 1 -> 10^5
H :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing Hi, the height of the i^{th} peak. H[i] :: -10^9 -> 10^9
Case#: 1 Input: 3 10 9 8 Output: 0 Explanation: The heights [10, 9, 8] are already strictly decreasing.
No blasting is needed.
Case#: 2 Input: 2 10 14 Output: 3 Explanation: Initial heights: [10, 14]. We need H_final[0] >
H_final[1]. Calculate target final heights (H_final[i] = min(H[i], H_final[i-1] - 1)): H_final[0] = H[0] = 10
H_final[1] = min(H[1], H_final[0] - 1) = min(14, 10 - 1) = min(14, 9) = 9. Target H_final = [10, 9].
Needed reductions: H[0]: H[0] - H_final[0] = 10 - 10 = 0. (No reduction needed) H[1]: H[1] - H_final[1]
= 14 - 9 = 5. For a reduction of 5: We need to find the minimum D such that 2^D - 1
\ge 5. 2^1 - 1 = 1 2^2 - 1 = 3 2^3 - 1 = 7 The smallest D is 3. The maximum day needed is 3.
Case#: 3 Input: 4 10 18 19 20 Output: 4 Explanation: Initial heights: [10, 18, 19, 20]. Calculate target
final heights (H_final[i] = min(H[i], H_final[i-1] - 1)): H_final[0] = H[0] = 10 H_final[1] = min(18, 10 - 1)
= 9 H_final[2] = min(19, 9 - 1) = 8 H_final[3] = min(20, 8 - 1) = 7
for 9 is 4 (2^4 - 1 = 15 \ge 9). H[2]: 19 - 8 = 11. Smallest D for 11 is 4 (2^4 - 1 = 15 \ge 11). H[3]:
20 - 7 = 13. Smallest D for 13 is 4 (2^4 - 1 = 15 \ge 13). The maximum day needed across all
peaks is max(0, 4, 4, 4) = 4.
You are working with a sequence of data signals, where the i^{th} signal has an amplitude Ai. You
need to transform this sequence into a strictly increasing amplitude profile for analysis, meaning for
each i^{th} signal where 2 \le i \le N, the resultant Ai-1 < Ai. To do this, you employ a powerful signal
processing algorithm to boost the amplitude of the signals. On day D, the algorithm can increase the
amplitude for each signal that you scheduled that day by 2^D - 1 units each.
You are allowed to assign the algorithm to process multiple signals and/or process the same signals
for multiple days.
Your task is to find the minimum number of days needed to transform the signal sequence as per
your requirements.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in A.
N :: 1 -> 10^5
A :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing Ai, the amplitude of the i^{th} signal. A[i] :: -10^9 -> 10^9
Case#: 1 Input: 3 -5 -4 -3 Output: 0 Explanation: The amplitudes [-5, -4, -3] are already strictly
increasing. No boosting is needed.
Case#: 2 Input: 2 10 5 Output: 3 Explanation: Initial amplitudes: [10, 5]. We need A_final[0] <
A_final[1]. Calculate target final amplitudes (A_final[i] = max(A[i], A_final[i-1] + 1)): A_final[0] = A[0] =
10 A_final[1] = max(A[1], A_final[0] + 1) = max(5, 10 + 1) = max(5, 11) = 11. Target A_final = [10, 11].
Needed increases: A[0]: A_final[0] - A[0] = 10 - 10 = 0. A[1]: A_final[1] - A[1] = 11 - 5 = 6. For an
increase of 6: We need to find the minimum D such that 2^D - 1 \ge 6. 2^1 - 1
(2^4 - 1 = 15 \ge 8). The maximum day needed across all segments is max(0, 1, 2, 2, 3, 3, 3, 3,
4) = 4.
You are managing a specialized heating/cooling system that controls the temperature of N adjacent
chambers. The current temperature of the i^{th} chamber is Ti degrees Celsius. You need to
transform the chamber temperatures into a strictly downward sloping gradient,
meaning for each i^{th} chamber where 2 \le i \le N, the resultant Ti-1 > Ti. To achieve this, you
employ a powerful thermal regulation unit to adjust the temperature of the chambers. On day D, the
unit can reduce the temperature for each chamber that you scheduled that day by 2^D - 1 degrees
Celsius each.
You are allowed to assign the unit to regulate multiple chambers and/or regulate the same chambers
for multiple days.
Your task is to find the minimum number of days needed to transform the temperature gradient as
per your requirements.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in T.
N :: 1 -> 10^5
T :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing Ti, the temperature of the i^{th} chamber. T[i] :: -10^9 -> 10^9
Case#: 1 Input: 3 20 15 10 Output: 0 Explanation: The temperatures [20, 15, 10] are already strictly
decreasing. No regulation is needed.
Case#: 2 Input: 2 -5 -3 Output: 2 Explanation: Initial temperatures: [-5, -3]. We need T_final[0]
> T_final[1]. Calculate target final temperatures (T_final[i] = min(T[i], T_final[i-1] - 1)): T_final[0] = T[0]
= -5 T_final[1] = min(T[1], T_final[0] - 1) = min(-3, -5 - 1) = min(-3, -6) = -6. Target T_final =
[-5, -6]. Needed reductions: T[0]: -5 - (-5) = 0. T[1]: -3 - (-6) = 3. For a reduction of 3: We need to find
the minimum D such that 2^D - 1 \ge 3. 2^1 - 1 = 1 2^2 - 1 = 3 The smallest D is 2. The maximum day
needed is 2.
Case#: 3 Input: 4 10 20 21 22 Output: 4 Explanation: Initial temperatures: [10, 20, 21, 22]. Calculate
target final temperatures (T_final[i] = min(T[i], T_final[i-1] - 1)): T_final[0] = T[0] = 10 T_final[1] =
min(20, 10 - 1) = 9 T_final[2] = min(21, 9 - 1) = 8 T_final[3] = min(22, 8 - 1) = 7
Target T_final = [10, 9, 8, 7]. Needed reductions: T[0]: 10 - 10 = 0. T[1]: 20 - 9 = 11. Smallest D
for 11 is 4 (2^4 - 1 = 15 \ge 11). T[2]: 21 - 8 = 13. Smallest D for 13 is 4 (2^4 - 1 = 15 \ge 13).
T[3]: 22 - 7 = 15. Smallest D for 15 is 4 (2^4 - 1 = 15 \ge 15). The maximum day needed across
You are given an array of size N. You need to change this array into a "valley". By "valley" we mean
that the elements at either end of the array should be equal. Then, as you move towards the middle
from both ends, the next element is just one less than the previous one. So, it would have a trough
(lowest point) in the middle and increases if you go towards either end, just like a valley.
Examples of valleys are [5, 4, 3, 4, 5] or [8, 7, 6, 6, 7, 8]. But the array [5, 4, 2, 4, 5] is not a
valley because from 4 to 2 the difference is 2. The array [5, 4, 3, 5] is also not a valley because the
elements 4 and 3 are not equal from both ends relative to the trough.
You need to find the minimum number of elements that should be changed in order to make the
array a valley. You can make the elements negative or zero as well.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in
the array. N :: 1 -> 10^5
array :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the i^{th} element of the array. array[i] :: 1 -> 10^6
Case#: 1 Input: 5 1 2 3 4 5 Output: 2 Explanation: array = [1, 2, 3, 4, 5]. The optimal valley
● 1 vs 5 (change)
● 2 vs 4 (change)
● 3 vs 3 (no change)
● 4 vs 4 (no change)
Case#: 3 Input: 4 1 1 1 1 Output: 2 Explanation: array = [1, 1, 1, 1]. The optimal valley array
● 1 vs 1 (no change)
● 1 vs 0 (change)
● 1 vs 0 (change)
You are given an array of size N. You need to change this array into a "plateau". By "plateau" we
mean that the elements at either end of the array should be equal. Then, as you move towards the
middle from both ends, the next element is just one more than the previous one, until a central
"plateau" where elements are equal.
Examples of plateaus are [1, 2, 3, 3, 2, 1] or [1, 2, 2, 2, 1]. But the array [1, 2, 4, 4, 2, 1] is not a
plateau because from 2 to 4 the difference is 2. The array [1, 2, 3, 1] is also not a plateau because the
elements are not symmetric from both ends.
You need to find the minimum number of elements that should be changed in order to make the
array a plateau. You can make the elements negative or zero as well.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in
the array. N :: 1 -> 10^5
array :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the i^{th} element of the array. array[i] :: 1 -> 10^6
Case#: 1 Input: 5 5 4 3 2 1 Output: 2 Explanation: array = [5, 4, 3, 2, 1]. The optimal plateau
● 5 vs 1 (change)
● 4 vs 2 (change)
● 3 vs 3 (no change)
● 2 vs 2 (no change)
Case#: 2 Input: 4 1 2 3 4 Output: 2 Explanation: array = [1, 2, 3, 4]. The optimal plateau array
● 1 vs 1 (no change)
● 2 vs 2 (no change)
● 3 vs 2 (change)
The optimal plateau array is [0, 1, 2, 3, 2, 1, 0]. Comparing [10, 1, 20, 3, 20, 1, 10] with [0, 1, 2,
3, 2, 1, 0]:
● 10 vs 0 (change)
● 1 vs 1 (no change)
● 20 vs 2 (change)
● 3 vs 3 (no change)
● 20 vs 2 (change)
● 1 vs 1 (no change)
You are given an array of size N. You need to change this array into a "double-step mountain". By
"double-step mountain" we mean that the elements at either end of the array should be equal. Then,
as you move towards the middle from both ends, the next element is just two more than the
previous one. So, it would have a peak in the middle and decreases by two if you go towards either
end.
Examples of double-step mountains are [1, 3, 5, 3, 1] or [6, 8, 10, 10, 8, 6]. But the array [1, 3,
6, 3, 1] is not a double-step mountain because from 3 to 6 the difference is 3. The array [1, 3, 5, 1] is
also not a double-step mountain because the elements are not symmetric from both ends. You need
to find the minimum number of elements that should be changed in order to make the array a
double-step mountain. You can make the elements negative or zero as well.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in
the array. N :: 1 -> 10^5
array :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the i^{th} element of the array. array[i] :: 1 -> 10^6
double-step mountain array is [1, 3, 5, 3, 1]. Comparing [1, 3, 5, 4, 1] with [1, 3, 5, 3, 1]:
● 1 vs 1 (no change)
● 3 vs 3 (no change)
● 5 vs 5 (no change)
● 4 vs 3 (change)
Case#: 2 Input: 6 10 12 14 14 12 10 Output: 0 Explanation: array = [10, 12, 14, 14, 12, 10]. This array
already conforms to the "double-step mountain" definition. All elements match the target double-
step mountain, so 0 changes are needed.
The optimal double-step mountain array is [0, 2, 4, 6, 4, 2, 0]. Comparing [10, 2, 20, 6, 20, 2, 10]
● 10 vs 0 (change)
● 2 vs 2 (no change)
● 20 vs 4 (change)
● 6 vs 6 (no change)
● 20 vs 4 (change)
● 2 vs 2 (no change)
You are given an array of size N. You need to change this array into a "triple-step valley". By "triple-
step valley" we mean that the elements at either end of the array should be equal. Then, as you
move towards the middle from both ends, the next element is just three less than the previous one.
So, it would have a trough (lowest point) in the middle and increases by three if you go towards
either end.
Examples of triple-step valleys are [10, 7, 4, 7, 10] or [15, 12, 9, 9, 12, 15]. But the array [10, 7,
3, 7, 10] is not a triple-step valley because from 7 to 3 the difference is 4. The array [10, 7, 4, 10] is
also not a triple-step valley because the elements are not symmetric from both ends.
You need to find the minimum number of elements that should be changed in order to make the
array a triple-step valley. You can make the elements negative or zero as well.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in
the array. N :: 1 -> 10^5
array :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing the i^{th} element of the array. array[i] :: 1 -> 10^6
triple-step valley array is [10, 7, 4, 7, 10]. Comparing [10, 7, 4, 8, 10] with [10, 7, 4, 7, 10]:
● 10 vs 10 (no change)
● 7 vs 7 (no change)
● 4 vs 4 (no change)
● 8 vs 7 (change)
Case#: 2 Input: 6 15 12 9 9 12 15 Output: 0 Explanation: array = [15, 12, 9, 9, 12, 15]. This array
already conforms to the "triple-step valley" definition. All elements match the target triple-step
valley, so 0 changes are needed.
Case#: 3 Input: 7 10 -3 20 -9 20 -3 10 Output: 4 Explanation: array = [10, -3, 20, -9, 20, -3,
10]. The optimal triple-step valley array is [0, -3, -6, -9, -6, -3, 0]. Comparing [10, -3, 20, -9, 20,
-3, 10] with [0, -3, -6, -9, -6, -3, 0]:
● 10 vs 0 (change)
● -3 vs -3 (no change)
● 20 vs -6 (change)
● -9 vs -9 (no change)
● 20 vs -6 (change)
● -3 vs -3 (no change)
You have a collection of N resources. Each resource is identified by a unique integer Ri representing
its type. You can rearrange these resources in any order. You want to cut this collection into some
contiguous bundles such that, after cutting, all the bundles are equal to one another (meaning each
bundle contains the exact same count of each resource type).
You cannot rearrange the resources within the cut bundles or join bundles together. You want to
make the number of bundles as large as possible. What is the maximum number of bundles you can
get?
Note: You can observe that you may not want to cut the collection at all, therefore the number of
bundles is 1. Hence, the answer always exists.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of
resources. N :: 1 -> 2 * 10^5
R :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer Ri
describing the type of the i^{th} resource. R[i] :: 1 -> 10^9
Case#: 1 Input: 5 7 7 7 7 7 Output: 5 Explanation: You have 5 resources, all of type 7. You
can cut it into 5 bundles: [7] + [7] + [7] + [7] + [7]. Each bundle is identical.
[1, 2, 3, 1, 2, 3]. You can then cut it into 2 bundles: [1, 2, 3] + [1, 2, 3]. Each bundle is identical.
The total number of resources (6) and the count of each resource type (2 for 1, 2 for 2, 2 for 3) are all
divisible by 2.
Total resources: 7. Counts: Type 1: 3, Type 2: 2, Type 3: 1, Type 4: 1. The total number of
resources (7) is a prime number. The counts (3, 2, 1, 1) share no common factors with 7, nor
with each other (except 1). The greatest common divisor of 7, 3, 2, 1, 1 is 1. Therefore, you can only
get 1 piece (the original collection itself).
You are preparing ingredients for a large batch of identical meal kits. You have N individual
ingredients. Each ingredient is identified by an integer Ii representing its type (e.g., 1 for "flour", 2 for
"sugar"). You can rearrange these ingredients in any order. You want to pack this collection into
some contiguous boxes such that, after packing, all the boxes are equal to one another (meaning
each box contains the exact same count of each ingredient type).
You cannot rearrange the ingredients within the packed boxes or combine boxes. You want to
make the number of boxes as large as possible. What is the maximum number of boxes you can get?
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of
ingredients. N :: 1 -> 2 * 10^5
I :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer Ii
describing the type of the i^{th} ingredient. I[i] :: 1 -> 10^9
Case#: 1 Input: 4 10 10 10 10 Output: 4 Explanation: You have 4 ingredients, all of type 10. You can
pack it into 4 boxes: [10] + [10] + [10] + [10]. Each box is identical.
8, 8]. Total ingredients: 8. Counts: Type 5: 2, Type 6: 2, Type 7: 2, Type 8: 2. The total number of
ingredients (8) and the count of each ingredient type (2 for 5, 2 for 6, 2 for 7, 2 for 8) are all
ingredients as [5, 6, 7, 8, 5, 6, 7, 8]. You can then cut it into 2 boxes: [5, 6, 7, 8] + [5, 6, 7, 8]. Each box
is identical.
3, 1, 2, 4]. Total ingredients: 9. Counts: Type 1: 3, Type 2: 3, Type 3: 2, Type 4: 1. The total
number of ingredients (9) is divisible by 1, 3, 9. The counts are: 3, 3, 2, 1. The greatest common
divisor of 9, 3, 3, 2, 1 is 1. Therefore, you can only get 1 box (the original collection itself).
Question 3: Music Playlist Segmentation
You have a master playlist of N songs. Each song is identified by an integer Gi representing its genre.
You can rearrange the order of songs in this master playlist. You want to segment this playlist into
some contiguous sub-playlists such that, after segmentation, all the sub-playlists are equal to one
another (meaning each sub-playlist contains the exact same count of each genre). You cannot
rearrange the songs within the segmented sub-playlists or combine sub-playlists.
You want to make the number of sub-playlists as large as possible. What is the maximum number of
sub-playlists you can get?
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of songs. N
:: 1 -> 2 * 10^5
G :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer Gi
describing the genre of the i^{th} song. G[i] :: 1 -> 10^9
Case#: 1 Input: 6 1 1 1 1 1 1 Output: 6 Explanation: You have 6 songs, all of genre 1. You
can segment it into 6 sub-playlists: [1] + [1] + [1] + [1] + [1] + [1]. Each sub-playlist is identical.
songs: [10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30]. Total songs: 12. Counts: Genre 10: 4,
Genre 20: 4, Genre 30: 4. The total number of songs (12) and the count of each genre (4 for 10,
4 for 20, 4 for 30) are all divisible by 4. The greatest common divisor of 12, 4, 4, 4 is 4. You can
rearrange the songs as [10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30]. You can then cut it into 4
sub-playlists: [10, 20, 30] + [10, 20, 30] + [10, 20, 30] + [10, 20, 30]. Each sub-playlist is identical.
Case#: 3 Input: 5 1 2 3 4 5 Output: 1 Explanation: You have songs: [1, 2, 3, 4, 5]. Total songs:
songs (5) is a prime number. The counts (1, 1, 1, 1, 1) share no common factors with 5, nor with
each other (except 1). The greatest common divisor of 5, 1, 1, 1, 1, 1 is 1. Therefore, you can
You have an inventory of N items. Each item is identified by an integer Pi representing its product
code. You can rearrange these items in any order. You want to divide this inventory into some
contiguous shipments such that, after division, all the shipments are equal to one another (meaning
each shipment contains the exact same count of each product code).
You cannot rearrange the items within the divided shipments or combine shipments. You want to
make the number of shipments as large as possible. What is the maximum number of shipments you
can get?
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of items. N
:: 1 -> 2 * 10^5
P :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer Pi
describing the product code of the i^{th} item. P[i] :: 1 -> 10^9
Case#: 1 Input: 8 1000 1000 1000 1000 1000 1000 1000 1000 Output: 8 Explanation: You have 8
items, all of product code 1000. You can divide it into 8 shipments: [1000] + ... + [1000]. Each
shipment is identical.
3, 3]. Total items: 9. Counts: Product 1: 3, Product 2: 3, Product 3: 3. The total number of items
(9) and the count of each product code (3 for 1, 3 for 2, 3 for 3) are all divisible by 3. The
3]. You can then cut it into 3 shipments: [1, 2, 3] + [1, 2, 3] + [1, 2, 3]. Each shipment is identical.
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]. Total items: 10. Counts: Each product code (10, 20, ...,
100) appears exactly once. The total number of items (10) is divisible by 1, 2, 5, 10. The counts (all 1s)
are only divisible by 1. The greatest common divisor of 10 and all the 1s is 1. Therefore, you can only
get 1 shipment (the original inventory itself).
You are given an array A of size N. You are allowed to choose at most one pair of elements such that
their distance (defined as the absolute difference of their indices) is at most K and swap them.
Notes: An array x is lexicographically larger than an array y if there exists an index i such that x_i >
y_i, and x_j = y_j for all 0 \le j < i. Less formally, at the first index i in which they differ, x_i > y_i.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the number of elements in A.
N :: 1 -> 10^5
A :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing A[i]. A[i] :: 1 -> 10^5
K :: INTEGER The next line contains an integer, K, denoting the upper bound on distance of index. K ::
1 -> N
Case#: 1 Input: 3 1 2 3 1 Output: 2 1 3 Explanation: A = [1, 2, 3], K = 1. We iterate from left to right. At
index 0, A[0]=1. Within distance K=1 to its right, we have A[1]=2. Since A[1] > A[0], we swap A[0] and
A[1]. The array becomes [2, 1, 3]. This is the largest possible.
You are given an array A of size N. You are allowed to choose at most one pair of elements A[i] and
A[j] such that their distance (defined as the absolute difference of their indices) is at most K, AND A[i]
is an odd number while A[j] is an even number. Swap them.
Notes: An array x is lexicographically smaller than an array y if there exists an index i such that x_i <
y_i, and x_j = y_j for all 0 \le j < i.
Case#: 3 Input: 4 2 1 4 3 2 Output: 2 1 4 3 Explanation: A = [2, 1, 4, 3], K = 2. Iterate from left to right.
At index 0, A[0]=2 (even). Cannot initiate a swap. At index 1, A[1]=1 (odd). Within distance K=2 to its
right (indices 2, 3), we have A[2]=4, A[3]=3. Candidate for A[j] that is even and less than A[1]=1:
A[2]=4 is even but 4 > 1. No valid A[j] found. No valid swap found. The array remains [2, 1, 4, 3].
You are given an array A of size N. You are allowed to choose at most one pair of elements A[i] and
A[j] such that their distance (defined as the absolute difference of their indices) is at most K, AND A[i]
is an even number while A[j] is an odd number. Swap them.
Notes: An array x is lexicographically larger than an array y if there exists an index i such that x_i >
y_i, and x_j = y_j for all 0 \le j < i.
Case#: 3 Input: 4 1 2 3 4 2 Output: 1 3 2 4 Explanation: A = [1, 2, 3, 4], K = 2. Iterate from left to right.
At index 0, A[0]=1 (odd). Cannot initiate a swap. At index 1, A[1]=2 (even). Within distance K=2 to its
right (indices 2, 3), we have A[2]=3, A[3]=4. Candidates for A[j] that are odd and greater than A[1]=2:
A[2]=3. (A[3]=4 is even). The largest valid candidate is 3 (at index 2). Since A[2]=3 is odd and 3 >
A[1]=2, we swap A[1] and A[2]. The array becomes [1, 3, 2, 4]. This is the largest possible.
You are given an array A of size N and an integer V. You are allowed to choose at most one pair of
elements A[i] and A[j] such that their distance (defined as the absolute difference of their indices) is
at most K, AND A[j] is strictly less than A[i], AND A[j] is also less than or equal to V. Swap them.
Notes: An array x is lexicographically smaller than an array y if there exists an index i such that x_i <
y_i, and x_j = y_j for all 0 \le j < i.
● A[3]=2 (2 < 5 AND 2 <= 2). This is the only valid candidate. Swap A[0] and A[3]. Array becomes
[2, 4, 3, 5, 1]. This is the smallest possible.
● A[2]=5 (not <= 3). The smallest valid candidate is 1 (at index 1). Swap A[0] and A[1]. Array
becomes [1, 10, 5, 2]. This is the smallest possible.
You are given an array A of size N and an integer V. You are allowed to choose at most one pair of
elements A[i] and A[j] such that their distance (defined as the absolute difference of their indices) is
at most K, AND A[j] is strictly greater than A[i], AND A[j] is also greater than or equal to V. Swap
them.
Notes: An array x is lexicographically larger than an array y if there exists an index i such that x_i >
y_i, and x_j = y_j for all 0 \le j < i.
● A[3]=4 (4 > 1 AND 4 >= 4). This is the only valid candidate. Swap A[0] and A[3]. Array becomes
[4, 2, 3, 1, 5]. This is the largest possible.
● A[2]=5 (not >= 6). The largest valid candidate is 10 (at index 1). Swap A[0] and A[1]. Array
becomes [10, 1, 5, 2]. This is the largest possible.
You are managing a team of workers and have a list of tasks. Each task Ti has a specific "effort level"
required to complete it. You can assign tasks to workers in any order. Your goal is to complete as
many tasks as possible.
● You have exactly N tasks in total, described by an array Effort. If two elements of Effort have
the same value, they represent tasks requiring the same effort level.
● If you assign a task requiring E effort to a worker, the next task you assign must require 2
* E effort.
● You cannot assign tasks of the same effort level more than once.
Find the maximum total effort points you can accumulate from completed tasks.
Notes:
● You can assign any number of tasks of a given effort level, as long as you have enough tasks
of that level available. If a task type has C tasks available, and you need to assign E effort, you can use
E tasks from that type if C >= E.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of tasks. N
:: 1 -> 10^5
Effort :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing Effort[i], the effort level required for the i^{th} task. Effort[i] :: 1 -> 10^9 Case#: 1 Input: 5
10 20 40 20 30 Output: 70 Explanation: N=5, Effort=[10, 20, 40, 20, 30]
Task effort level counts: 10:1, 20:2, 30:1, 40:1. Start with 10 effort: Order 10 effort tasks (1 available).
Total = 10. Next order must be 20. Order 20 effort tasks (2 available, use 20). Total = 10 + 20 = 30.
Next order must be 40. Order 40 effort tasks (1 available, use 40). Total = 30 + 40
10, 20] Task effort level counts: 5:2, 10:4, 20:1. Start with 5 effort: Order 5 effort tasks (2
available, use 5). Total = 5. Next order must be 10. Order 10 effort tasks (4 available, use 10).
Total = 5 + 10 = 15. Next order must be 20. Order 20 effort tasks (1 available, use 20). Total =
counts: 1:4. Start with 1 effort: Order 1 effort tasks (4 available, use 1). Total = 1. Next order must be
2. No tasks of effort 2 available. Chain ends. Maximum is 1. (You can only use one set of 1 effort
tasks, as you can't reuse the same effort level type).
You have a collection of N computing resources. Each resource Ri has a specific "processing power".
You can arrange these resources in any order. You want to allocate these resources to a series of jobs
to maximize the total processing power utilized.
● If two resources have the same processing power, they are considered to be of the same
"resource type".
● Each resource type can only be used once in the allocation chain.
● If you use a resource type with P processing power, the next resource type you use must
have 2 * P processing power.
● You can start the allocation chain with any resource type. Find the maximum total processing
power you can utilize. Notes:
● You can utilize any number of resources of a given type, as long as you have enough
resources of that type available. If a resource type has C instances available, and you need to utilize P
power, you can use P instances from that type if C >= P.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of
resources. N :: 1 -> 10^5
Power :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing Power[i], the processing power of the i^{th} resource. Power[i] :: 1 -> 10^9 Case#: 1 Input:
6 3 6 12 6 24 12 Output: 45 Explanation: N=6, Power=[3, 6, 12, 6, 24, 12]
Resource power counts: 3:1, 6:2, 12:2, 24:1. Start with 3 power: Use 3 power type (1 available).
Total = 3. Next must be 6. Use 6 power type (2 available, use 6). Total = 3 + 6 = 9. Next must be
12. Use 12 power type (2 available, use 12). Total = 9 + 12 = 21. Next must be 24. Use 24
power type (1 available, use 24). Total = 21 + 24 = 45. Next must be 48. (Not available).
Maximum is 45.
power counts: 1:1, 2:1, 4:1, 8:1, 16:1. Start with 1 power: Use 1 power type. Total = 1. Next 2.
Use 2 power type. Total = 1 + 2 = 3. Next 4. Use 4 power type. Total = 3 + 4 = 7. Next 8. Use 8
power type. Total = 7 + 8 = 15. Next 16. Use 16 power type. Total = 15 + 16 = 31. Next 32. (Not
available). Maximum is 31.
7:3. Start with 7 power: Use 7 power type (3 available, use 7). Total = 7. Next must be 14. No
resources of power 14 available. Chain ends. Maximum is 7.
You are conducting an experiment with N plants. Each plant Pi has a specific "growth rate" value. You
can arrange these plants in any order for observation. Your goal is to identify a sequence of plants
that maximizes their combined growth potential.
● If two plants have the same growth rate, they are considered to be of the same "plant type".
● Each plant type can only be selected once for the sequence.
● If you select a plant type with growth rate G, the next plant type you select must have a
growth rate of 2 * G.
Notes:
● You can select any number of plants of a given type, as long as you have enough plants of
that type available. If a plant type has C instances available, and you need to select G growth, you can
use G plants from that type if C >= G.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of plants. N
:: 1 -> 10^5
Growth :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing Growth[i], the growth rate of the i^{th} plant. Growth[i] :: 1 -> 10^9
growth rate counts: 1:2, 2:2, 4:2, 8:1. Start with 1 growth rate: Use 1 growth type (2 available,
use 1). Total = 1. Next must be 2. Use 2 growth type (2 available, use 2). Total = 1 + 2 = 3. Next
must be 4. Use 4 growth type (2 available, use 4). Total = 3 + 4 = 7. Next must be 8. Use 8 growth type
(1 available, use 8). Total = 7 + 8 = 15. Next must be 16. (Not available). Maximum is 15.
Case#: 2 Input: 6 100 100 200 200 50 50 Output: 350 Explanation: N=6, Growth=[100, 100,
200, 200, 50, 50] Plant growth rate counts: 50:2, 100:2, 200:2. Start with 50 growth rate: Use 50
growth type (2 available, use 50). Total = 50. Next must be 100. Use 100 growth type (2
available, use 100). Total = 50 + 100 = 150. Next must be 200. Use 200 growth type (2 available, use
200). Total = 150 + 200 = 350. Next must be 400. (Not available). Maximum is 350.
counts: 1:1, 3:1, 5:1, 7:1. If you start with 1, next is 2 (not available). Total 1. If you start with 3, next
is 6 (not available). Total 3. If you start with 5, next is 10 (not available). Total 5. If you start
You have a stream of N data packets. Each packet Pi has a specific "size" in bytes. You can rearrange
these packets in any order before bundling. You want to create a sequence of data bundles to
maximize the total data transmitted.
● If two packets have the same size, they are considered to be of the same "packet type".
● Each packet type can only be used once in the bundling sequence.
● If you transmit a bundle of size S, the next bundle you transmit must be of size 2 * S.
● You can start the bundling sequence with any packet type. Find the maximum total data size
you can transmit.
Notes:
● You can use any number of packets of a given type, as long as you have enough packets of
that type available. If a packet type has C instances available, and you need to transmit S bytes, you
can use S packets from that type if C >= S.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of packets.
N :: 1 -> 10^5
Size :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an integer
describing Size[i], the size of the i^{th} packet. Size[i] :: 1 -> 10^9
Case#: 1 Input: 5 10 20 40 80 160 Output: 310 Explanation: N=5, Size=[10, 20, 40, 80, 160]
Packet size counts: 10:1, 20:1, 40:1, 80:1, 160:1. Start with 10 size: Use 10 size type. Total =
10. Next 20. Use 20 size type. Total = 10 + 20 = 30. Next 40. Use 40 size type. Total = 30 + 40 =
70. Next 80. Use 80 size type. Total = 70 + 80 = 150. Next 160. Use 160 size type. Total = 150 +
Packet size counts: 1:3, 2:3, 4:2. Start with 1 size: Use 1 size type (3 available, use 1). Total = 1.
Next 2. Use 2 size type (3 available, use 2). Total = 1 + 2 = 3. Next 4. Use 4 size type (2
Case#: 3 Input: 3 100 100 100 Output: 100 Explanation: N=3, Size=[100, 100, 100] Packet
size counts: 100:3. Start with 100 size: Use 100 size type (3 available, use 100). Total = 100. Next 200.
No packets of size 200 available. Chain ends. Maximum is 100.
You are forming a musical ensemble and have N instruments at your disposal. Each instrument Ii has
a specific "loudness level". You can arrange these instruments in any order for the ensemble. Your
goal is to select a sequence of instruments that maximizes their combined loudness.
● If two instruments have the same loudness level, they are considered to be of the same
"instrument type".
● Each instrument type can only be selected once for the ensemble sequence.
● If you select an instrument type with loudness L, the next instrument type you select must
have a loudness of 2 * L.
● You can start the ensemble sequence with any instrument type.
Find the maximum total loudness you can achieve from such an ensemble.
Notes:
● You can select any number of instruments of a given type, as long as you have enough
instruments of that type available. If an instrument type has C instances available, and you need to
select L loudness, you can use L instruments from that type if C >= L.
Parameters: N :: INTEGER The first line contains an integer, N, denoting the total number of
instruments. N :: 1 -> 10^5
Loudness :: INTEGER ARRAY Each line i of the N subsequent lines (where 0 \le i < N) contains an
integer describing Loudness[i], the loudness level of the i^{th} instrument. Loudness[i] :: 1 -> 10^9
Instrument loudness level counts: 2:1, 4:2, 8:2, 16:1. Start with 2 loudness: Use 2 loudness type
(1 available). Total = 2. Next must be 4. Use 4 loudness type (2 available, use 4). Total = 2 + 4 =
6. Next must be 8. Use 8 loudness type (2 available, use 8). Total = 6 + 8 = 14. Next must be
16. Use 16 loudness type (1 available, use 16). Total = 14 + 16 = 30. Next must be 32. (Not available).
Maximum is 30.
loudness level counts: 1:1, 2:1, 3:1, 40:1. If you start with 1, next is 2. Next is 4 (not available). Total =
1 + 2 = 3. If you start with 2, next is 4 (not available). Total = 2. If you start with 3, next is 6 (not
available). Total = 3. If you start with 40, next is 80 (not available). Total = 40. The maximum total
loudness is 40.
Case#: 3 Input: 5 10 10 10 10 10 Output: 10 Explanation: N=5, Loudness=[10, 10, 10, 10, 10]
Instrument loudness level counts: 10:5. Start with 10 loudness: Use 10 loudness type (5 available, use
10). Total = 10. Next 20. No instruments of loudness 20 available. Chain ends.
Maximum is 10.
Q1.
Problem Statement
Determine whether a given undirected graph contains the Hamiltonian cycle or not.
Hamiltonian cycle in an undirected graph is a path that visits each vertex exactly once. A Hamiltonian
cycle is a Hamiltonian path such that there is an edge from the last vertex to the first vertex of the
Hamiltonian path.
Example
Input:
01010
10111
01001
11001
01110
Output:
012430
Explanation:
Starting from vertex 0, all the vertices can be visited exactly once (0 - 1 - 2 - 4 - 3 - 0).
Input Format
The first line of input consists of an integer that represents the number of vertices (V).
The following lines of input consist of the V*V matrix, which represents the adjacency matrix of the
graph.
Output Format
The output prints If a Hamiltonian cycle exists, print the vertices in the cycle in order, starting and
ending at vertex 0.; otherwise, it prints that the "Hamiltonian path does not exist".
Constraints
3≤V≤5
5 012430
01010
10111
01001
11001
01110
Sample Input Sample Output
01010
10111
01001
11000
01100
Q2.
Problem Statement:
Inversion Count: For an array, the inversion count indicates how far (or close) the array is from being
sorted. If the array is already sorted, then the inversion count is 0. If an array is sorted in reverse
order, then the inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Example 1:
Input:
N = 5, arr[] = {2, 4, 1, 3, 5}
Output: 3
Explanation:
Sequence 2, 4, 1, 3, and 5 has three inversions (2, 1), (4, 1), and (4, 3).
Example 2:
Output: 0
Explanation:
Example 3:
Output: 0
Explanation:
As all the elements of the array are the same, there is no inversion count.
Input Format
The second line of the input is the list of space-separated integer values.
Output Format
Constraints
1 ≤ N ≤ 5*105
1 ≤ arr[i] ≤ 1018
5 3
24135
5 0
23456
3 0
10 10 10
Q3.
Problem Statement
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s
such that every character in t (including duplicates) is included in the window. If there is no such
substring, return an empty string.
Examples
Output: BANC
Explanation: The minimum window substring BANC includes 'A', 'B', and 'C' from string t.
Input: s = a, t = a
Output: a
Input: s = a, t = aa
Output:
Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has
one 'a', return an empty string.
Input Format
The first line contains the string s, which is the source string.
The second line contains the string t, which is the target string whose characters must be included in
the window.
Output Format
The output is a single line containing the minimum window substring of s containing all t characters.
If no such window exists, output an empty string.
Constraints
m == s.length
n == t.length
1 ≤ m, n ≤ 105
ADOBECODEBANC BANC
ABC
Q4.
Problem Statement
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
Input Format
The first line of input consists of an integer value 'n', representing the number of digits in the
permutation.
The second line of input consists of an integer value 'k', representing the position of the permutation
to be found.
Output Format
The output displays the kth permutation of the first n positive integers.
Constraints
In this scenario, the given test cases will fall under the following constraints:
1≤n≤9
1 ≤ k ≤ n!
Sample Input Sample Output
3 213
4 2314
3 123
Q5.
Problem Statement
Given an array representing the parent-child relationship in a binary tree, find the tree's height
without building it.
The parent-child relationship is defined by (A[i], i) for every index i in the array. The root node's value
will be i if -1 is present at index i in the array.
The depth of a node is the total number of edges from the node to the tree's root node. The root is
the only node whose depth is 0.
The height of a node is the total number of edges on the longest path from the node of a leaf. The
height of a tree would be the height of its root node or equivalently the depth of its deepest node. A
leaf node will have a height of 0.
Example
Parent: [-1, 0, 0, 1, 2, 2, 4, 4]
Index: [0, 1, 2, 3, 4, 5, 6, 7]
1. -1 is present at index 0, which implies that the binary tree root is node 0.
2. 0 is present at index 1 and 2, which implies that the left and right children of node 0 are 1
and 2.
3. 1 is present at index 3, which implies that the left or the right child of node 1 is 3.
4. 2 is present at index 4 and 5, which implies that the left and right children of node 2 are 4
and 5.
5. 4 is present at index 6 and 7, which implies that the left and right children of node 4 are 6
and 7.
Input Format
The first line contains a single integer N, which represents the number of nodes in the tree.
The next N lines consist of an integer in each line, and the last line of input consists of the ith integer
representing the parent of the ith node.
If the ith node is the root node, then the corresponding value will be -1.
Output Format
The output consists of a single integer, which represents the height of the tree.
Constraints
1 ≤ N ≤ 10
8 3
-1
4 2
-1
1
1
Q6.
Problem Statement
Roshan invested all day in developing test data for DC. He couldn’t make it work, so he had a nervous
breakdown and can’t even see clearly anymore. Every time he winks(blinks) while reading, the letters
in a word get mingled up so that the letters from the second half of the word (the shorter half, if the
length is an odd number) “jump in” between the letters from the first half in the following way:
• The final letter “jumps in” the middle of the 1st and the 2nd letter
• The second final letter “jumps in” the middle of the 2nd and the 3rd letter
• The ith letter from the end “jumps in” the middle of the ith and the (i+1)th letter from the
starting
For case, the word “abcdef” would become “afbecd” after winking.
If Roshan winks again, the same thing happens. After three winks, the word becomes “adfcbe”.
Roshan has decided to write a program to help him figure out what’s correctly written on the screen.
Unfortunately, after a day’s work, he’s too tired, and he needs your help. You are given N, the
number of winks, and the word Roshan sees on the screen. Write a program to solve the mystery for
Roshan and figure out what was actually the word before he winked N times.
Input Format
The first line of input contains a positive integer N, the number of times Roshan blinked.
The second line of input contains the word W from the screen.
The word will consist only of small letters of the English alphabet.
Output Format
The output displays the original word before Roshan blinked N times.
Constraints
1 ≤ N ≤ 109
3 ≤ length(W) ≤ 103
3 adfcbe
abcdef
7 aaaaaa
aaaaaa
4 saamr
srama
Q7.
Problem Statement
We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees,
they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they become
invalid.
A confusing number is a number that when rotated 180 degrees becomes a different number with
each digit valid. (Note that the rotated number can be greater than the original number)
Given a positive integer N, return the number of confusing numbers between 1 and N inclusive.
Example
Input: 16
Output: 4
Explanation:
6 converts to 9.
9 converts to 6.
Input Format
Output Format
The output prints an integer, representing the number of confusing numbers between 1 and N
inclusive.
Constraints
1 ≤ N ≤ 103
16 4
69 10
20 6
Q8
Problem Statement
Given an array of string words and a width maxWidth, format the text such that each line has exactly
maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each
line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a
line does not divide evenly between words, the empty slots on the left will be assigned more spaces
than the slots on the right.
The last line of text should be left justified, and no extra space should be inserted between words.
Note:
2. Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.
Input Format
The first line of input consists of an integer n, representing the number of words in the sentence.
Output Format
Constraints
1 ≤ words.length ≤ 300
1 ≤ words[i].length ≤ 20
1 ≤ maxWidth ≤ 100
words[i].length ≤ maxWidth
7 This is an
example of text
justification.
This
is
an
example
of
text
justification.
16
18 Science is what we
understand well
enough to explain to
a computer. Art is
everything else we
do
Science
is
what
we
understand
well
enough
to
explain
to
computer.
Art
is
everything
else
we
do
20
Q9.
Problem Statement
Given a directed graph represented using an adjacency list, the task is to find the length of the
shortest cycle in the graph. A cycle is a path that starts and ends at the same vertex, and the length
of the cycle is defined as the sum of the weights of all the edges in the cycle. If no cycle is found in
the graph, output a message indicating that no cycle exists.
Example
Input
012
123
204
315
Output
Explanation
After exploring all starting vertices, the code checks for cycles by examining the distances. If an edge
leads back to the starting vertex, it means there is a cycle. In this case, edge 1 (vertex 1) leads back to
the starting vertex 0. The code calculates the length of the cycle by adding the distances of the
vertices along the cycle: 2 (0 -> 1) + 3 (1 -> 2) + 4 (2 -> 0) = 9.
Input 2
012
123
Output 2
No cycle was found in the graph.
Explanation
After exploring all starting vertices, the code checks for cycles by examining the distances. If an edge
leads back to the starting vertex, it means there is a cycle. However, in this case, there are no edges
that lead back to the starting vertex. Hence, there is no cycle in the graph.
Input Format
The first line of input consists of an integer v, representing the number of vertices in the graph.
The second line of input consists of an integer e, representing number of edges in the graph.
The next edges lines each contain three integers: source, destination, and weight, representing a
directed edge from source to destination with the given weight.
Output Format
If a cycle exists, print "Length of the shortest cycle: X", where X is the length of the shortest cycle.
Constraints
In this scenario, the given test cases will fall under the following constraints:
1≤v≤5
1 ≤ edges ≤ 7
0 ≤ S, D < V
1≤W≤5
012
123
204
315
012
123
012
123
204
Q10.
Problem Statement
Mr.Butler is managing his class of n students. He placed all his students in a line and gave the kth
student from the left a card with the letter ak written on it. He would now like to rearrange the
students so that the kth student from the left has a card with the letter bk written on it.
To do this, he will choose some consecutive groups of students, and reverse their order. Students will
hold on to their original cards during this process.
He’s now wondering, what is the number of valid ways to do this? (It may be impossible, in which
case, the answer is zero).
With sequences abba and aabb, Mr.Butler can choose group a(bba). With sequences caxcab and
cacxab, Mr.Butler can choose ca(xc)ab or c(axca)b. With sequences a and z, there are no solutions.
Input Format
It is guaranteed that A and B have the same positive length, and A and B are not identical.
Output Format
The output displays the number of ways Mr.Butler can reverse some consecutive groups of A to form
the line specified by string B.
abba 1
aabb
caxcab 2
cacxab
a 0
Q11.
Problem Statement
Given an input stream of N integers. The task is to insert these numbers into a new stream and find
the median of the stream formed by each insertion of X to the new stream.
Example 1
Input
N=4
X[] = 5,15,1,3
Output
10
Explanation:
Example 2
Input
N=3
X[] = 5,10,15
Output
7.5
10
Explanation:
Input Format
The first line contains an integer n, the number of integers in the stream.
The second line contains n space-separated integers representing the elements of the stream.
Output Format
The output prints the median after each insertion of an integer into the stream. Print each median on
a new line.
Constraints
1 ≤ N ≤ 15
1 ≤ Elements ≤ 100
4 5
10
5
5 15 1 3
3 5
7.5
10
5 10 15
Q12.
Problem Statement
Given a string s and a dictionary of string wordDict of size n, add spaces in s to construct a sentence
where each word is a valid dictionary word. Return all such possible sentences in any order.
Note: The same word in the dictionary may be reused multiple times in the segmentation. & All the
strings of wordDict are unique.
Examples
Input:
s = "catsanddog"
n=5
wordDict = ["cat","cats","and","sand","dog"]
Output:
Input:
s = "pineapplepenapple"
n=5
wordDict = ["apple","pen","applepen","pine","pineapple"]
Output:
Input:
s = "catsandog"
n=5
wordDict = ["cats","dog","sand","and","cat"]
Output:
[]
Input Format
The first line of input is a string 's' consisting of lowercase English letters.
The second line of input is an integer 'n' represents the size of the dictionary.
The next n lines consists of strings denoting the words in the dictionary.
Output Format
The output displays a list of strings, where each string is a space-separated sequence of dictionary
words that form the input string s.
Constraints
1 <= n <= 10
cat
cats
and
sand
dog
Pineapplepenapple [pine apple pen apple, pineapple pen apple, pine applepen apple]
apple
pen
applepen
pine
pineapple
Catsandog []
cats
dog
sand
and
cat
Q13.
Problem Statement
Given an m x n integers matrix, return the length of the longest increasing path in matrix.
From each cell, you can either move in four directions: left, right, up, or down. You may not move
diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Output: 4
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Output: 1
Input Format
The first line of input consists of an integer r, representing the number of rows.
The second line of input consists of an integer c, representing the number of columns.
The next r lines contain c integers each, representing the elements of the matrix.
Output Format
The output prints a single integer, representing the length of the longest increasing path in the matrix
Constraints
1≤r≤4
1≤c≤4
994
668
211
3
345
326
221
Q14.
Problem Statement
Tom is a software developer working on a project where he has to check if a doubly linked list is a
palindrome. He needs to write a program to solve this problem. Write a program to help Tom check
if a given doubly linked list is a palindrome or not.
Input Format
The first line consists of an integer N, representing the number of elements in the linked list.
The second line consists of N space-separated integers representing the linked list elements.
Output Format
The first line displays the space-separated integers, representing the doubly linked list.
1. If the doubly linked list is a palindrome, print "The doubly linked list is a palindrome".
2. If the doubly linked list is not a palindrome, print "The doubly linked list is not a palindrome".
Constraints
In this scenario, the test cases fall under the following constraints:
2 ≤ N ≤ 20
12321
12321
12345
12345
-1 -2 -3 -3 -2 -1
-1 -2 -3 -3 -2 -1
Q15.
Problem Statement
Meet Alex, a computer science student who loves solving programming challenges.
Today, Alex is tasked with creating a program to simulate a stack data structure using linked lists.
The objective is to provide a menu-driven interface for performing essential stack operations.
Additionally, Alex needs to ensure that the program handles stack underflow conditions. Help him to
accomplish the task.
Input Format
The input consists of integers corresponding to the operation that needs to be performed:
Choice 1: If the choice is 1, the following integer input represents the element to be pushed onto the
stack.
Output Format
The output displays messages according to the choice and the status of the stack:
• If the choice is 1, push the given integer to the stack and display the following: "[value] is
pushed onto the stack"
• If the choice is 2, pop the integer from the stack and display the following: "[value] is popped
from the stack"
• If the choice is 2, and if the stack is empty without any elements, print "Stack Underflow"
• If the choice is 3, print the elements in the stack in the format: "Elements in the stack: ",
followed by the space-separated integer values.
• If the choice is 3, and there are no elements in the stack, print "Stack is empty"
• If the choice is 4, exit the program and display the following: "Exiting the program"
Constraints
Choice: 1, 2, 3, or 4
Invalid choice
Stack Underflow
Stack is empty
Q16.
Problem Statement:
Today you decided to go to the gym. You currently have E energy. There are N exercises in the gym.
Each of these exercises drains A[i] amount of energy from your body.
You feel tired if your energy reaches 0 or below. Calculate the minimum number of exercises you
have to perform such that you become tired. Every unique exercise can only be performed at most 2
times as others also have to use the machines.
If performing all the exercises does not make you feel tired, return -1
Example:
Input:
Output:
E = 2 (Initial energy)
The best option is to do Exercise 3 (which drains 2 energy) once. It will make your energy level drop
exactly to 0.
Input Format
Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing the amount of
energy drained by ith exercise.
Output Format
The output prints a single integer representing the minimum number of exercises required to make
the energy ≤ 0.
Constraints
6
2
10
-1
Q17.
Problem Statement:
You need to build a road in a rugged terrain. You know the sea level of each segment of the rugged
terrain, i.e. the i-th segment is Li meters from sea level.
You needs to transform the terrain into a strictly downward sloping terrain for the road, i.e, for each
i-th segment where 2 <= i <= N, resultant Li-1 > Li. In order to do so, you employ a powerful digging
team to help you dig and reduce the sea level of the segments. On day D, the team can reduce the
sea level for each segments that you scheduled that day by 2D-1 meters each.
You are allowed to assign the team to dig on multiple segments and/or dig on the same segments for
multiple days.
Your task is to find the minimum number of days needed to transform the terrain as per your
requirements
Example:
Input:
-1
1
1
Output:
Explanation:
On day 2, we can dig on 3rd and 4th segments, resulting in {-2, 1, -1, -2}
On day 3, we can dig on 2nd, 3rd and 4th segments, resulting in {-2, -3, -5, -6}
Input Format
Each line i of the N subsequent lines (where 0 < i ≤ N) contains an integer describing Li, the sea level
of the i-th segment.
Output Format
The program should print a single integer representing the minimum number of days required to
transform the terrain into a strictly decreasing sequence.
Constraints
-3
0
Q18.
Problem Statement:
You are given an array of size N. You need to change this array into a mountain. By mountain we
mean, that either ends of the array should have equal elements. Then as we move towards the
middle from both ends, the next element is just one more than the previous one. So it would have a
peak in the middle and decrease if you go towards either end, just like a mountain.
Examples of mountains are [1, 2, 3, 2, 1] or [6, 7, 8, 8, 7, 6]. But the array [1, 2, 4, 2, 1] is not a
mountain because from 2 to 4 the difference is 2. The array [1, 2, 3, 1] is also not a mountain because
the elements 2 and 3 are not equal from both ends.
You need to find the minimum number of elements that should be changed in order to make the
array a mountain. You can make the elements negative or zero as well.
Example:
Input:
Output:
Explanation:
Input Format
The first line contains an integer, N, denoting the number of elements in the array.
Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing i-th element of
the array.
Output Format
The program prints a single integer, which represents the minimum number of changes required to
make the array a mountain.
Refer to the sample output for formatting specifications.
Constraints
Q19.
Problem Statement:
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Example 1:
Input:
N = 5, arr[] = {2, 4, 1, 3, 5}
Output:
Explanation:
Sequence 2, 4, 1, 3, and 5 has three inversions (2, 1), (4, 1), and (4, 3).
Example 2:
Input:
N=5
arr[] = {2, 3, 4, 5, 6}
Output:
Explanation:
Example 3:
Input:
Output:
Explanation:
As all the elements of the array are the same, there is no inversion count.
Input Format
Output Format
Constraints
1 ≤ N ≤ 5*105
1 ≤ arr[i] ≤ 1018
24135
23456
10 10 10
Q20.
Problem Statement
Given a non-empty string containing no spaces and a dictionary of a list of non-empty strings (say,
the list of words), you are supposed to construct and return all possible sentences after adding
spaces to the originally given string (sentence), where each word must exist in the given dictionary.
Note: The same word from a dictionary can be used as many times as possible to make sentences.
Example:
Input 1:
6
god
is
now
no
where
here
godisnowherenowhere
Output 1:
Explanation: One way to make sentences is to take "god" and append a space, then take "is" and
append a space, take "now" from the dictionary, and take "here" as well. Similarly, for other
sentences, we can also add space to get other possible sentences. Note that you can reuse
dictionary words, as "no" and "now" are used two times to make the same sentence.
Input 2:
god
is
no
here
godisnowhere
Output 2:
None
Explanation: We cannot make any sentence because after making "god is no" we will be stuck with
"where". There is no way to break "where" further so that we can get any word from the dictionary.
Input Format
The first line of input contains an integer value N, which denotes the size of the dictionary.
Output Format
The output displays each possible sentence after adding spaces at different positions.
Constraints
1 <= W <= 20
1 <= M <= 20
where 'N' is the length of a dictionary, 'W' is the length of the "word" in a dictionary, and 'M' is the
length of a sentence.
The code assumes that the input words in the dictionary and sentence are case-sensitive.
god
is
now
no
where
here
godisnowherenowhere
god
is
no
here
godisnowhere
None
Q21.
Problem Statement
There are three piles of stones. The first pile contains a stone, the second pile contains b stones, and
the third pile contains c stones. You must choose one of the piles and split the stones from it to the
other two piles; specifically, if the chosen pile initially contained s stones, you should choose an
integer k (0≤k≤s), move k stones from the chosen pile onto one of the remaining two piles and s−k
stones onto the other remaining pile. Determine if it is possible for the two remaining piles (in any
order) to contain x stones and y stones respectively after performing this action.
Input Format
The first line of the input contains a single integer T denoting the number of test cases. The
description of T test cases follows.
The first and only line of each test case contains five space-separated integers a,b,c, x and y.
Output Format
For each test case, print a single line containing the string “YES” if it is possible to obtain piles of the
given sizes or “NO” if it is impossible.
Constraints
1 ≤ T ≤ 100
1 ≤ a, b, c, x, y ≤ 700
12324
32565
24262
6 5 2 12 1
YES
NO
YES
NO
Q22.
Problem Statement:
In modern economic planning, governments and financial institutions need to dynamically adjust
budget allocations across different sectors to ensure economic stability and efficient resource
distribution. The Dynamic Fiscal Adjustment System (DFAS) is designed to monitor sectoral budget
utilization and suggest optimal reallocations based on real-time economic stress levels. Continuous
economic data updates allow policymakers to adapt to changing financial conditions and ensure
smooth fiscal operations.
Your task is to develop a system that takes real-time economic stress data and suggests optimal
budget reallocation strategies while also determining the most efficient fund transfer sequence
between financial sectors. The system should account for economic stress factors when
redistributing funds and ensure that total expenditure is minimized across all transfers.
The program must determine revised budget limits for affected sectors and compute the optimal
sequence of fund reallocations to maintain financial stability while ensuring that all sectors receive
the necessary funds. If no valid reallocation path exists between two sectors, the system should
indicate the impossibility of fund transfers.
Formulas:
Input Format
The first line contains an integer N, representing the number of financial sectors.
The second line contains an integer M, representing the number of fund transfer channels between
sectors.
The next M lines each contain three integers u v w, where u and v are sector IDs, and w represents
the allocated budget in millions of dollars.
The following line contains an integer K, representing the number of economic stress updates.
The next K lines each contain three integers x y z, where x and y are sector IDs, and z represents the
economic stress factor (as a percentage).
The final line contains two integers S and D, representing the source and destination sectors for fund
transfers.
Output Format
The next line of the output prints the Optimal Reallocation Path.
The last line of the output prints the Total minimum expenditure.
Constraints
1≤N≤7
1≤M≤8
1 ≤ u, v ≤ N1
1 ≤ w ≤ 60
1≤K≤3
1 ≤ x, y ≤ N
1 ≤ z ≤ 60
1 ≤ S, D ≤ N
All fund transfer channels are bidirectional, meaning fund movement between u and v is possible
both ways.
1 2 15
2 3 20
1 3 30
1 2 25
2 3 15
13
Budget Adjustments:
1 → 2: 8750M
2 → 3: 7250M
13
30
1 2 12
1 3 20
248
3 4 25
4 5 10
1 5 60
1 2 30
2 4 50
4 5 20
15
Budget Adjustments:
1 → 2: 9500M
2 → 4: 12500M
4 → 5: 8000M
Optimal Reallocation Path:
1245
30
Q23.
Problem Statement
You are a financial analyst at a top investment firm, and your client is a high-net-worth individual
looking to invest in the stock market. They have a fixed budget and can make up to two investments
in a particular stock over a given period. However, the market is unpredictable—some days see a
surge in stock prices, while others witness a sharp decline.
The client’s primary concern is risk management—they want to ensure that their investments are
made at the right time to maximize their portfolio's growth. They do not want to hold more than one
investment at a time, meaning they must sell their first investment before making a second one.
Additionally, they want a strategy that adapts to the market, whether it’s a slow upward trend,
sudden dips, or volatile fluctuations.
Your task is to analyze the given stock price data over a specific period and provide the best possible
strategy based on the market conditions. The client wants a clear breakdown of when to enter and
exit the market to ensure their funds are used optimally. However, they are also prepared for
scenarios where no suitable opportunities arise, in which case they prefer to hold onto their capital
rather than risk a loss.
With only two chances to enter the market, careful planning is essential. Can you provide the right
insights to guide their investment decisions?
Input Format
The first line of input contains an integer N, representing the number of days for which stock prices
are available.
The second line of input contains N space-separated integers representing the stock prices for each
day.
Output Format
The output prints a single integer representing the best possible strategy to achieve profit.
Refer to the sample output for formatting specifications.
Constraints
1 ≤ N ≤ 100
33500314
764310
Q24.
Problem Statement
In a bustling financial district, there are N investment opportunities, each offering a certain return on
investment (ROI). An ambitious investor, let's call her Alice, aims to maximize her gains. She can
choose one investment opportunity at a time, but there's a twist: she can only pick from the leftmost
or rightmost opportunity, and once she selects one, the adjacent opportunities become inaccessible.
Alice has devised a cunning strategy to maximize her returns, and she seeks your assistance in
determining the maximum gain she can achieve. Utilizing your programming expertise, implement a
function to find the answer for Alice. Can you calculate the maximum return on investment Alice can
secure by following her strategy?
Input Format
The first line consists of an integer N, representing the number of investment opportunities available
in the financial district.
The second line consists of N integers separated by a space, denoting the return on investment (ROI)
for each investment opportunity from left to right.
Output Format
The output prints a single integer representing the maximum return on investment (ROI) that Alice
can secure by following her strategy.
Constraints
1 ≤ N ≤ 25
8 15 3 7
22
2222
Q25.
Problem Statement
John, a seasoned financial analyst, is tasked with optimizing the budget allocation for a high-
frequency trading firm. The firm has a fixed budget B and a portfolio of N financial instruments such
as stocks, bonds, and commodities. Each instrument has specific constraints, including a minimum
required investment (Mᵢ), a maximum allowable investment (Lᵢ), and a risk factor (Rᵢ) that fluctuates
daily based on market trends.
John must devise an intelligent strategy to distribute the budget across these instruments over D
days, ensuring that the portfolio risk never exceeds a threshold T. Since the market is highly volatile,
returns and risk factors change daily, requiring dynamic reallocation of funds. However, reallocating
funds comes with a liquidation penalty, which must be minimized to avoid unnecessary losses.
The goal is to maximize overall returns while maintaining a balanced risk level throughout the
investment period. Given historical market data, John needs an efficient algorithm that determines
the optimal daily budget allocation for the portfolio while adhering to all constraints.
Formula:
scaleFactor = (T * B) / totalRisk
Input Format
The first line contains an integer N, representing the number of financial instruments.
The fourth line contains a floating-point number T, representing the maximum allowable portfolio
risk threshold.
The next N lines contain three integers and a floating-point number: Mᵢ, Lᵢ, Rᵢ(0), representing the
minimum investment, maximum investment, and initial risk factor for each financial instrument.
The next D sets of N lines contain two floating-point numbers Return(i, t) and Risk(i, t), representing
the daily return rate and updated risk factor for each instrument i on day t.
Output Format
The first line prints a floating-point number representing the maximum possible return at the end of
D days.
The next N lines display the final allocated budget for each instrument, in order of their input.
Constraints
1 ≤ N ≤ 105
1 ≤ D ≤ 105
1.0 ≤ B ≤ 10.04
0 ≤ Mᵢ ≤ Lᵢ ≤ B
0.0 ≤ T ≤ 1.0
500
0.4
0.05 0.2
0.04 0.15
0.06 0.1
0.02 0.3
0.03 0.2
0.05 0.1
565.06
286.60
278.46
1000
0.4
0.05 0.1
0.03 0.12
0.04 0.14
0.06 0.18
0.02 0.15
0.07 0.12
0.03 0.25
0.04 0.20
0.02 0.18
1124.69
382.13
364.21
378.35
Q26.
Problem Statement
In Transportopolis, the city's transport management system has established a critical command point
near a network of high-tech roads and routes. These roads are represented as line segments on a
two-dimensional plane and play a vital role in ensuring the smooth flow of traffic and energy-
efficient vehicle movement.
During the day, the transport system operates smoothly with a network of vehicles moving between
various locations. However, in order to optimize transportation routes and energy consumption, the
system needs to ensure that strategic vehicle positions are maintained.
Three smart vehicles are required to be positioned such that each vehicle can observe the other two,
ensuring efficient route planning and preventing unnecessary traffic congestion.
Given the network of roads represented as line segments on a plane, write a program to calculate
the number of ways the three vehicles can be placed such that each vehicle has a clear line of sight to
the other two while ensuring energy-efficient transportation flow.
Input Format
The first line of input consists of integer N, representing the number of roads (line segments).
The next N lines contain four integers x1, y1, x2, and y2, denoting the coordinates of the endpoints of
each road segment (x1, y1) to (x2, y2).
Output Format
The output prints a single integer representing the number of ways the three vehicles can be placed.
Constraints
1 ≤ N ≤ 20
0010
0001
1011
0111
0011
1001
5171
1151
4044
7034
2232
3233
3323
0
Q27.
Problem Statement
Alex is analyzing a bus network to identify which stops have charging stations for electric buses. The
bus network is represented as a 5x5 grid, where each cell corresponds to a bus stop. Some stops
have charging stations, marked with 'C'. The grid is initialized with three charging stations placed at
fixed positions. Alex can inspect up to 10 stops to determine if they have a charging station.
Your task is to write a program that simulates Alex's inspections, checks whether a stop has a
charging station or not, updates the grid after each inspection, and prints the total results at the end.
Input Format
The input consists of 10 lines of two integers, representing Alex's inspection in the format (row,
column), where both row and column are zero-based indices within the 5x5 grid. Alex can inspect up
to 10 stops.
Output Format
The program should print "Charging Station Found!" or "No Charging Station!" based on whether the
stop contains a charging station ('C') or is empty ('O').
Constraints
Input Validation: Inspections must be within the grid (0 ≤ row, column ≤ 4).
Charging Station Placement: Charging stations are fixed at positions (1, 1), (2, 3), and (4, 0).
11
23
40
00
10
33
04
22
44
30
Updated Grid:
OOOOO
OXOOO
OOOCO
OOOOO
COOOO
Updated Grid:
OOOOO
OXOOO
OOOXO
OOOOO
COOOO
Updated Grid:
OOOOO
OXOOO
OOOXO
OOOOO
XOOOO
No Charging Station!
Updated Grid:
XOOOO
OXOOO
OOOXO
OOOOO
XOOOO
No Charging Station!
Updated Grid:
XOOOO
XXOOO
OOOXO
OOOOO
XOOOO
No Charging Station!
Updated Grid:
XOOOO
XXOOO
OOOXO
OOOXO
XOOOO
No Charging Station!
Updated Grid:
XOOOX
XXOOO
OOOXO
OOOXO
XOOOO
No Charging Station!
Updated Grid:
XOOOX
XXOOO
OOXXO
OOOXO
XOOOO
No Charging Station!
Updated Grid:
XOOOX
XXOOO
OOXXO
OOOXO
XOOOX
No Charging Station!
Updated Grid:
XOOOX
XXOOO
OOXXO
XOOXO
XOOOX
Simulation Over
00
04
44
22
11
23
33
40
10
01
No Charging Station!
Updated Grid:
XOOOO
OCOOO
OOOCO
OOOOO
COOOO
No Charging Station!
Updated Grid:
XOOOX
OCOOO
OOOCO
OOOOO
COOOO
No Charging Station!
Updated Grid:
XOOOX
OCOOO
OOOCO
OOOOO
COOOX
No Charging Station!
Updated Grid:
XOOOX
OCOOO
OOXCO
OOOOO
COOOX
Updated Grid:
XOOOX
OXOOO
OOXCO
OOOOO
COOOX
Updated Grid:
XOOOX
OXOOO
OOXXO
OOOOO
COOOX
No Charging Station!
Updated Grid:
XOOOX
OXOOO
OOXXO
OOOXO
COOOX
Updated Grid:
XOOOX
OXOOO
OOXXO
OOOXO
XOOOX
No Charging Station!
Updated Grid:
XOOOX
XXOOO
OOXXO
OOOXO
XOOOX
No Charging Station!
Updated Grid:
XXOOX
XXOOO
OOXXO
OOOXO
XOOOX
Simulation Over
Total Charging Stations Found: 3
Q28.
Problem Statement
In a smart city, transportation systems are designed to optimize the movement of travelers across
various roads and intersections. Consider a scenario where a traveler must navigate through a grid-
based city layout, moving from the top-left corner to the bottom-right corner. Each cell in this grid
represents a segment of road, with a value that specifies the number of steps the traveler can move
in either the down or right direction. However, some cells are blocked (denoted by 0), preventing
movement through those points. The traveler’s task is to determine whether they can reach the
destination, and if so, mark the path they took through the grid. The key challenge here is that the
traveler must prioritize moving downwards first before considering moving right when both
directions are possible. Additionally, for the traveler to successfully reach the destination, the value
at the destination cell must be greater than 0.
The traveler starts at position (0,0) and aims to reach the bottom-right corner (n-1,m-1). The grid
contains values that define how far the traveler can move in either direction from each cell. If a cell’s
value is 3, the traveler can move up to 3 steps down or right, depending on the available paths. If the
traveler encounters a blocked cell or is unable to proceed in the grid, the algorithm must halt and
report the highest point they managed to reach. If the destination cell (bottom-right corner) has a
value of 0, the destination cannot be reached, even if there is a valid path up to that point. This
problem involves simulating the movement based on the current position, where the decision to
move down or right is made based on the cell value. The traveler is required to explore the grid until
they either reach the destination or are blocked.
The output should specify whether the destination was successfully reached and, if so, show the path
taken. If the destination is not reachable, the output should indicate the highest point reached by the
traveler. Additionally, the grid should be printed showing the path taken, with cells that the traveler
traversed marked as x, the highest reachable point marked with o, and other unvisited cells marked
as .. This approach will simulate the dynamic nature of smart city transportation, where travelers
need to navigate varying conditions and make decisions in real-time, all while prioritizing downward
movement over horizontal movement.
Input Format
The first line of input consists of two integers, n and m, which represent the number of rows and
columns in the grid.
The following n lines contain m integers each, where each integer represents the number of steps
the traveler can move from that cell.
A value of 0 denotes a blocked cell, while any positive integer indicates a valid cell where movement
is possible. The traveler must consider the movement constraints based on these values.
Additionally, if the value at the destination (n-1,m-1) is 0, the traveler cannot reach the destination,
regardless of whether a valid path exists to that point.
Output Format
The first line indicates whether the destination has been reached, printed as "Destination reached:
Yes or Destination reached: No".
The second line prints the highest point the traveler was able to reach, in the format "Highest point
reached: (row, col)".
The subsequent lines display the grid with the following marks:
Important: In the grid, the traveler must prioritize moving down first if possible. Hence, when
printing the grid," x " should represent the path that was successfully traveled, with the highest
reachable point marked as " o ". Blocked cells will remain as " . ".
Constraints
2 ≤ n, m ≤ 10
0 ≤ cityGrid[i][j] ≤ 1
33
111
101
111
Path Grid:
xoo
xoo
xxx
33
111
000
001
Destination reached: No
Path Grid:
ooo
...
...
Q29.
Problem Statement:
In the futuristic city of Rameshpur, an advanced autonomous vehicle system operates on a circular
track with designated docking stations. These vehicles, equipped with varying speeds and endurance,
must navigate efficiently to secure docking positions before they are eliminated. However, at regular
intervals, docking stations are removed, forcing vehicles to reevaluate their routes in real-time. The
challenge intensifies with the presence of shortcut portals that offer faster routes at a cost and
hazardous zones that can drain vehicle stamina or delay progress.
Each vehicle starts from a fixed position along the circular track and must decide the best path to
reach an available docking station while considering its stamina, speed, and strategic use of portals.
Additionally, power-ups providing temporary speed boosts and shields against hazards appear
randomly, adding an element of unpredictability. The vehicles that fail to secure docking positions
are eliminated at the end of each round.
Your task is to simulate this competition across multiple rounds and determine the sequence of
eliminated vehicles. The simulation involves strategic decision-making using pathfinding techniques
to minimize traversal costs and maximize survival chances.
Note:
- STAMINA REGEN = 1
- PORTAL RANGE = 10
- POWERUP INTERVAL = 3
Formulas:
- Powerup Effects:
Input Format
The next K lines each contain an integer M, representing the number of docking stations removed in
each round.
The next N lines contain an integer S, representing the speed of each vehicle.
The next N lines contain an integer T, representing the stamina of each vehicle.
The following P lines each contain three integers x, y, and c, representing the portal's start, end
positions, and usage cost.
The next line contains an integer R, representing the number of hazardous zones.
The following R lines each contain three integers x, r, and d, representing the hazard's position,
radius, and damage.
Output Format
The first line prints "Starting...".
Each round prints R[i] out: followed by a list of eliminated vehicle IDs.
The final line prints "Eliminated: " followed by the list of all eliminated vehicles.
Constraints
1 ≤ N ≤ 500
1≤K≤N
0≤M<N
1 ≤ S ≤ 100
1 ≤ T ≤ 1000
0 ≤ P ≤ 1000
0 ≤ R ≤ 1000
100
100
Starting...
R1 out: [0]
Alive: [1]
Eliminated: [0]
2
1
80
90
100
70
45 30 3
225 40 4
Starting...
R1 out: [0, 1, 2]
Alive: [3]
R2 out: [3]
Alive: []
Eliminated: [0, 1, 2, 3]
Q30.
Problem Statement
There are n cities, numbered from 0 to n-1. Given the array edges, where edges[i] = [ai, bi, weighti]
represents a bidirectional and weighted edge between cities ai and bi, and given the integer T
(distance Threshold).
Return the city with the smallest number of cities that are reachable through some path and whose
distance is at the highest distance threshold. If there are multiple such cities, return the city with the
greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edge weights
along that path.
Example 1:
Output: 3
Cities 0 and 3 have 2 neighboring cities at a T = 4, but we have to return city 3 since it has the
greatest number.
Example 2:
Output: 0
Input Format
The first line of input consists of integer n, representing the number of cities.
The second line of input consists of integer m, representing the number of edges.
The next m lines contain integers a, b, and weight, representing a bidirectional edge between cities a
and b with weight separated by spaces.
The last line of input consists of an integer T representing the maximum distance allowed to reach a
city.
Output Format
The output prints an integer representing the index of the city with the smallest number of reachable
cities within the given distance threshold. If there are multiple cities with the same smallest number
of reachable cities, return the city with the highest index.
Constraints
2 ≤ n ≤ 100
1 ≤ edges.length ≤ n * (n - 1) / 2
edges[i].length == 3
0 ≤ ai < bi < n
1 ≤ weighti, T ≤ 104
013
121
134
231
3
Sample Input Sample Output
012
048
123
142
231
341
Q31.
Problem Statement
Ram is working as a data analyst at a thriving e-commerce company that has a diverse range of
products.
The marketing team is planning a major campaign and needs to identify the most popular product to
feature. This will be determined based on sales data.
As part of the analytics team, your task is to process the sales data and find the most frequently
purchased product. This data-driven approach will help in tailoring the marketing strategy effectively
and potentially boost sales.
Ram has provided with a large dataset containing product IDs corresponding to each sale made on
the platform.
Each product ID is a unique identifier for a specific product. Your objective is to write a program that
sifts through this dataset and identifies the most popular product, i.e., the product that has been sold
the most.
This information is crucial for the marketing team to decide which product to highlight in their
upcoming campaign.
Input Format
The first line of input consists of an integer N, representing the number of products.
The second line consists of N integers, where each integer represents a product ID.
Output Format
The output should display the product ID that appears most frequently in the list.
If there are multiple products with the same highest frequency, return the product ID that appears
first in the list.
Constraints
1 ≤ N ≤ 105
201
401
Q32.
Problem Statement
You are presented with a series of investment stages, each representing a potential financial
opportunity with its initial investment, additional investment, projected returns, and investment
horizon. The objective is to determine the maximum achievable return on investment (ROI) by
strategically allocating funds across these investment stages.
Your task is to write a program that takes the following inputs:
The program should output the maximum achievable ROI by optimizing the allocation of funds across
the investment stages.
• Each investment must have a positive return over its horizon to be considered viable.
Input Format
The first line contains an integer n, representing the number of investment opportunities.
• The projected returns over the investment horizon (projected_returns) are given as a
percentage.
Output Format
The output displays a single integer, representing the maximum achievable return on investment
(ROI) obtained by optimally allocating funds across the investment opportunities.
Constraints
95 72 918 8
6 3 205 6
86 62 907 6
7 89 525 10
36 52 138 7
Q33.
Problem Statement
In a forward-thinking urban landscape, Mr. Jackson, a diligent citizen, strives to streamline financial
allocations within the city's educational system to foster sustainable development.
Facing constraints of limited resources and escalating educational needs, Mr. Jackson turns to you, a
proficient financial analyst, for guidance.
Upon analysis, you uncover that the educational system comprises multiple schools, each with
distinct budgetary requirements and distances from Mr. Jackson's residence. These schools serve as
nodes within the financial network, and your objective is to ascertain the maximum number of cost-
effective schools that can be included in an "Optimal Budget Set," adhering to specific criteria.
You develop an innovative algorithm to handle Mr. Jackson's inquiries, considering three key
conditions for each query:
Maximum Distance: The farthest distance from Mr. Jackson's home that his sons can travel to attend
school.
Maximum Tuition Fee: The highest fee Mr. Jackson can afford to pay for his son's education.=
Minimum Tuition Fee: The minimum fee Mr. Jackson is willing to pay to ensure quality education.
Your algorithm systematically filters the schools based on these conditions and calculates the
maximum number of schools that can form part of the "Optimal Budget Set." This set represents a
subset of financially viable schools, where no school holds a financial advantage over another within
the set.
As Mr. Jackson embarks on his quest for ideal educational institutions armed with your curated list,
the city's educational system embraces financial efficiency, paving the way for a brighter future.
How will your algorithm influence the city's financial landscape, and what obstacles will Mr. Jackson
encounter in his pursuit of the perfect schools for his sons?
Input Format
The first line contains an integer N, the number of schools in the smart grid system.
The following N lines each contain two space-separated integers, representing the distance from Mr.
Jackson's home and the fee F collected by the school.
The next line contains an integer Q, the number of queries from Mr. Jackson.
The following Q lines each contain three space-separated integers: maxDistance, maxFee, and
minFee.
Output Format
For each of his queries, he wants you to consider only a set S of schools that satisfy the given 3
conditions and all you need to do is just print the maximum number of schools that can be in a 'Max
Special S'.
Constraints
1 ≤ N ≤ 100,000
1 ≤ Q ≤ 100,000
minFee ≤ maxFee
11
22
43
34
15
534
546
514
314
426
2
1
Q34.
Problem Statement
Given an array nums with n objects colored red, white, or blue, sort them in place so that objects of
the same color are adjacent, with the colors in the order red, white, and blue. We will use the
integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function. Use the Selection sort
algorithm.
Example 1
Input:
202110
Output:
001122
Example 2
Input:
201
Output:
012
Input Format
The first line contains an integer n, representing the number of elements in the array.
The second line contains n space-separated integers, representing the colors in the array(either 0, 1,
or 2).
Output Format
The output prints a single line containing the sorted array of colors separated by a comma within a
square bracket.
Constraints
n == nums.length
1 ≤ n ≤ 300
nums[i] is either 0, 1, or 2.
202110
001122
201
012
Q35.
Problem Statement
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's
head.
1. Insertion sort iterates, consuming one input element each repetition and growing a sorted
output list.
2. At each iteration, insertion sort removes one element from the input data, finds the location
it belongs within the sorted list and inserts it there.
Example 1
Input:
4213
Output:
1234
Example 2
Input:
-1 5 3 4 0
Output:
-1 0 3 4 5
Input Format
The first line of input consists of an integer N representing the number of nodes in the linked list.
The second line of input consists of N space separated integers representing the values of the nodes
in the linked list.
Output Format
The output prints a single line containing N integers in ascending order, separated by spaces.
Constraints
In this scenario, the given test cases will fall under the following constraints:
1 ≤ N ≤ 30
4 1234
4213
5 -1 0 3 4 5
-1 5 3 4 0
Q36.
Problem Statement
Given a string s, remove duplicate letters so that every letter appears once and only once. You must
ensure your result is in the smallest order among all possible results.
Example 1:
Input: s = "bcabc"
Output: "ABC"
Example 2:
Input: cbacdcbc
Output: abcd
Input Format
The first line of input consists of a string s, representing the input string.
Output Format
Constraints
1 ≤ s.length ≤ 100
cbacdcbc abcd
Q37.
Problem Statement
You are given a 1-indexed 8 x 8 chessboard containing three pieces: a white rook, a white bishop, and
a black queen. You are provided with six integers: a b c d e f representing the positions of these
pieces:
The goal is to determine the minimum number of moves required for the white rook or white bishop
to capture the black queen.
Rules:
• The white rook can move any number of squares either vertically or horizontally but cannot
jump over other pieces.
• The white bishop can move any number of squares diagonally but also cannot jump over
other pieces.
• A rook or a bishop can capture the queen if it is on a square they can move to.
Your task is to return the minimum number of moves needed for either the white rook or white
bishop to capture the black queen.
Example 1:
Input: 1 1 8 8 2 3
Output: 2
Explanation: It is impossible to capture the black queen in less than two moves, as it is not under
immediate attack from any white piece initially.
- Move the white rook to (1, 3)
Example 2:
Input: 5 3 3 4 5 2
Output: 1
Explanation: Can capture the black queen in a single move by doing one of the following:
Input Format
Output Format
The output prints a single integer representing the minimum number of moves required to capture
the black queen.
Constraints
1 ≤ a, b, c, d, e, f ≤ 8
118823 2
533452 1
Sample 1 – Minimum Coins to Exhaust Energy (Greedy – Easy)
You are in a treasure room with a line of coins. Each coin has a certain value. You can pick a coin only
from the ends (either the first or the last coin in the row). Your goal is to collect coins such that the
total value is at least X, using the minimum number of coins. If it's not possible to reach the required
value with the available coins, return -1.
Parameters:
Case#: 1
Input:
5
15
1 2 3 4 10
Output:
3
Case#: 2
Input:
3
12
345
Output:
3
Case#: 3
Input:
4
20
1234
Output:
-1
Parameters:
• • N: INTEGER
• • deadlines[]: INTEGER ARRAY
• • profits[]: INTEGER ARRAY
Case#: 1
Input:
4
1221
20 10 40 30
Output:
70
Case#: 2
Input:
3
333
10 20 30
Output:
60
Case#: 3
Input:
3
121
5 15 25
Output:
40
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
7
1234567
Output:
7
Case#: 2
Input:
5
46531
Output:
3
Case#: 3
Input:
6
10 11 13 12 13 14
Output:
4
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Sample 7 – Custom Problem 7 (Category – Medium)
This is a placeholder description for problem 7. Students must process the input according to the
described logic.
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Sample 15 – Custom Problem 15 (Category – Medium)
This is a placeholder description for problem 15. Students must process the input according to the
described logic.
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Parameters:
• • N: INTEGER
• • arr[]: INTEGER ARRAY
Case#: 1
Input:
5
12345
Output:
Sample Output
Case#: 2
Input:
3
10 20 30
Output:
Sample Output
Case#: 3
Input:
4
5555
Output:
Sample Output
Question 1
Imagine you are helping a cashier at a local departmental store. At the end of the day, they want to
bundle all their sales data, which is recorded as a list of positive integers, representing the amount of
money earned in various transactions.
However, there's a catch — their reporting system only accepts even-numbered totals for processing.
So, if the total earnings (sum of all transactions) is already even, it can be submitted as is. But if the
total is odd, it must be rounded up to the next even number before submission.
• Returns the nearest even number that is equal to or greater than this total.
This is a common type of question where small logical adjustments like rounding up based on parity
(even/odd) are expected to be handled efficiently.
Input Format:
A single line of space-separated positive integers, representing the list of transaction amounts.
Output Format:
A single integer – the nearest even number that is equal to or greater than the total sum of the input
numbers.
Constraints:
Input:
375
Output:
16
Explanation:
• Total sum = 3 + 7 + 5 = 15
Input:
10 20 30 15
Output:
76
Explanation:
• Input numbers: 10, 20, 30, 15
• Total sum = 10 + 20 + 30 + 15 = 75
• Output is 76
Input:
462
Output:
12
Explanation:
• Input numbers: 4, 6, 2
• Total sum = 4 + 6 + 2 = 12
Question 2
Problem Statement:
You are given a positive integer. Your task is to count how many digits within this number are prime
digits. A prime digit is any digit that is itself a prime number. The single-digit prime numbers are 2, 3,
5, and 7.
For example, if the input number is 12345, the digits are 1, 2, 3, 4, and 5. Among these, the digits 2,
3, and 5 are prime digits. Therefore, the count would be 3.
Write a function that accepts a positive integer and returns the count of single-digit prime numbers
in it.
Input Format:
Output Format:
Constraints:
• 1 ≤ Number ≤ 10^18 (The input can be very large, so consider reading it as a string.)
Input:
12345
Output:
3
Explanation:
Input:
9876543210
Output:
Explanation:
• Digits: 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
Input:
4444
Output:
0
Explanation:
Question 3
Problem Statement:
You are given a string consisting of lowercase English alphabets. Your task is to find the
lexicographically next string that can be formed by rearranging the characters of the given string. If
such a string is not possible (i.e., the given string is already the lexicographically largest permutation),
then return the smallest possible string that can be formed using the same characters.
For example, consider the string "abc". The lexicographically next string is "acb". If the input string is
"cba", which is already the highest lex order permutation, the answer should be "abc", the smallest
possible arrangement.
You must implement a function to find and return this lexicographical neighbor.
Input Format:
Output Format:
A single string — the lexicographically next permutation if it exists; otherwise, the smallest
permutation possible with the same characters.
Constraints:
Input:
abc
Output:
acb Explanation:
• The permutations of "abc" in lex order are: "abc", "acb", "bac", ...
Input:
cba
Output:
abc Explanation:
"abc".
Sample Test Case 3:
Input:
abb
Output:
bab Explanation:
Question 4
Problem Statement:
In text processing, identifying repeated consecutive characters is a common task that can help in
compression algorithms or pattern recognition. You are given a string S consisting of lowercase
English letters. Your goal is to compress the string by replacing every sequence of consecutive
repeating characters with a single instance of the character followed by the count of its repetitions.
If a character appears only once consecutively, it should appear in the compressed string without a
count.
You must write a function to return the compressed version of the input string.
Input Format:
Constraints:
• 1 ≤ Length of S ≤ 10^5
Input:
aaabbcccc
Output:
a3b2c4 Explanation:
• The string contains the character 'a' repeated 3 times consecutively → "a3"
Input:
abcd
Output:
abcd Explanation:
• No counts are added; hence output remains the same as the input string.
Input:
zzzzzzzzzzzzzzzzzzzz
Output:
z20 Explanation:
• It is compressed to "z20".
Question 5
Problem Statement:
Imagine a scenario where you are designing a system that interprets a sequence of directional
commands represented as a string of characters 'L' and 'R'. Here, 'L' means a turn to the left, and 'R'
means a turn to the right. Your goal is to partition this command string into multiple segments where
each segment is balanced.
A balanced substring is one in which the number of 'L' characters is exactly equal to the number of 'R'
characters. Each balanced substring can be considered as a self-contained command sequence that
results in the device or robot facing the same direction it started with at the beginning of that
substring.
You need to find the maximum number of such balanced substrings into which the original command
string can be split.
Input Format:
A single line containing the string S, which consists only of the characters 'L' and 'R'.
Output Format:
An integer representing the maximum number of balanced substrings that can be obtained.
Constraints:
• 1 ≤ Length of S ≤ 10^5
Input:
RLRRLLRLRL
Output:
Explanation:
Each substring has equal counts of 'L' and 'R', which makes them balanced. Splitting at these points
gives the maximum count of balanced substrings, which is 4.
Input:
RLRRRLLRLL
Output:
Explanation:
• "RRRLLRLL" → Here, although there are multiple 'R's and 'L's, the total counts match (4 'R's
and 4 'L's), making this substring balanced.
However, it’s not possible to split the second substring further into smaller balanced parts to
increase the count. Thus, the maximum number of balanced substrings is 2.
Input:
LLLLRRRR
Output:
1
Explanation:
The entire string consists of 4 'L's followed by 4 'R's. There are no smaller balanced substrings inside
it since the characters are grouped together. The only balanced substring is the entire string itself,
giving the maximum count as 1.
Question 6
Problem Statement:
Imagine you are working on a cutting-edge image editing software that manipulates images
represented as square matrices of pixels. One of the features you need to develop is the ability to
rotate the layers of the matrix clockwise by one position.
A square matrix of size N x N can be thought of as having multiple layers (or rings). The outermost
layer is the border formed by the first row, last column, last row, and first column. The next layer lies
just inside the outer layer, and so on.
Your task is to rotate each layer of the matrix clockwise by exactly one element. For example, the
element at the top-left corner of the outer layer should move to the position just to its right, and so
on, wrapping around the entire layer. The inner layers must be rotated similarly.
Return the resulting matrix after performing this single-step clockwise rotation on all layers.
Input Format:
• The first line contains an integer N, the size of the square matrix.
• The next N lines each contain N space-separated integers representing the rows of the
matrix.
Output Format:
Print the resulting matrix after rotating all layers clockwise by one step.
Constraints:
• 2 ≤ N ≤ 100
Input:
1234
5678
9 10 11 12
13 14 15 16
Output:
5123
9674
13 10 11 8
14 15 16 12
Explanation:
→ 16 → 15 → 14 → 13 → 9 → 5
After rotating clockwise by one, each element moves to the position of its predecessor, so 5 takes
the place of 1, 1 moves to 2's place, and so on.
The inner layer contains 6, 7, 11, 10. Rotating clockwise by one step shifts these as well: 10 moves to
6's position, 6 moves to 7's position, etc.
Input:
123
456
789
Output:
412
753
896
Explanation:
For a 3x3 matrix, only one outer layer exists, containing elements: 1 → 2 → 3 → 6 → 9 → 8
→ 7 → 4.
After rotating clockwise by one, 4 moves to the top-left corner, 1 moves to the second element, and
so forth.
Input:
12
34
Output:
31
42
Explanation:
Rotating by one clockwise means 3 moves to the top-left, 1 moves to top-right, and so forth. This
rotation results in the given output.
Question 7
Problem Statement:
In the world of data compression and encryption, grouping digits of a number in meaningful ways can
optimize storage and improve security. You are given a string representing a large number. Your task
is to group the digits of this number such that the sum of the digits in each group is at most 10.
You need to find the minimum number of such groups required to partition the entire number from
left to right. The groups must be contiguous and cannot overlap or skip digits.
For example, if the number is "293817", one possible grouping is [2, 9, 3], [8], [1, 7]. The
sums are 2+9+3=14 (which is more than 10, so invalid), but if you try [2, 9], [3, 8], [1, 7], the sums are
11, 11, and 8 respectively — still invalid. The task is to find the minimum number of groups where
each group sum ≤ 10.
Input Format:
• A single line containing the string representation of the number (digits only, no spaces).
Output Format:
Constraints:
Input: 293817
Output: 4
Explanation:
We want to group the digits so each group sums up to at most 10. Possible valid grouping is: [2, 9] →
11 (invalid)
[2], sum=2
[9], sum=9
[2], sum=2
[2], sum=2
[9], sum=9
[3], sum=3
[7], sum=7
[2], sum=2
[9], sum=9
[3, 8], invalid
One valid grouping: [2], [9], [3], [8,1,7] with sums 2, 9, 3, 16 (invalid)
So instead: [2], [9], [3], [8], [1,7] with sums 2,9,3,8,8 → 5 groups. After carefully checking, the
minimal groups needed is 4.
Input:
11111
Output:
Explanation:
But since sum ≤ 10, we can have all in one group. So output should be 1, but constraints require
contiguous grouping and the problem demands the minimum number of groups, which is actually 1.
So output is 1.
Input: 987654321
Output:
Question 8
Problem Statement:
Palindromes are strings that read the same forwards and backwards, and they hold a special place in
many areas such as text processing and DNA sequencing. Given a string, your goal is to find the
minimum number of character insertions needed to convert the string into a palindrome.
You can insert characters anywhere in the string any number of times. The inserted characters do not
need to be part of the original string. Your task is to compute the least number of insertions required
to make the string a palindrome.
For example, consider the string "abc". By inserting 'b' and 'a' appropriately, it can be converted into
"abcba", which is a palindrome. The minimum number of insertions here is 2.
Input Format:
Output Format:
Print a single integer representing the minimum number of insertions needed to make S a
palindrome.
Constraints:
• 1 ≤ Length of S ≤ 500
Input:
abc
Output:
Explanation:
By inserting characters, we can transform it into "abcba". Steps: Insert 'b' after 'c' → "abcb"
Input:
aabb
Output:
Explanation:
Insert 'b' at the start → "baabb" Insert 'a' at the end → "baabba" "baabba" is a palindrome.
Minimum insertions = 2.
Sample Test Case 3:
Input:
racecar
Output:
Explanation:
Question 9
Problem Statement:
In a grid of size M x N, you start from the top-left corner (cell (1,1)) and want to reach the bottom-
right corner (cell (M,N)). You can only move either down or right at any point in time.
However, some cells in the grid contain blockers, making them inaccessible. You cannot step on
these blocked cells.
Given the grid layout, determine the total number of unique paths from the start to the destination
that do not pass through any blocked cell.
Since the number of unique paths can be large, output the result modulo 10^9 + 7.
Input Format:
• The first line contains two integers M and N, the number of rows and columns of the grid.
• The next M lines each contain N integers (0 or 1), where 0 indicates a free cell and 1 indicates
a blocked cell.
Output Format:
Print a single integer representing the total number of unique paths modulo 10^9 + 7.
Constraints:
• 1 ≤ M, N ≤ 1000
• The start cell (1,1) and destination cell (M,N) are always free (0).
Input: 3 3
000
010
000
Output:
Explanation:
Grid:
2. Down → Down → Right → Right Moving through (2,2) is not allowed. So total 2 unique paths.
Input:
22
01
00
Output:
Explanation:
Input:
22
01
10
Output:
0
Explanation:
Both (1,2) and (2,1) are blocked. No paths exist from (1,1) to (2,2).
Question 10
Problem Statement:
You are given an integer array nums of length n. Your task is to determine if the array can be split
into four parts by selecting three indices i, j, and k such that:
• The sum of the elements in each of the four parts is equal. That is:
Here, the parts are the subarrays between the indices, excluding the indices i, j, and k
themselves.
Input Format:
• The second line contains n space-separated integers representing the array elements.
Output Format:
Print true if the array can be split as described; otherwise, print false.
Constraints:
• 7 ≤ n ≤ 10^5
Input:
1212121
Output: true
Explanation:
Input:
1234567
Output:
false
Explanation:
No such indices exist to split the array into four parts with equal sums. Hence output is false.
Input:
251251251
Output:
true
Explanation:
nums[6..6] = [2], sum=2 (does not match sum=7) This split is invalid. Try other indices until:
Parts:
Eventually, if indices satisfy the condition, output true, otherwise false. For this input, such a split
exists.
Question -11
You are given a square matrix N×N of integers. Your task is to calculate the sum of elements from
three distinct regions:
1. Main diagonal and its adjacent diagonals: Elements from the main diagonal and one diagonal
on each side (above and below).
Note: Each element in the matrix can contribute to only one region.
The first line contains two integers N and K, where N is the size of matrix(NxN) and K is the size of
the central sub-matrix.
The next N lines each contain N space separated integers, representing the matrix elements.
Print a single integer representing the sum of the three regions, adhering to the above rules.
Explanation
Elements:
Unique Elements:
{1,5,9,1,9,2,6,7,1,4,8,9,8}
Sum: 1+5+9+1+9+2+6+7+1+4+8+9+8=70
2. Border Elements
Elements:
{3,4,3,8,2,6,4,2,3,7}
Sum:
3+4+3+ 8+2+6+4+2+3+7=42
3. Central Sub-Matrix
Element:
(3,3)=9
Sum: 0
Total Sum
Explanation
{4,5,9,2,6,1,8}
Sum: 4+5+9+2+6+1+8=35
2. Border Elements
• Overlaps: 4,2,6,8,9,1
• Sum: 3+7=10
3. Central Sub-Matrix
For k=1, the central sub-matrix is the single element at the center of the matrix, (2,2)=5 but (2,2) is
already selected so we will take 0.
Sum: 0
Total Sum
Question -12
Alice loves palindromes. She has been given a string S of length N, and she can perform up to K
operations on the string. Each operation can either be an insertion or a deletion of a character at any
position in the string. The goal is to determine how many distinct palindromic strings can be formed
after exactly K operations and also return the lexicographically smallest palindrome that can be
created.
Operations:
• Insertion: You can insert any character at any position in the string.
Count of palindromic string in line 1: the count of distinct palindromic strings that can be formed by
performing exactly K operations.
Palindrome string in line 2: The lexicographically smallest palindrome string that can be obtained
within the given number of operations.
1 <= k < N
Explanation
The output -1 indicates that it is not possible to generate a palindrome by inserting or deleting
characters from "hello" up to 2 times
Explanation
After all operations, the set will have 40 distinct palindromic strings, including:
Question -13
In the kingdom of Numeria, wealth fluctuated across villages, creating unrest. To restore stability,
King Algo summoned his trusted advisor, Sir Codewell, with a challenge:
"Find the smallest possible maximum wealth difference among any K contiguous villages!"
Sir Codewell knew brute force wouldn’t work—he needed a smart, efficient approach. With careful
calculations, he searched for the most balanced segment among N villages.
Would he succeed in restoring harmony, or would Numeria remain in chaos? The kingdom’s fate
rested on his solution...
The first line of input conains an integer N representing the number of elements in the array.
The second line of input contains an array arr of length N containing integers separated by space.
The third line of input contains an integer K representing the size of the subarray.
Print an integer representing the smallest maximum difference among all contiguous subarrays of
size k.
1 ≤ N ≤ 10^5
1≤K≤N
Explanation
Explanation
You are given a string S of length N, consisting of lowercase English letters. Your task is to partition
the string into the minimum number of palindromic substrings while also minimizing the cost of
partitioning.
The cost of partitioning is defined as the sum of ASCII values of the characters at both ends of each
cut. If multiple ways exist to achieve the minimum number of palindromic partitions, select the one
with the lowest cost.
Return the minimum cost required to partition the string. If the string is already a palindrome, return
0.
Return the minimum cost required to partition the string. If the string is already a palindrome, return
0.
1 ≤ N ≤ 10^4
The partition happens at three points, adding the ASCII values of the characters at the split positions:
ASCII('a') = 97
ASCII('b')
Cost = 97 + 98 = 195 = 98
Between "bcb"
"d" →
ASCII('b') = 98
ASCII('d')
Between "d"
"a" →
ASCII('d') = 100
ASCII('a')
Question -15
You are given N tasks, each with a required time time[i] and a dependency condition. There are some
conditions given called as dependencies, where each element (a, b) means that task b cannot start
until task a is completed.
You need to determine the minimum time required to complete all tasks given that:
• A task can only start when all its dependencies are met.
The first line contains an integer N, representing the number of tasks.
The second line contains an array time of size N where time[i], represents the time required to
complete the i-th task.
The third line contains an integer M, representing the number of dependency relations.
The next M lines, each line contains two space-separated integers a b, representing a dependency
where task a must be completed before task b
Print a single integer representing the minimum time required to complete all tasks.
1 ≤ N ≤ 10^5
1 ≤ time[i] ≤ 1000
0 ≤ M ≤ 10^5
0 ≤ a, b < N
Explanation
Task 0 takes 2 units of time.
Task 4 is independent and takes 2 units of time, but since it can run in parallel, the answer is max(9,
2) = 9.
Explanation
Step-by-step Explanation:
Question -16
In a futuristic world, a groundbreaking robot named RoboLex was built to interpret human
instructions fed to it as strings. RoboLex's advanced programming allowed it to traverse the string
character by character, identifying meaningful substrings that corresponded to actions.
For example, encountering the substring "run" made RoboLex sprint forward, "jump" caused it to
leap over obstacles, and so on.
However, RoboLex had its flaws. A critical oversight was discovered when the
word "kill" appeared in the instruction string. This caused RoboLex to mistakenly attempt destructive
behaviors—an action completely unintended by its creators, who envisioned it as a harmless
assistant.
To address this flaw, RoboLex's creators devised a simple rule: if "kill" appeared as a substring in the
instructions, RoboLex would halt all operations. Therefore, to ensure RoboLex worked efficiently, its
creators needed to remove just enough characters from the instruction string to eliminate all
occurrences of "kill" while preserving as many meaningful actions as possible.
Can you help its creators determine the longest possible instruction string that RoboLex can safely
execute without encountering the forbidden substring?
The first line contains an integer N, the length of the instruction string.
The second line contains a string S of length N consisting of lower-case Latin letters (a to z).
Print a single integer, the length of the longest possible instruction string that RoboLex can safely
execute without encountering the forbidden substring "kill".
Explanation
If we remove k from the string, there is no substring “kill”. The string becomes “abcillxyz” with length
9.
Explanation
There are two occurrences of “kill” in S, so we remove k from both, which is also the minimum
characters needed to remove all occurrences of “kill” from S. The remaining string becomes
illabcillxyz, length of which is 12.
Question -17
Problem Title: Encoding
Ram and Shyam have devised a new encoding scheme called "Reverse Mirror Encoding." In this
system:
For letters 'a' to 'n', the code is their reverse position in the first half of the alphabet.
For letters 'o' to 'z', the code is their reverse position in the second half of the alphabet followed by a
#.
Given a coded message S, determine the original decoded message Ram sent to Shyam.
The first and only line of input contains a single string S, representing the encoded message.
'u#' → 't'.
'j' → 'e'.
'l' → 'c'.
'g' → 'h'.
Explanation
'm' → 'b'.
'j' → 'e'.
't#' → 'u'.
'a' → 'n'.
'v#' → 's'.
'u#' → 't'.
'z#' → 'o'.
'y#' → 'p'.
'y#' → 'p'.
'n' → 'a'.
'm' → 'b'.
'c' → 'l'.
'j' → 'e'.
Question -18
You are given a number N and asked to calculate X based on the following recurrence rules:
Base cases:
• If N = 0, then X = 5.
• If N = 1, then X = 3.
Where F(N) represents the value of X for N calculated according to the above rules.
Explanation
Given N = 10, We need to calculate F[2], F[3], F[4], ... , F[9], such that F[10] = (F[9]
+ F[8]) mod 999, which will give answer = 675.
Explanation
Given N = 5, We need to calculate F[2], F[3] and F[4], such that F[5] = (F[4] +
F[3]) mod 998, which will give answer = 288.
Question -19
Alice had a string T, a secret message, and Bob had a string S, which was a sequence of random
letters. Bob had an interesting habit — every day, he would reverse the string he had
and then append the original string S to the reversed string. Alice was curious to know on which day
the secret message T would first appear as a subsequence in Bob's growing string.
For example, if S was “abc”, Bob would start with “abc” on the first day. The next day, he would
reverse “abc” to get “cba” and append “abc” again, so his string would become “cbaabc”. On the
third day, Bob would reverse “cbaabc” to get “cbacba” and then append “abc” again, resulting in
“cbacbaabc”.
Alice, being a curious mind, wanted to know the first day on which her secret message T would show
up as a subsequence in Bob’s string. Bob kept repeating his string- reversing and appending process
every day, but Alice couldn’t keep track of when exactly her message would appear.
Output a single integer, representing the number of days when Alice's string will be a subsequence of
Bob's string for the first time.
Explanation
Day 1: The string Bob has is "abcd". We check if "cba" is a subsequence of "abcd". It’s not, because
the characters "cba" do not appear in that order. So, on Day 1, "cba" is not a subsequence.
Day 2: Bob reverses "abcd" to "dcba" and appends S, forming "dcbaabcd". We check if "cba" is a
subsequence of "dcbaabcd". It’s still not, because the order "cba" does appear in the string. So, on
Day 2, "cba" is a subsequence.
Explanation
Day 1: The string Bob has is S = "jabgi". We check if "gij" is a subsequence of "jabgi". It’s not, because
we cannot find "gij" in that order.
Day 2: Bob reverses "jabgi", which becomes "igbaj", and appends S again, forming "igbajjabgi".
We check if "gij" is a subsequence of "igbajjabgi". This still isn’t true.
Day 3: Bob reverses "igbajjabgi", forming "igbajjabgi" again, and appends S, resulting in
"igbajjabgijabgi". We check if "gij" is a subsequence of "igbajjabgijabgi". It is, so on Day 3, "gij"
becomes a subsequence.
Easy
1. Collecting Baskets
Problem Statement:
There is a long stretch of market stalls. Each stall has a certain number of fruit baskets. You start at
the first stall and can only move forward. At every step, you are allowed to pick up baskets from that
stall—but there’s a twist.
You can only collect baskets in increasing order of quantity (strictly). That means, if the last basket
you collected had X baskets, you can only pick a basket with more than X baskets next.
You want to know the maximum number of baskets you can collect following this rule.
Input Format:
• Second line contains N integers separated by space, where each integer A[i] denotes the
number of baskets at the i-th stall.
Output Format:
• A single integer — the maximum number of baskets you can collect in increasing order.
Sample Input 1:
132546
Sample Output 1:
Explanation:
Sample Input 2:
54321
Sample Output 2:
Explanation:
Only one basket can be collected at most, since all are in decreasing order.
Test Cases
Input 1
1
10
Output 1
Input 2
333
Output 2
Input 3
123456
Output 3
Input 4
77777
Output 4
Input 5
10 22 9 33 21 50 41 60
Output 5
Input 6
6
132435
Output 6
Input 7
10
100 90 80 70 60 50 40 30 20 10
Output 7
Input 8
2 4 6 8 10 12 14
Output 8
Code
def max_baskets(arr):
tails = []
if pos == len(tails):
tails.append(basket)
else:
tails[pos] = basket
return len(tails)
# Read input
n = int(input())
# Print output
print(max_baskets(arr))
Problem Statement:
There’s a single ticket counter and a line of people waiting. Each person needs a specific amount of
time to be served, which is represented by an array T.
The counter serves people in order, but here's the rule: the counter works in rounds. In each round,
the person at the front gets served for 1 time unit, then goes to the back of the queue if their
remaining time is more than 0.
You are given the time required for each person, and you are asked to calculate how many time units
it will take before the K-th person (0-indexed) in the original queue completes their service.
Input Format:
• First line contains two integers N (number of people) and K (index of target person).
• Second line contains N space-separated integers, where T[i] is the total time required for the
i-th person.
Output Format:
• A single integer — total time taken until the K-th person completes service.
Sample Input 1:
42
1234
Sample Output 1:
Explanation:
Sample Input 2:
50
51111
Sample Output 2:
Test Cases
Input 1
10
Output 1
Input 2
32
111
Output 2
3
Input 3
30
333
Output 3
Input 4
54
11115
Output 4
Input 5
62
331333
Output 5
Input 6
52
22222
Output 6
Input 7
52
10 2 3 1 1
Output 7
10
Input 8
43
1115
Output 8
Code
total_time = 0
while queue:
time_left -= 1
total_time += 1
if time_left == 0:
if idx == k:
return total_time
else:
queue.append((idx, time_left))
n, k = map(int, input().split())
# Output result
print(ticket_counter_time(n, k, times))
3. Repeating Pairs
Problem Statement:
You are given a string S. Your task is to count how many distinct pairs of characters occur more than
once as consecutive characters in the string.
A "pair" means two characters next to each other. Pairs are considered the same if they have the
same characters in the same order (e.g., ab and ab are the same, ab and ba are different).
Input Format:
Output Format:
• Print a single integer — the number of distinct character pairs that appear more than once as
consecutive characters.
Sample Input 1:
ababcabc
Sample Output 1:
2
Explanation:
Consecutive pairs:
ab occurs 3 times
bc occurs 2 times
Sample Input 2:
aaaa
Sample Output 2:
Test Cases
Input 1
abcdef
Output 1
Input 2
Output 2
Input 3
abababa
Output 3
Input 4
abcabcabc
Output 4
3
Input 5
aaaaaa
Output 5
Input 6
abcdefg
Output 6
Input 7
abababab
Output 7
Input 8
Output 8
Code
def count_repeating_pairs(s):
pair_count = defaultdict(int)
pair_count[pair] += 1
# Count pairs that appear more than once
# Read input
s = input().strip()
# Output result
print(count_repeating_pairs(s))
Problem Statement:
• Digits (0-9)
If multiple characters have the same maximum frequency, return the one that comes first in
alphabetical order.
Input Format:
Output Format:
• A single lowercase letter — the most frequent alphabetic character (after cleanup).
Sample Input 1:
Sample Output 1:
Explanation:
Cleaned string: helloworld → Frequencies: h:1, e:1, l:3, o:2, w:1, r:1, d:1
Most frequent: l
Sample Input 2:
A@aaBBccC1234#
Sample Output 2:
Test Cases
Input 1
aaBBccC
Output 1
Input 2
aaBBccCaa
Output 2
Input 3
AAAAaaaaAAAaaa!!!@@@
Output 3
Input 4
xxYYzz!!
Output 4
Input 5
QWERTYQWERTY
Output 5
Input 6
!!!@@@###bbb%%%^^^
Output 6
Input 7
aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1234567890!@#$
Output 7
Input 8
Output 8
Code
def most_frequent_letter(s):
freq = defaultdict(int)
for char in s:
if char.isalpha(): # Only consider alphabetic characters
char = char.lower()
freq[char] += 1
if not freq:
# Find the character with highest frequency, break ties by alphabetical order
max_freq = max(freq.values())
print(result)
# Read input
s = input().strip()
most_frequent_letter(s)
5. Lonely Light
Problem Statement:
In a row of street lights, only one light is faulty — it flickers only when it receives power an odd
number of times.
You are given an array of integers, where each integer represents the ID of a street light that received
power. Every light gets powered an even number of times — except for one faulty light that was
powered an odd number of times.
Input Format:
• Second line contains N space-separated integers representing the light IDs that received
power.
Output Format:
Sample Input 1:
12321
Sample Output 1:
Explanation:
Sample Input 2:
5754794
Sample Output 2:
Test Cases
Input 1
42
Output 1
42
Input 2
4565477
Output 2
Input 3
3
10 20 10
Output 3
20
Input 4
838632255
Output 4
Input 5
11
9 10 10 12 13 9 13 15 15 12 11
Output 5
11
Input 6
11 12 13 11 12 13 14
Output 6
14
Input 7
56765
Output 7
Input 8
3
1000 2000 1000
Output 8
2000
Code
def find_faulty_light(arr):
result = 0
return result
# Read input
n = int(input())
# Output result
print(find_faulty_light(arr))
Problem Statement:
You are given an array of integers. Your task is to find all unique pairs of integers in the array whose
sum is equal to a given target value.
Input Format:
• The first line contains an integer n (1 ≤ n ≤ 1000), the number of elements in the array.
• The second line contains n space-separated integers, representing the elements of the array.
• The third line contains an integer target, representing the sum you need to find pairs for.
Output Format:
• Output all unique pairs of integers whose sum equals the given target.
• Each pair should be printed on a new line, with the two integers separated by a space.
142335
Sample Output 1:
15
24
33
Sample Input 2:
10 20 30 40 50
100
Sample Output 2:
No pairs found
Test Cases
Input 1
10
Output 1
No pairs found
Input 2
2222
Output 2
22
Input 3
31456279
10
Output 3
19
37
46
Input 4
1234
10
Output 4
No pairs found
Input 5
513724
Output 5
17
35
Input 6
-1 -2 3 4 5
Output 6
-2 5
-1 4
Input 7
333333
Output 7
33
Input 8
10
Output 8
No pairs found
Code
if complement in seen:
result.add(tuple(sorted((num, complement))))
seen.add(num)
if result:
print(pair[0], pair[1])
else:
# Reading input
find_pairs(arr, target)
Problem Statement:
Given a non-negative integer n, your task is to count the number of set bits (1s) in its binary
representation.
Input Format:
Output Format:
Sample Input 1:
Sample Output 1:
Explanation:
15
Sample Output 2:
Explanation:
Test Cases
Input 1
Output 1
Input 2
64
Output 2
Input 3
255
Output 3
Input 4
254
Output 4
Input 5
164
Output 5
Input 6
128
Output 6
Input 7
42
Output 7
Input 8
1024
Output 8
Code
def count_set_bits(n):
count = 0
while n:
count += 1
print(count)
# Input parsing
n = int(input())
count_set_bits(n)
A number is considered digit-power-weighted if the sum of its digits raised to their position from left
to right, multiplied by their position, results in a unique score.
Given a positive integer n, calculate its weighted digit power sum using the formula:
Input Format:
Output Format:
Sample Input 1:
321
Sample Output 1:
14
Explanation:
Digits: 3 2 1
• 3^1 * 1 = 3
• 2^2 * 2 = 4 * 2 = 8
• 1^3 * 3 = 1 * 3 = 3
Total = 3 + 8 + 3 = 14
Sample Input 2:
245
Sample Output 2:
409
Explanation:
• 2^1 × 1 = 2
• 4^2 × 2 = 16 × 2 = 32
Test Cases
Input 1
Output 1
Input 2
111
Output 2
Input 3
Output 3
Input 4
222
Output 4
34
Input 5
123
Output 5
90
Input 6
321
Output 6
14
Input 7
406
Output 7
652
Input 8
105
Output 8
376
Code
def weighted_digit_power_sum(n):
s = str(n)
total = 0
for i, ch in enumerate(s):
digit = int(ch)
power = digit ** (i + 1)
total += power * (i + 1)
print(total)
# Read input
n = int(input())
weighted_digit_power_sum(n)
Chef Rahul has recently taken a pledge to improve his health. Every morning, he drinks different fruit
smoothies lined up in a long queue at his smoothie bar. Each smoothie has a certain energy value,
which can be positive (if it boosts his energy) or negative (if it's a detox smoothie that lowers it).
Chef wants to figure out which k-day stretch of smoothies gives him the maximum total energy. He
can only pick a consecutive sequence of k smoothies.
You must help Chef find the maximum energy he can gain in any stretch of k consecutive days.
Input Format:
• Second line: n space-separated integers representing the energy values of the smoothies.
Output Format:
A single integer – the maximum total energy Chef can gain from any k consecutive smoothies.
Sample Input 1:
66
123456
Sample Output 1:
21
Sample Input 2:
52
-1 -2 -3 -4 -5
Sample Output 2:
-3
Test Cases
Input 1
11
Output 1
5
Input 2
53
12345
Output 2
12
Input 3
62
-1 -2 -3 -4 -5 -6
Output 3
-3
Input 4
74
3 -1 2 -5 4 6 -2
Output 4
Input 5
83
1 -1 2 -2 3 -3 4 -4
Output 5
Input 6
63
10 9 8 -1 -2 -3
Output 6
27
Input 7
62
-1 -2 -3 4 5 6
Output 7
11
Input 8
95
222222222
Output 8
10
Code
window_sum = sum(energy[:k])
max_sum = window_sum
return max_sum
# Read input
n, k = map(int, input().split())
print(max_energy_window(n, k, energy))
Problem Statement:
An ancient locker in a treasure vault opens only when you enter a "Lucky Code". A number is
considered lucky if the sum of its digits is a multiple of 4.
You're given a number N. Your task is to find the smallest integer greater than or equal to N which is
a lucky code.
Input Format:
Output Format:
Sample Input 1:
100
Sample Output 1:
103
Explanation:
101 → 1 + 0 + 1 = 2 → No
102 → 1 + 0 + 2 = 3 → No
103 → 1 + 0 + 3 = 4 → Correct
Sample Input 2:
1234
Sample Output 2:
1236
Test Cases
Input 1
Output 1
Input 2
16
Output 2
17
Input 3
9999
Output 3
9999
Input 4
256
Output 4
259
Input 5
1006
Output 5
1007
Input 6
2017
Output 6
2019
Input 7
10
Output 7
13
Input 8
45
Output 8
48
Code
def is_lucky(n):
def find_lucky_code(n):
n += 1
return n
# Read input
n = int(input())
print(find_lucky_code(n))
Problem Statement:
In a small village by the river, the villagers are crossing a stream using rocks. The rocks are placed at
varying distances from each other along the riverbank. A young boy wants to cross the river, but he is
only allowed to jump between rocks that are at a specific distance apart. You are tasked with helping
the boy identify all the pairs of rocks where the difference between their positions equals a given
distance.
Input Format:
• The first line contains an integer n (1 ≤ n ≤ 1000), the number of rocks placed along the river.
• The second line contains n integers rocks[0], rocks[1], ..., rocks[n-1] (1 ≤ rocks[i] ≤ 10^6),
representing the positions of the rocks in sorted order.
• The third line contains an integer target_distance (1 ≤ target_distance ≤ 10^6), the distance
between the rocks the boy can jump.
Output Format:
• For each pair of rocks whose difference in positions equals the target_distance, print the pair
on a new line as (rock1, rock2).
Sample Input 1:
1 3 5 7 9 11
Sample Output 1:
(1, 3)
(3, 5)
(5, 7)
(7, 9)
(9, 11)
Sample Input 2:
2 4 6 8 10
Sample Output 2:
No pairs found
Test Cases
Input 1
2 4 6 8 10
Output 1
No pairs found
Input 2
1357
4
Output 2
(1, 5)
(3, 7)
Input 3
1 3 5 7 9 11
Output 3
(1, 3)
(3, 5)
(5, 7)
(7, 9)
(9, 11)
Input 4
1234567
Output 4
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
Input 5
5 1 10 8 6 4 3
2
Output 5
No pairs found
Input 6
10 15 20 25 30
Output 6
(10, 15)
(15, 20)
(20, 25)
(25, 30)
Input 7
123456
Output 7
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
Input 8
100
Output 8
No pairs found
Code
def find_pairs_with_distance(rocks, target_distance):
left = 0
right = 1
pairs = []
if current_diff == target_distance:
pairs.append((rocks[left], rocks[right]))
left += 1
right = left + 1 # Reset the right pointer to one step ahead of the left
right += 1
else:
left += 1
if left == right:
right += 1
if not pairs:
else:
print(f"({pair[0]}, {pair[1]})")
# Example usage
if __name__ == "__main__":
# Sample Input 1
find_pairs_with_distance(rocks, target_distance)
Problem Statement:
Sara is writing her college essay in a simple text editor that only supports typing lowercase alphabets
and undoing the last letter using the backspace key (represented by #). She types a sequence of
characters, and for every #, the last typed character (if any) gets removed.
Can you help her figure out the final text after all typing and backspaces?
Input Format:
• A single line string s (1 ≤ |s| ≤ 10^5), consisting of lowercase letters and the # character.
Output Format:
• A single line containing the final string after processing all characters.
Sample Input 1:
abc#d##
Sample Output 1:
Sample Input 2:
a#bc##d
Sample Output 2:
Test Cases
Input 1
##abc
Output 1
abc
Input 2
hello
Output 2
hello
Input 3
abc###xyz
Output 3
xyz
Input 4
helloworld
Output 4
helloworld
Input 5
a#b#c#d#e
Output 5
Input 6
abc##de#
Output 6
Ad
Input 7
a#bc#d#efg#h#
Output 7
bef
Input 8
a#b#c#d#e#f#z
Output 8
Code
def process_typing(s):
stack = []
for ch in s:
if ch == '#':
if stack:
stack.pop()
else:
stack.append(ch)
return ''.join(stack)
# Example usage:
if __name__ == "__main__":
s = input().strip()
print(process_typing(s))
Problem Statement:
A warehouse robot is stacking boxes represented by opening [ and closing ] brackets. It follows a
sequence of commands, where:
Your job is to determine whether the robot has stacked and unstacked the boxes correctly. That is,
every opening [ must have a corresponding closing ], and the order must be valid.
Input Format:
• A single line string s consisting only of the characters [ and ].
Output Format:
Sample Input 1:
[[]]
Sample Output 1:
Balanced
Sample Input 2:
][][
Sample Output 2:
Unbalanced
Test Cases
Input 1
[]
Output 1
Balanced
Input 2
[[[]]]
Output 2
Balanced
Input 3
][
Output 3
Unbalanced
Input 4
[[[]]
Output 4
Unbalanced
Input 5
[]][[]
Output 5
Unbalanced
Input 6
[[[[[]]]]]
Output 6
Balanced
Input 7
[][[[[]]]]
Output 7
Balanced
Input 8
]]]]
Output 8
Unbalanced
Code
def is_balanced_boxes(s):
stack = []
for ch in s:
if ch == '[':
stack.append(ch)
elif ch == ']':
if not stack:
return "Unbalanced"
stack.pop()
# Example usage
if __name__ == "__main__":
s = input().strip()
print(is_balanced_boxes(s))
Medium
Problem Statement:
In the ancient kingdom of Chronosia, there exists a legendary thief named Kael who can steal time
from time crystals. Each time crystal has a time value and a steal time (how long it takes to steal from
it). Kael has T minutes before the royal guards catch him. His goal is to maximize the amount of time
he can steal from the available crystals before he gets caught.
Each crystal can only be stolen once and stealing must be completed fully to obtain the time value.
Kael decides to steal from the most "efficient" crystals first, where efficiency is defined as the highest
time value per unit of steal time. Help Kael make the optimal choice.
Input Format:
• The second line contains an integer T — the total time Kael has before the guards arrive.
• The next N lines each contain two integers vi and ti — value of time (vi) and time to steal (ti)
for each crystal.
Output Format:
• Print a single integer — the maximum total value of time Kael can steal before getting
caught.
Sample Input 1:
4
10
60 2
100 4
120 6
30 1
Sample Output 1:
190
Sample Input 2:
50 3
70 4
30 2
Sample Output 2:
70
Test Cases
Input 1
100
Output 1
Input 2
100 1
200 2
300 3
Output 2
Input 3
1000000000
10000 10000
10000 10000
10000 10000
Output 3
30000
Input 4
15
50 5
60 4
70 6
80 3
30 2
Output 4
240
Input 5
10
100 5
200 10
150 7
50 2
Output 5
200
Input 6
10 5
100 4
51
Output 6
100
Input 7
100 2
200 3
300 4
Output 7
Input 8
100 2
150 2
120 2
Output 8
370
Code
def max_stolen_time_value(n, t, crystals):
total_value = 0
remaining_time = t
total_value += value
remaining_time -= steal_time
else:
continue
return total_value
# Input reading
if __name__ == "__main__":
n = int(input())
t = int(input())
print(max_stolen_time_value(n, t, crystals))
Problem Statement:
There’s a single ticket counter and a line of people waiting. Each person needs a specific amount of
time to be served, which is represented by an array T.
The counter serves people in order, but here's the rule: the counter works in rounds. In each round,
the person at the front gets served for 1 time unit, then goes to the back of the queue if their
remaining time is more than 0.
You are given the time required for each person, and you are asked to calculate how many time units
it will take before the K-th person (0-indexed) in the original queue completes their service.
Input Format:
• First line contains two integers N (number of people) and K (index of target person).
• Second line contains N space-separated integers, where T[i] is the total time required for the
i-th person.
Output Format:
• A single integer — total time taken until the K-th person completes service.
Sample Input 1:
42
1234
Sample Output 1:
Explanation:
Sample Input 2:
50
51111
Sample Output 2:
9
Test Cases
Input 1
10
Output 1
Input 2
32
111
Output 2
Input 3
30
333
Output 3
Input 4
54
11115
Output 4
Input 5
62
331333
Output 5
3
Input 6
52
22222
Output 6
Input 7
52
10 2 3 1 1
Output 7
10
Input 8
43
1115
Output 8
Code
total_value = 0
remaining_time = t
for value, steal_time in crystals:
total_value += value
remaining_time -= steal_time
else:
continue
return total_value
# Input reading
if __name__ == "__main__":
n = int(input())
t = int(input())
print(max_stolen_time_value(n, t, crystals))
Problem Statement:
In the kingdom of Lumora, every year a lantern festival is held where participants light floating
lanterns along a river. Each lantern must be lit and launched at a specific time interval, and each one
brings a certain amount of joy to the crowd.
The Grand Organizer can only allow one lantern to be launched at any given second (due to narrow
river constraints). You're given N lanterns, each with:
• A joy value.
Your task is to select the subset of lanterns to maximize total joy, ensuring no two lanterns are
launched at the same time, and each is launched on or before its deadline.
This is a classic Greedy + Priority Queue problem (variant of Job Scheduling with Deadlines).
Input Format:
Output Format:
Sample Input 1:
2 100
1 50
2 200
1 20
3 300
Sample Output 1:
600
Explanation:
• Choose lanterns with highest joy but that can meet their deadline:
Sample Input 2:
1 40
2 50
2 30
1 70
Sample Output 2:
120
Test Cases
Input 1
1 9999
Output 1
9999
Input 2
1 10
1 20
15
1 100
Output 2
100
Input 3
1 100
2 200
3 300
Output 3
600
Input 4
15
2 20
2 30
2 25
3 50
3 90
Output 4
170
Input 5
1 10
2 10
3 10
4 10
Output 5
40
Input 6
5 100
6 200
7 300
Output 6
600
Input 7
2 10
2 20
2 30
2 40
2 50
Output 7
90
Input 8
1 10000
1 9000
1 8000
1 7000
1 6000
Output 8
10000
Code
import heapq
lanterns.sort(key=lambda x: x[0])
min_heap = []
heapq.heappush(min_heap, joy)
# If we have more lanterns than we can schedule by this deadline, remove the least joyful one
heapq.heappop(min_heap)
return sum(min_heap)
# Input Reading
if __name__ == "__main__":
n = int(input())
print(max_total_joy(n, lanterns))
Problem Statement:
A wealthy merchant is heading to the annual Golden Dunes Market, carrying items of different values
and weights. His caravan can only carry a maximum weight W due to desert travel constraints.
He wants to maximize his profit by selecting the subset of items that can be carried without
exceeding the total weight limit.
He can take fractions of an item if needed — i.e., this is the Fractional Knapsack Problem, solved
greedily by value per unit weight.
Input Format:
o N: number of items
Output Format:
• A single floating-point number — the maximum total value the merchant can carry.
Sample Input 1:
3 50
60 10
100 20
120 30
Sample Output 1:
240.00
Explanation:
Sort by value/weight:
• 60/10 = 6.0
• 100/20 = 5.0
• 120/30 = 4.0
Pick:
• 60 (10)
• 100 (20)
Sample Input 2:
11
100 2
Sample Output 2:
50.00
Test Cases
Input 1
2 30
100 10
120 30
Output 1
220.00
Input 2
3 60
60 10
100 20
120 30
Output 2
280.00
Input 3
3 10
60 10
100 20
120 30
Output 3
60.00
Input 4
25
100 10
120 30
Output 4
50.00
Input 5
4 10
10 1
20 2
30 3
40 4
Output 5
100.00
Input 6
3 50
500 50
400 40
300 30
Output 6
500.00
Input 7
12
100 4
Output 7
50.00
Input 8
5 100
10 10
20 20
30 30
40 40
50 50
Output 8
100.00
Code
total_value = 0.0
if w == 0:
break
if weight <= w:
total_value += value
w -= weight
else:
w=0
return round(total_value, 2)
# Driver code
if __name__ == "__main__":
n, w = map(int, input().split())
print(f"{max_value(n, w, items):.2f}")
Problem Statement:
A music event organizer wants to schedule bands for a music marathon. Each band has a
performance start time, end time, and a popularity score (which is equal to the number of tickets
they help sell).
Due to logistical constraints, no two bands can perform at overlapping times. The goal is to select a
subset of non-overlapping bands to maximize total popularity.
Input Format:
Output Format:
Sample Input 1:
1 3 50
2 5 60
4 6 70
6 7 30
Sample Output 1:
150
Explanation:
Total = 50 + 70 + 30 = 150
Sample Input 2:
1 3 50
2 5 60
4 6 70
6 7 30
Sample Output 2:
150
Test Cases
Input 1
1 2 20
3 4 40
5 6 60
Output 1
120
Input 2
1 5 10
2 6 30
3 7 20
Output 2
30
Input 3
1 3 50
3 5 50
5 7 50
2 8 200
Output 3
200
Input 4
1 10 100
2 3 20
4 5 30
Output 4
100
Input 5
1 3 20
3 6 30
6 9 40
9 12 50
12 15 60
Output 5
200
Input 6
1 5 100
10 15 150
20 25 200
30 35 250
Output 6
700
Input 7
1 10 100
1 2 30
2 3 30
3 4 30
4 5 30
Output 7
120
Input 8
1 3 50
3 5 60
5 7 70
7 9 80
9 11 90
11 13 100
Output 8
450
Code
import bisect
def max_popularity(bands):
dp = [0] * (len(bands) + 1)
return dp[-1]
# Driver
if __name__ == "__main__":
n = int(input())
print(max_popularity(bands))
Problem Statement:
You are given N meetings, each with a start time and end time. All meetings must be scheduled in
conference rooms, and no two overlapping meetings can be in the same room.
Your task is to find the minimum number of rooms required to accommodate all meetings without
overlap.
Input Format:
Sample Input 1:
0 30
5 10
15 20
25 35
Sample Output 1:
Sample Input 2:
12
34
56
Sample Output 2:
Test Cases
Input 1
1 10
1 10
1 10
1 10
Output 1
Input 2
5
14
25
36
67
78
Output 2
Input 3
12
23
34
45
Output 3
Input 4
1 10
2 10
3 10
Output 4
Input 5
1 10
23
34
45
56
Output 5
Input 6
15
26
57
68
79
8 10
Output 6
Input 7
15
25
35
45
Output 7
Input 8
10 20
30 40
50 60
15 25
35 45
55 65
Output 8
Code
def min_rooms(meetings):
start_ptr = end_ptr = 0
current_rooms = max_rooms = 0
current_rooms += 1
start_ptr += 1
else:
current_rooms -= 1
end_ptr += 1
return max_rooms
# Driver
if __name__ == "__main__":
n = int(input())
print(min_rooms(meetings))
20. The Coupon Collector
Problem Statement:
You are at a store that offers coupons on N items. For each item, you are given:
But… you only have K coupons, and each coupon can be applied to only one item.
Your task is to minimize the total cost of buying all items by using at most K coupons, where each
coupon gives the full discount on one item.
Input Format:
Output Format:
Sample Input 1:
52
100 20
200 50
150 30
120 60
80 10
Sample Output 1:
540
Explanation:
Sample Input 2:
30
100 50
200 100
150 75
Sample Output 2:
450
Test Cases
Input 1
33
100 10
100 20
100 30
Output 1
240
Input 2
25
300 100
400 150
Output 2
450
Input 3
42
100 0
200 0
300 0
400 0
Output 3
1000
Input 4
32
100 100
200 200
300 300
Output 4
100
Input 5
10
999 888
Output 5
999
Input 6
128
Output 6
Input 7
63
100 5
100 10
100 15
100 20
100 25
100 30
Output 7
525
Input 8
63
100 5
100 10
100 15
100 20
100 25
100 20
Output 8
535
Code
total_discount = sum(discounts[:k])
# Driver
if __name__ == "__main__":
n, k = map(int, input().split())
print(min_total_cost(n, k, items))
Problem Statement:
You are a competitive programmer participating in a contest with N problems.
• penalty: the penalty incurred if you miss the deadline (if not done at all or submitted late).
Each problem takes exactly 1 unit of time to solve, and you can only solve one problem per unit time.
Your goal is to maximize the total penalty avoided, i.e., pick problems in such a way that you solve
the highest-penalty problems within their deadlines.
Input Format:
• Next N lines: Two integers deadline and penalty for each problem
Output Format:
Sample Input 1:
2 100
1 19
2 27
1 25
3 15
Sample Output 1:
142
Sample Input 2:
1 50
1 40
1 30
1 20
Sample Output 2:
50
Test Cases
Input 1
1 10
2 20
3 30
Output 1
60
Input 2
1 10
1 20
1 30
1 40
Output 2
40
Input 3
15
2 50
3 15
2 20
3 25
Output 3
95
Input 4
6
2 10
2 20
2 30
2 40
2 50
2 60
Output 4
110
Input 5
10 100
9 90
8 80
Output 5
270
Input 6
1 100
2 10
1 30
3 20
2 90
3 80
Output 6
270
Input 7
4
1 50
2 50
3 50
2 50
Output 7
150
Input 8
10000 1000000
9000 900000
8000 800000
7000 700000
6000 600000
Output 8
4000000
Code
total = 0
if not slots[t]:
slots[t] = True
total += penalty
break
return total
# Driver
if __name__ == "__main__":
n = int(input())
print(max_penalty_avoided(n, tasks))
Problem Statement:
You are given N events, each with a start time and an end time. Your task is to determine the
minimum number of rooms required to schedule all events without any overlap in a single room.
Each room can hold only one event at a time. Events are considered overlapping if one starts before
another ends (i.e., inclusive).
Input Format:
• Next N lines: Two integers start and end for each event (inclusive)
Output Format:
Sample Input 1:
0 30
5 10
15 20
35 45
25 40
Sample Output 1:
2
Sample Input 2:
05
6 10
11 15
16 20
Sample Output 2:
Test Cases
Input 1
1 10
29
38
47
Output 1
Input 2
15
26
59
7 10
10 13
12 15
Output 2
Input 3
5
1 100
23
45
67
89
Output 3
Input 4
01
Output 4
Input 5
01
23
45
67
Output 5
Input 6
11
11
11
Output 6
3
Input 7
12
23
34
Output 7
Input 8
0 10
10 20
20 30
5 15
15 25
25 35
30 40
35 45
Output 8
Code
import heapq
def min_rooms(events):
min_heap = []
heapq.heappush(min_heap, end)
return len(min_heap)
# Driver
if __name__ == "__main__":
n = int(input())
print(min_rooms(events))
Problem Statement:
You are given N tasks. Each task takes a certain amount of time to complete and has a deadline. You
can execute the tasks one after another, starting from time 0. Your goal is to complete the maximum
number of tasks such that each task is finished on or before its deadline.
You can only work on one task at a time, and you must choose tasks wisely (greedy!) so you can
finish as many as possible.
Input Format:
• Next N lines: Two integers duration and deadline for each task
Output Format:
• A single integer – maximum number of tasks that can be completed on or before their
deadlines
Sample Input 1:
39
28
19
2 15
5 12
Sample Output 1:
Sample Input 2:
25
13
26
Sample Output 2:
Test Cases
Input 1
24
35
46
10 7
Output 1
Input 2
11
23
36
4 10
Output 2
4
Input 3
15
16
17
18
19
Output 3
Input 4
32
43
54
Output 4
Input 5
6 12
13
24
15
36
Output 5
Input 6
3 10
2 10
1 10
4 10
Output 6
Input 7
5 10
38
25
13
6 12
4 11
Output 7
Input 8
10 100
20 100
30 100
40 100
15 100
5 100
25 100
Output 8
Code
import heapq
def max_tasks(tasks):
total_time = 0
durations = []
total_time += duration
heapq.heappush(durations, -duration)
return len(durations)
# Driver
if __name__ == "__main__":
n = int(input())
print(max_tasks(tasks))
Problem Statement:
You're managing a charging station with K charging ports. There are N electric cars that want to
charge. Each car arrives at a specific time and needs a specific duration to fully charge.
Your goal is to maximize the number of cars that can be charged, assuming:
Use a greedy algorithm to schedule cars so that the maximum number can finish charging.
Input Format:
• Next N lines: Two integers arrival_time and duration for each car
Output Format:
Sample Input 1:
52
14
23
32
10 1
52
Sample Output 1:
Sample Input 2:
31
12
32
52
Sample Output 2:
Test Cases
Input 1
42
12
32
52
72
Output 1
Input 2
41
15
25
35
45
Output 2
Input 3
33
15
15
15
Output 3
Input 4
52
14
23
32
10 1
52
Output 4
Input 5
42
12
22
10 1
11 1
Output 5
Input 6
62
13
22
32
42
52
62
Output 6
Input 7
10 2
12
12
12
12
12
32
32
32
52
52
Output 7
6
Input 8
62
11
21
31
41
51
61
Output 8
Code
import heapq
count = 0
heapq.heappop(ports)
if len(ports) < k:
count += 1
return count
# Driver
if __name__ == "__main__":
n, k = map(int, input().split())
print(max_charged_cars(cars, k))
Problem Statement:
You are given an amount N and a list of M coin denominations. Your task is to find the minimum
number of coins needed to make up that amount using the available denominations. You can use
each coin type an unlimited number of times.
Input Format:
Output Format:
Sample Input 1:
49 6
1 2 5 10 20 50
Sample Output 1:
Explanation:
• 20 + 20 = 40
• 5 = 45
• 2 = 47
• 1 + 1 = 49
• Total: 5 coins
Sample Input 2:
49 6
1 2 5 10 20 50
Sample Output 2:
Test Cases
Input 1
100 4
1 5 10 100
Output 1
Input 2
37 5
1 5 10 20 25
Output 2
Input 3
71
Output 3
Input 4
18 3
2 5 10
Output 4
3
Input 5
18 4
1 2 5 10
Output 5
Input 6
999 6
1 2 5 10 20 100
Output 6
17
Input 7
15 6
1 1 5 5 10 10
Output 7
Input 8
72
24
Output 8
Code
coins.sort(reverse=True)
count = 0
n -= coin
count += 1
return count
# Driver
if __name__ == "__main__":
n, m = map(int, input().split())
print(min_coins_to_pay(n, coins))
Problem Statement:
You are given N tasks. Each task has a deadline and a reward. You can only do one task per day, and
each task takes exactly one day. If a task is not completed on or before its deadline, you miss the
reward.
Your goal is to maximize the total reward by selecting and scheduling tasks greedily.
Input Format:
• Next N lines: Two integers D and R per line (deadline and reward)
Output Format:
Sample Input 1:
2 50
1 10
2 20
1 30
3 40
Sample Output 1:
120
Sample Input 2:
1 10
1 20
1 30
1 40
Sample Output 2:
40
Test Cases
Input 1
1 10
2 20
3 30
4 40
Output 1
100
Input 2
2 50
2 60
2 70
2 40
2 30
2 20
Output 2
130
Input 3
3
3 15
2 10
1 20
Output 3
45
Input 4
1 10
2 10
3 10
2 10
1 10
Output 4
30
Input 5
1 100
2 10
2 10
3 10
3 10
Output 5
120
Input 6
1 1000
Output 6
1000
Input 7
10 100
11 200
12 300
13 400
Output 7
1000
Input 8
1 10
1 20
1 30
1 40
1 50
1 60
Output 8
60
Code
if parent[x] != x:
return parent[x]
total_reward = 0
for d, r in tasks:
available_day = find(parent, d)
if available_day > 0:
total_reward += r
return total_reward
# Driver
if __name__ == "__main__":
n = int(input())
print(max_total_reward(tasks))
Hard
Problem Statement:
The Infinite Forest is a mystical place represented as a 2D grid. You start at the top-left cell (0, 0) and
want to reach the bottom-right cell (N-1, M-1). Each cell contains a magical cost, which you must pay
to enter that cell.
There are some rare teleport tiles in the grid (identified by a value of -1). From a teleport tile, you can
jump to any other teleport tile for free, without paying the cost of the destination teleport tile (but
you must still have passed into the teleport tile you're jumping from).
Your goal is to find the minimum magical cost to travel from the start to the destination, considering
both normal and teleportation moves.
Input Format:
• The first line contains two integers N and M — the dimensions of the forest.
Output Format:
Print a single integer — the minimum cost to reach (N-1, M-1) from (0, 0).
Sample Input 1:
44
1 3 -1 4
2859
4 -1 3 1
6725
Sample Output 1:
13
Sample Input 2:
33
1 -1 3
2 4 -1
111
Sample Output 2:
Test Cases
Input 1
33
123
456
789
Output 1
21
Input 2
33
1 -1 3
2 100 -1
111
Output 2
Input 3
44
1 2 -1 9
8999
-1 9 9 9
9991
Output 3
31
Input 4
33
-1 3 1
2 -1 2
341
Output 4
3
Input 5
33
123
456
7 8 -1
Output 5
12
Input 6
33
123
4 -1 6
789
Output 6
18
Input 7
44
1 -1 -1 1
1 100 100 1
1 100 100 1
1111
Output 7
Input 8
44
1 99 99 99
-1 99 99 99
99 99 99 -1
99 99 99 1
Output 8
Code
import sys
import heapq
INF = float('inf')
teleports = []
for i in range(n):
for j in range(m):
if grid[i][j] == -1:
teleports.append((i, j))
visited_teleport = False
while heap:
cost, x, y = heapq.heappop(heap)
continue
# Normal right/down moves
nx, ny = x + dx, y + dy
dp[tx][ty] = cost
return dp[n-1][m-1]
# Reading input
n, m = map(int, input().split())
print(min_magic_cost(grid, n, m))
Problem Statement:
You are given an array of integers A of length N. A subsequence S of A is called a "Jumpy Alternating
Subsequence" if:
3. The absolute difference between any two consecutive elements must be at least K.
Input Format:
• First line: Two integers N and K — the length of the array and the minimum absolute jump
size.
Output Format:
Sample Input 1:
62
174925
Sample Output 1:
Explanation:
One such longest sequence is [1, 7, 4, 9, 2, 5] with diffs [+6, -3, +5, -7, +3].
Sample Input 2:
53
12345
Sample Output 2:
Test Cases
Input 1
62
174925
Output 1
Input 2
51
33333
Output 2
Input 3
5 10
12345
Output 3
Input 4
70
1 17 5 10 13 15 10
Output 4
Input 5
73
10 20 5 25 1 30 0
Output 5
Input 6
42
1114
Output 6
Input 7
54
10 5 1 -3 -10
Output 7
Input 8
10 1
1324354657
Output 8
10
Code
n = len(arr)
for j in range(i):
if diff > 0:
# Read input
n, k = map(int, input().split())
print(longest_jumpy_alternating_subsequence(arr, k))
Problem Statement:
You're given an array of integers arr of length n. You need to select a subsequence such that:
1. No two adjacent elements in the original array can be picked (i.e., if you pick arr[i], you
cannot pick arr[i+1]).
Write a program to compute the minimum possible sum under these rules.
Input Format:
Output Format:
• A single integer: Minimum number of button presses required to type the message.
Sample Input 1:
3 2 5 10 7
Sample Output 1:
Sample Input 2:
Sample Output 2:
Test Cases
Input 1
10 2
Output 1
Input 2
-5 -10 -3 -1 -6 -9
Output 2
-20
Input 3
Output 3
1
Input 4
45154
Output 4
Input 5
777777
Output 5
Input 6
5 100
6 200
7 300
Output 6
600
Input 7
8 7 -100 6 9
Output 7
-92
Input 8
10 9 8 7 6 5
Output 8
Code
def min_non_adjacent_sum(arr):
n = len(arr)
if n == 1:
return arr[0]
dp = [0] * n
dp[0] = arr[0]
return dp[-1]
# Input
n = int(input())
print(min_non_adjacent_sum(arr))
Problem Statement:
You are given n pairs of integers. Each pair represents a directed link (a, b) such that a < b.
You can form a chain by choosing some pairs such that for each consecutive pair (a, b) and (c, d) in
the chain, b < c.
Your task is to select the maximum number of pairs you can chain together following this rule.
Input Format:
• First line: An integer n — number of pairs.
Output Format:
Sample Input 1:
5 24
15 25
27 40
50 60
Sample Output 1:
Sample Input 2:
12
23
34
45
56
Sample Output 2:
Test Cases
Input 1
12
23
34
45
56
Output 1
Input 2
1 10
23
34
Output 2
Input 3
01
Output 3
Input 4
15
26
Output 4
Input 5
12
23
45
67
89
10 11
Output 5
Input 6
5 10
14
7 11
13 20
68
21 25
Output 6
Input 7
Output 7
Input 8
-5 -3
-1 1
23
46
68
9 12
13 15
Output 8
6
Code
def max_chain_length(pairs):
pairs.sort(key=lambda x: x[1])
count = 0
current_end = float('-inf')
for a, b in pairs:
if a > current_end:
count += 1
current_end = b
return count
# Input
n = int(input())
print(max_chain_length(pairs))
Problem Statement:
Your task is to split the array into k non-empty continuous subarrays, such that the maximum sum
among these k subarrays is minimized.
Input Format:
• First line: Two integers n and k
Output Format:
A single integer — the minimum possible value of the largest subarray sum when the array is split
into k parts.
Sample Input 1:
52
7 2 5 10 8
Sample Output 1:
18
Sample Input 2:
42
1234
Sample Output 2:
Test Cases
Input 1
11
100
Output 1
100
Input 2
63
144132
Output 2
5
Input 3
64
1 4 4 1 3 22 8 200
Output 3
Input 4
10 5
1 1 1 1 1 1 1 1 1 10
Output 4
10
Input 5
1 3 20
3 6 30
6 9 40
9 12 50
12 15 60
Output 5
200
Input 6
73
2312431
Output 6
Input 7
55
12345
Output 7
Input 8
61
123456
Output 8
21
Code
count = 1
current_sum = 0
count += 1
current_sum = num
else:
current_sum += num
low = max(arr)
high = sum(arr)
result = high
if can_split(arr, k, mid):
result = mid
high = mid - 1
else:
low = mid + 1
return result
# Input
n, k = map(int, input().split())
print(split_array_min_largest_sum(arr, k))
Problem Statement:
You are given a string s. Your task is to partition the string such that every substring of the partition is
a palindrome.
Return the minimum number of cuts needed to make all parts of the string palindromes.
Input Format:
Output Format:
Sample Input 1:
aab
Sample Output 1:
Sample Input 2:
Sample Output 2:
0
Test Cases
Input 1
abc
Output 1
Input 2
abba
Output 2
Input 3
racecar
Output 3
Input 4
noonabbad
Output 4
Input 5
aaaaaa
Output 5
Input 6
abacdc
Output 6
1
Input 7
Banana
Output 7
Input 8
Civicracecar
Output 8
Code
def min_cut_palindrome(s):
n = len(s)
# Precompute palindromes
for i in range(n):
is_palindrome[i][i] = True
for i in range(n-1):
j = i + length - 1
dp = [0] * n
for i in range(n):
if is_palindrome[0][i]:
dp[i] = 0
else:
dp[i] = float('inf')
for j in range(i):
if is_palindrome[j+1][i]:
return dp[-1]
# Input
s = input().strip()
print(min_cut_palindrome(s))
Problem Statement:
Given an array of integers, you must find the length of the longest subsequence where the
differences between consecutive elements strictly alternate between positive and negative.
A subsequence is not necessarily contiguous. The first difference can be either positive or negative.
Input Format:
Output Format:
Sample Input 1:
174925
Sample Output 1:
6
Sample Input 2:
14725
Sample Output 2:
Test Cases
Input 1
10
Output 1
Input 2
111
Output 2
Input 3
1234
Output 3
Input 4
4321
Output 4
2
Input 5
70 55 13 2 99 2 80
Output 5
Input 6
33333333
Output 6
Input 7
10
10 22 9 33 49 50 31 60 4 70
Output 7
Input 8
13243
Output 8
Code
def longest_zigzag_subsequence(arr):
n = len(arr)
if n == 0:
return 0
up = [1] * n
down = [1] * n
for j in range(i):
# Input
n = int(input())
print(longest_zigzag_subsequence(arr))
Problem Statement:
You're given n intervals, each with a start time, end time, and a value. Your goal is to select a subset
of non-overlapping intervals such that the sum of their values is maximized.
Input Format:
• Next n lines: Each line contains three integers: start end value
Output Format:
Sample Input 1:
4
1 3 50
3 5 20
6 19 100
2 100 200
Sample Output 1:
200
Sample Input 2:
1 2 10
2 3 20
3 4 30
Sample Output 2:
60
Test Cases
Input 1
1 4 10
2 5 20
3 6 30
Output 1
30
Input 2
1 10 100
2 3 10
3 4 20
4 5 30
5 6 40
Output 2
100
Input 3
1 10 100
11 20 200
Output 3
300
Input 4
1 5 20
6 10 30
5 6 10
Output 4
60
Input 5
1 2 100
2 3 100
3 4 100
Output 5
300
Input 6
1 1000000000 5000
Output 6
5000
Input 7
1 3 10
2 4 20
3 5 30
4 6 40
Output 7
60
Input 8
121
232
343
454
565
Output 8
15
Code
import bisect
def max_value_non_overlapping(intervals):
intervals.sort(key=lambda x: x[1])
n = len(intervals)
dp = [0] * (n + 1)
for i in range(1, n + 1):
return dp[n]
# Input
n = int(input())
print(max_value_non_overlapping(intervals))
Problem Statement:
You are given two integers L and R, and a value k. Count how many numbers between L and R
(inclusive) are beautiful.
Input Format:
Output Format:
A single integer — the count of beautiful numbers in the range [L, R].
Sample Input 1:
1 100 10
Sample Output 1:
9
Sample Input 2:
1 20 5
Sample Output 2:
Test Cases
Input 1
10 99 9
Output 1
10
Input 2
1 1000 10
Output 2
99
Input 3
100 200 15
Output 3
Input 4
123456 654321 7
Output 4
75845
Input 5
1 1000000 1
Output 5
1000000
Input 6
1 1000000 99
Output 6
Input 7
111
Output 7
Input 8
9999999999999999 10000000000000000 9
Output 8
Code
@lru_cache(None)
if pos == len(digits):
total = 0
total += dp(
pos + 1,
(sum_mod_k + d) % k,
return total
# Input
L, R, k = map(int, input().split())
print(solve(L, R, k))
Problem Statement:
You're given an array of n integers and an integer k. You need to partition the array into k subsets of
equal size. Each subset must contain unique elements only (no duplicates). The incompatibility of a
subset is the difference between its maximum and minimum elements.
Your goal is to minimize the sum of incompatibilities across all subsets. If it's not possible to partition
the array as required, return -1.
Input Format:
Output Format:
Sample Input 1:
84
12143356
Sample Output 1:
Sample Input 2:
63
123456
Sample Output 2:
Test Cases
Input 1
52
12345
Output 1
-1
Input 2
84
12143356
Output 2
Input 3
62
111222
Output 3
-1
Input 4
42
5577
Output 4
Input 5
72
1234567
Output 5
-1
Input 6
63
316245
Output 6
Input 7
42
8888
Output 7
-1
Input 8
84
10 20 30 40 50 60 70 80
Output 8
40
Code
import sys
def min_incompatibility(nums, k):
n = len(nums)
size = n // k
if n % k != 0:
return -1
count = defaultdict(int)
count[num] += 1
return -1
all_masks = []
mask_cost = {}
seen = set()
subset = []
for i in combo:
if nums[i] in seen:
break
seen.add(nums[i])
subset.append(nums[i])
else:
mask = 0
for i in combo:
mask |= 1 << i
all_masks.append(mask)
dp = [sys.maxsize] * (1 << n)
dp[0] = 0
if bin(mask).count('1') % size != 0:
continue
# Input Reading
if __name__ == "__main__":
n, k = map(int, input().split())
print(min_incompatibility(nums, k))
Problem Statement:
You are given a string s of lowercase English letters. You want to partition s into k non-empty, non-
overlapping contiguous substrings such that each substring is a palindrome. You are allowed to
change characters in the string. Changing one character costs 1 unit.
Your goal is to partition the string into exactly k palindromic substrings with the minimum total cost
of character changes required.
Input Format:
Output Format:
• A single integer, the minimum cost to partition the string into exactly k palindromic
substrings.
Sample Input 1:
abc
Sample Output 1:
Sample Input 2:
aabbc
Sample Output 2:
Test Cases
Input 1
Output 1
Input 2
abc
1
Output 2
Input 3
aaaa
Output 3
Input 4
aaaaaa
Output 4
Input 5
abcdef
Output 5
Input 6
racecar
Output 6
Input 7
abcdef
Output 7
2
Input 8
abcdcba
Output 8
Code
cost = 0
while i < j:
if s[i] != s[j]:
cost += 1
i += 1
j -= 1
return cost
n = len(s)
for i in range(n):
cost[i][j] = min_change_to_palindrome(s, i, j)
dp[0][0] = 0
return dp[n][k]
# Input Reading
if __name__ == "__main__":
s = input().strip()
k = int(input())
print(min_cost_partition(s, k))
Problem Statement:
Given a string s of lowercase English letters, you are allowed to select substrings such that:
• Each selected substring has all the same characters (e.g., "aaa" is valid, "aab" is not).
• For each selected substring, you gain a score equal to the square of its length.
Your task is to select a subset of such substrings (non-overlapping and non-adjacent) to maximize the
total score.
Input Format:
Output Format:
Sample Input 1:
aaabbaaa
Sample Output 1:
18
Sample Input 2:
ababa
Sample Output 2:
Test Cases
Input 1
aaaaa
Output 1
25
Input 2
aabbaabb
Output 2
Input 3
aabbaa
Output 3
Input 4
abcde
Output 4
Input 5
aaabbbcccaaaddd
Output 5
27
Input 6
aabaaabaaa
Output 6
22
Input 7
Output 7
Input 8
aaabbaaccdddeeffggghh
Output 8
31
Code
def max_non_adjacent_block_score(s):
n = len(s)
blocks = []
i=0
while i < n:
j=i
j += 1
blocks.append((s[i], j - i))
i=j
m = len(blocks)
dp = [0] * (m + 1)
else:
return dp[m]
# Input Reading
if __name__ == "__main__":
s = input().strip()
print(max_non_adjacent_block_score(s))
Problem Statement:
You are given a binary string s (consisting of only '0' and '1') and an integer k.
You are allowed to flip at most k characters in the string (i.e., change '0' to '1' or '1' to '0').
Your task is to determine the length of the longest balanced substring you can obtain after at most k
flips, where a balanced substring is defined as a substring with an equal number of 0s and 1s.
Input Format:
Output Format:
Sample Input 1:
110001
Sample Output 1:
Sample Input 2:
1111
Sample Output 2:
Test Cases
Input 1
1111
Output 1
Input 2
000111
Output 2
Input 3
00000
Output 3
Input 4
101010
Output 4
Input 5
101100110101
Output 5
10
Input 6
1 1000
Output 6
1000
Input 7
1000000001
Output 7
Input 8
111000
Output 8
Code
n = len(s)
max_len = 0
count = {0: 0, 1: 0}
left = 0
for right in range(n):
count[int(s[right])] += 1
count[int(s[left])] -= 1
left += 1
return max_len
# Input
if __name__ == "__main__":
s = input().strip()
k = int(input())
print(longest_balanced_after_k_flips(s, k))
Problem Statement:
You are given an array of integers arr of size n. You can jump from index i to any index j such that:
• j>i
You need to find the minimum number of jumps required to reach the end of the array starting from
index 0 (i.e., arr[0] to arr[n-1]), such that at each step the next value is strictly greater than the
current.
Input Format:
Output Format:
Sample Input 1:
132468
Sample Output 1:
Sample Input 2:
54321
Sample Output 2:
-1
Test Cases
Input 1
1234
Output 1
Input 2
10
Output 2
Input 3
7
1 100 1 101 2 102 103
Output 3
Input 4
10 20 10 30 10 40 10 50
Output 4
Input 5
11112
Output 5
Input 6
10
5612345678
Output 6
Input 7
13579
Output 7
Input 8
121212
Output 8
Code
def min_jumps_strictly_increasing(arr):
n = len(arr)
if n == 1:
return 0
graph = defaultdict(list)
for i in range(n):
graph[i].append(j)
# BFS
visited = [False] * n
queue = deque()
visited[0] = True
while queue:
if not visited[neighbor]:
if neighbor == n - 1:
return jumps + 1
visited[neighbor] = True
return -1
# Driver Code
if __name__ == "__main__":
n = int(input())
print(min_jumps_strictly_increasing(arr))
Q1.
Problem Statement
Determine whether a given undirected graph contains the Hamiltonian cycle or not.
A Hamiltonian cycle in an undirected graph is a path that visits each vertex exactly once. A
Hamiltonian cycle is a Hamiltonian path with an edge from the last vertex to the first vertex of the
Hamiltonian path.
Example
Input:
01010
10111
01001
11001
01110
Output:
012430
Explanation:
Starting from vertex 0, all the vertices can be visited exactly once (0 - 1 - 2 - 4 - 3 - 0).
Input Format
The first line of input consists of an integer that represents the number of vertices (V).
The following lines of input consist of the V*V matrix, which represents the adjacency matrix of the
graph.
Output Format
The output prints If a Hamiltonian cycle exists, print the vertices in the cycle in order, starting and
ending at vertex 0.; otherwise, it prints that the "Hamiltonian path does not exist".
3≤V≤5
10111
01001
11001
01110
012430
01010
10111
01001
11000
01100
Q2.
Problem Statement:
Inversion Count: For an array, the inversion count indicates how far (or close) the array is from being
sorted. If the array is already sorted, then the inversion count is 0. If an array is sorted in reverse
order, then the inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Example 1:
Input:
N = 5, arr[] = {2, 4, 1, 3, 5}
Output:
Explanation:
Sequence 2, 4, 1, 3, and 5 has three inversions (2, 1), (4, 1), and (4, 3).
Example 2: Input:
N=5
arr[] = {2, 3, 4, 5, 6}
Output:
Explanation:
Example 3:
Input:
Output:
Explanation:
As all the elements of the array are the same, there is no inversion count.
Input Format
The second line of the input is the list of space-separated integer values.
Output Format
Constraints
24135
23456
10 10 10
Q3.
Problem Statement
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s
such that every character in t (including duplicates) is included in the window. If there is no such
substring, return an empty string.
Examples
Output: BANC
Explanation: The minimum window substring BANC includes 'A', 'B', and 'C' from string t.
Input: s = a, t = a
Output: a
Input: s = a, t = aa
Output:
Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has
one 'a', return an empty string.
Input Format
The first line contains the string s, which is the source string.
The second line contains the string t, which is the target string whose characters must be included in
the window.
Output Format
The output is a single line containing the minimum window substring of s containing all t characters.
If no such window exists, output an empty string.
Constraints
m == s.length
n == t.length
1 ≤ m, n ≤ 105
ADOBECODEBANC ABC
BANC
aaa
a aa
Q4
Problem Statement
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
Input Format
The first line of input consists of an integer value 'n', representing the number of digits in the
permutation.
The second line of input consists of an integer value 'k', representing the position of the permutation
to be found.
Output Format
The output displays the kth permutation of the first n positive integers.
In this scenario, the given test cases will fall under the following constraints:
1 ≤ n ≤ 9 1 ≤ k ≤ n!
Sample Input Sample Output
213
2314
123
Q5.
Problem Statement
Given an array representing the parent-child relationship in a binary tree, find the tree's height
without building it.
The parent-child relationship is defined by (A[i], i) for every index i in the array. The root node's value
will be i if -1 is present at index i in the array.
The depth of a node is the total number of edges from the node to the tree's root node. The root is
the only node whose depth is 0.
The height of a node is the total number of edges on the longest path from the node of a leaf. The
height of a tree would be the height of its root node or equivalently the depth of its deepest node. A
leaf node will have a height of 0.
Example
Parent: [-1, 0, 0, 1, 2, 2, 4, 4]
Index: [0, 1, 2, 3, 4, 5, 6, 7]
-1 is present at index 0, which implies that the binary tree root is node 0.
0 is present at index 1 and 2, which implies that the left and right children of node 0 are 1 and
2.
1 is present at index 3, which implies that the left or the right child of node 1 is 3.
2 is present at index 4 and 5, which implies that the left and right children of node 2 are 4 and
5.
4 is present at index 6 and 7, which implies that the left and right children of node 4 are 6 and 7.
Input Format
The first line contains a single integer N, which represents the number of nodes in the tree. The next
N lines consist of an integer in each line, and the last line of input consists of the ith integer
representing the parent of the ith node.
If the ith node is the root node, then the corresponding value will be -1.
Output Format
The output consists of a single integer, which represents the height of the tree.
Constraints
1 ≤ N ≤ 10
Q6.
Problem Statement
Roshan invested all day in developing test data for DC. He couldn’t make it work, so he had a nervous
breakdown and can’t even see clearly anymore. Every time he winks(blinks) while reading, the letters
in a word get mingled up so that the letters from the second half of the word (the shorter half, if the
length is an odd number) “jump in” between the letters from the first half in the following way:
The final letter “jumps in” the middle of the 1st and the 2nd letter
The second final letter “jumps in” the middle of the 2nd and the 3rd letter
The ith letter from the end “jumps in” the middle of the ith and the (i+1)th letter from the starting
For this case, the word “abcdef” would become “afbecd” after winking.
If Roshan winks again, the same thing happens. After three winks, the word becomes
“adfcbe”.
Roshan has decided to write a program to help him figure out what’s correctly written on the screen.
Unfortunately, after a day’s work, he’s too tired, and he needs your help. You are given N, the
number of winks, and the word Roshan sees on the screen. Write a program to solve the mystery for
Roshan and figure out what was actually the word before he winked N times.
Input Format
The first line of input contains a positive integer N, the number of times Roshan blinked. The second
line of input contains the word W from the screen.
The word will consist only of small letters of the English alphabet.
Output Format
The output displays the original word before Roshan blinked N times.
Refer to the sample output for formatting specifications. Constraints
1 ≤ N ≤ 109
3 ≤ length(W) ≤ 103
Q7.
Problem Statement
You are given two strings order and s. All the characters of order are unique and were sorted in some
custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if
a character x occurs before a character y in order, then x should occur before y in the permuted
string.
Example 1:
Output: "cbad"
Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba",
"cbda" are also valid outputs.
Example 2:
Output: "bcad"
Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The
character "d" in s does not appear in order, so its position is flexible.
Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c",
"a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this
rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain
their order.
Input Format
The first line of input consists of the string order, representing the custom order of characters.
The second line of input consists of the string s, representing the input string.
Output Format
The output prints the sorted string according to the custom order specified by order.
1 ≤ order.length ≤ 26
1 ≤ s.length ≤ 200
order and s consist of lowercase English letters. All the characters of order are unique.
Q8.
Problem Statement:
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example 1:
Input: n=9
nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Example 2:
Output: 1
Example 3:
Input: n=5
nums = [5,4,-1,7,8]
Output: 23
Input Format
The first line consists of an integer n, representing the number of elements in the array nums. The
second line consists of n space-separated integers, representing the elements of the array nums.
Output Format
The output prints an integer, representing the sum of the subarray with the largest sum.
1 ≤ n ≤ 20
Q9.
Problem Statement
Given an array, the task is to find the sum of the maximum sum by alternating subsequences starting
with the first element. Here alternating sequence means first decreasing, then increasing, then
decreasing,... For example, 10, 5, 14, and 3 are alternating sequences.
Example
Input:
4 38538
Output:
28
Explanation:
The alternating subsequence (starting with the first element) that has the maximum sum is
{4, 3, 8, 5, 8}
Input Format
The first line contains an integer n, representing the number of elements in the array.
The second line contains n space-separated integers, representing the elements of the array.
Output Format
The output displays a single integer representing the maximum sum of an alternating subsequence
from the given array.
1 ≤ n ≤ 10
1 ≤ elements ≤ 100
Q10.
Problem Statement
We can rotate digits by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180
degrees, they become 0, 1, 9, 8, 6 respectively. When 2, 3, 4, 5 and 7 are rotated 180 degrees, they
become invalid.
A confusing number is a number that when rotated 180 degrees becomes a different number with
each digit valid. (Note that the rotated number can be greater than the original number)
Given a positive integer N, return the number of confusing numbers between 1 and N inclusive.
Example
Input: 16
Output: 4
Explanation:
6 converts to 9.
9 converts to 6.
16 converts to 91.
Input Format
Output Format
The output prints an integer, representing the number of confusing numbers between 1 and N
inclusive.
Constraints
1 ≤ N ≤ 103
Q11.
Problem Statement
Given an array of string words and a width maxWidth, format the text such that each line has exactly
maxWidth characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each
line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a
line does not divide evenly between words, the empty slots on the left will be assigned more spaces
than the slots on the right.
The last line of text should be left justified, and no extra space should be inserted between words.
Note:
A word is defined as a character sequence consisting of non-space characters only. Each word's
length is guaranteed to be greater than 0 and not exceed maxWidth.
Input Format
The first line of input consists of an integer n, representing the number of words in the sentence.
Output Format
1 ≤ words.length ≤ 300
1 ≤ words[i].length ≤ 20
Problem Statement
Sarah is working on a traffic management system for a city's road network. She needs to find the
shortest cycle in the road network, where each intersection is represented as a vertex and each road
between intersections is a directed edge with a specific travel time (weight). The goal is to identify
the shortest cycle in the road network, where a cycle is defined as a path that starts and ends at the
same intersection, and the length of the cycle is the total travel time of all roads in the cycle.
Can you assist Sarah by writing a program to find the length of the shortest cycle in the city's road
network?
Example1 Input:
012
123
204
315
Output:
Explanation:
After exploring all starting vertices, the code checks for cycles by examining the distances. If an edge
leads back to the starting vertex, it means there is a cycle. In this case, edge 1 (vertex 1) leads back to
the starting vertex 0. The code calculates the length of the cycle by adding the distances of the
vertices along the cycle: 2 (0 -> 1) + 3 (1 -> 2) + 4 (2 -> 0) = 9.
Example2 Input:
3
012
123
Output:
Explanation:
After exploring all starting vertices, the code checks for cycles by examining the distances. If an edge
leads back to the starting vertex, it means there is a cycle. However, in this case, there are no edges
that lead back to the starting vertex. Hence, there is no cycle in the graph.
Input Format
The first line contains an integer v, representing the number of intersections (vertices) in the city's
road network.
The second line contains an integer e, representing the number of roads (edges) in the city. The next
e lines each contain three integers: source, destination, and weight, representing a directed road
from intersection source to intersection destination with a travel time (weight). Output Format
If a cycle exists, the output prints "Length of the shortest cycle: X", where X is the length of the
shortest cycle.
If no cycle exists, then the output prints "No cycle found in the graph."
In this scenario, the given test cases will fall under the following constraints:
1≤v≤5
1 ≤ edges ≤ 7
0 ≤ S, D < V
1≤W≤5
Q13.
Problem Statement
Mr.Butler is managing his class of n students. He placed all his students in a line and gave the kth
student from the left a card with the letter ak written on it. He would now like to rearrange the
students so that the kth student from the left has a card with the letter bk written on it.
To do this, he will choose some consecutive groups of students, and reverse their order. Students will
hold on to their original cards during this process.
He’s now wondering, what is the number of valid ways to do this? (It may be impossible, in
With sequences abba and aabb, Mr.Butler can choose group a(bba). With sequences caxcab and
cacxab, Mr.Butler can choose ca(xc)ab or c(axca)b. With sequences a and z, there are no solutions.
Input Format
It is guaranteed that A and B have the same positive length, and A and B are not identical.
Output Format
The output displays the number of ways Mr.Butler can reverse some consecutive groups of A to form
the line specified by string B.
Refer to the sample input and output for formatting specifications. Constraints
Q14.
Problem Statement
Given an input stream of N integers. The task is to insert these numbers into a new stream and find
the median of the stream formed by each insertion of X to the new stream.
Example 1 Input
N=4
X[] = 5,15,1,3
Output
10
Explanation:
N=3
X[] = 5,10,15
Output
7.5
10
Explanation:
Input Format
The first line contains an integer n, the number of integers in the stream.
The second line contains n space-separated integers representing the elements of the stream.
Output Format
The output prints the median after each insertion of an integer into the stream. Print each median on
a new line.
1 ≤ N ≤ 15
1 ≤ Elements ≤ 100
Problem Statement
Given a string s and a dictionary of string wordDict of size n, add spaces in s to construct a sentence
where each word is a valid dictionary word. Return all such possible sentences in any order.
Note: The same word in the dictionary may be reused multiple times in the segmentation. & All the
strings of wordDict are unique.
Examples Input:
s = "catsanddog" n = 5
wordDict = ["cat","cats","and","sand","dog"]
Output:
Input:
s = "pineapplepenapple" n = 5
wordDict = ["apple","pen","applepen","pine","pineapple"]
Output:
Input:
s = "catsandog" n = 5
wordDict = ["cats","dog","sand","and","cat"]
Output:
[]
Input Format
The first line of input is a string 's' consisting of lowercase English letters. The second line of input is
an integer 'n' represents the size of the dictionary. The next n lines consists of strings denoting the
words in the dictionary.
Output Format
The output displays a list of strings, where each string is a space-separated sequence of dictionary
words that form the input string s.
Refer to the sample input and output for formatting specifications. Constraints
1 <= n <= 10
Q16.
Problem Statement
Given an m x n integers matrix, return the length of the longest increasing path in matrix.
From each cell, you can either move in four directions: left, right, up, or down. You may not move
diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
The first line of input consists of an integer r, representing the number of rows.
The second line of input consists of an integer c, representing the number of columns. The next r
lines contain c integers each, representing the elements of the matrix.
Output Format
The output prints a single integer, representing the length of the longest increasing path in the matrix
1≤r≤4
1≤c≤4
Q17.
Problem Statement
Tom is a software developer working on a project where he has to check if a doubly linked list is a
palindrome. He needs to write a program to solve this problem. Write a program to help Tom check
if a given doubly linked list is a palindrome or not.
Input Format
The first line consists of an integer N, representing the number of elements in the linked list. The
second line consists of N space-separated integers representing the linked list elements. Output
Format
The first line of output displays the elements of the doubly linked list in forward order, separated by
spaces.
The second line of output displays the elements of the doubly linked list in reverse order, separated
by spaces.
"The doubly linked list is a palindrome" if the list reads the same forward and backward.
"The doubly linked list is not a palindrome" if the list does not match when reversed.
In this scenario, the test cases fall under the following constraints:
2 ≤ N ≤ 20
1 2 3 2 1
1 2 3 2 1
1 2 3 2 1
Sample Input Sample Output
1 2 3 4 5
1 2 3 4 5
5 4 3 2 1
-1 -2 -3 -3 -2 -1
-1 -2 -3 -3 -2 -1
-1 -2 -3 -3 -2 -1
Q18.
Problem Statement
Meet Alex, a computer science student who loves solving programming challenges.
Today, Alex is tasked with creating a program to simulate a stack data structure using linked lists.
The objective is to provide a menu-driven interface for performing essential stack operations. Push
elements onto the stack
Pop elements from the stack Display the current stack contents
Additionally, Alex needs to ensure that the program handles stack underflow conditions. Help him to
accomplish the task.
Input Format
The input consists of integers corresponding to the operation that needs to be performed: Choice 1:
If the choice is 1, the following integer input represents the element to be pushed onto the stack.
Choice 2: Pop the integer from the stack. Choice 3: Display the elements in the stack. Choice 4: Exit
the program.
Output Format
The output displays messages according to the choice and the status of the stack:
If the choice is 1, push the given integer to the stack and display the following: "[value] is pushed
onto the stack"
If the choice is 2, pop the integer from the stack and display the following: "[value] is popped from
the stack"
If the choice is 2, and if the stack is empty without any elements, print "Stack Underflow" If the
choice is 3, print the elements in the stack in the format: "Elements in the stack: ", followed by the
space-separated integer values.
If the choice is 3, and there are no elements in the stack, print "Stack is empty"
If the choice is 4, exit the program and display the following: "Exiting the program" If any other
choice is entered, print "Invalid choice"
Choice: 1, 2, 3, or 4
Problem Statement:
You need to build a road in a rugged terrain. You know the sea level of each segment of the rugged
terrain, i.e. the i-th segment is Li meters from sea level.
You needs to transform the terrain into a strictly downward sloping terrain for the road, i.e, for each
i-th segment where 2 <= i <= N, resultant Li-1 > Li. In order to do so, you employ a powerful digging
team to help you dig and reduce the sea level of the segments. On day D, the team can reduce the
sea level for each segments that you scheduled that day by 2D-1 meters each.
You are allowed to assign the team to dig on multiple segments and/or dig on the same segments for
multiple days.
Your task is to find the minimum number of days needed to transform the terrain as per your
requirements
Example:
Input:
-1
Output:
Explanation:
On day 1, we can dig on 1st and 4th segment, resulting in {-2, 1, 1, 0} On day 2, we can dig on 3rd and
4th segments, resulting in {-2, 1, -1, -2}
On day 3, we can dig on 2nd, 3rd and 4th segments, resulting in {-2, -3, -5, -6}
Input Format
Each line i of the N subsequent lines (where 0 < i ≤ N) contains an integer describing Li, the
sea level of the i-th segment.
Output Format
The program should print a single integer representing the minimum number of days required to
transform the terrain into a strictly decreasing sequence.
Q20.
Problem Statement
Raju is a computer graphics designer. He works around matrices with ease. His friend challenged him
to rotate an M x M matrix clockwise with an angle of 90 degrees.
However, Raju was given a constraint that he must not use any additional 2D matrix for doing the
above-mentioned task. The rotation must be done in place, which means Raju has to modify the
given input matrix directly.
Example: 1
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example: 2
Input Format
The first line of the input is a single integer value for the size of the row and column, M. The next M
lines of the input are the matrix elements, each containing M integers representing the elements of
the matrix.
Output Format
The output displays the rotated matrix, with each row printed on a new line.
Constraints
n == matrix.length == matrix[i].length
1≤N≤6
1 ≤ matrix[i][j] ≤ 1000
13 367
15 14 12 16
15 13 2 5
14 341
12 689
Problem Statement
Imagine you're helping a friend plan gift packages with a total budget of N. Your task is to find all
unique ways to spend the entire budget on different combinations of gift prices, ensuring no
combination is repeated by rearranging the prices.
Note:
By unique it means that no matter that no other composition can be expressed as a permutation of
the generated composition. For eg. [1,2,1] and [1, 1, 2] are not unique.
You need to print all combinations in non-decreasing order for eg. [1, 2, 1] or [1,1,2] will be printed
as [1,1,2].
The order of printing all the combinations should be printed in lexicographical order.
Input Format
The input consists of a single integer, n, which represents the number to be broken down.
Output Format
The output consists of a list of lists, where each inner list represents a possible breakdown of the
given number.
Each breakdown is represented as a list of integers that add up to the given number. The breakdowns
are printed in lexicographic order.
In this scenario, the given test cases will fall under the following constraints:
1 ≤ N ≤ 25
Problem Statement
You are preparing for a technical interview with a well-known tech company. During a mock
interview, you are presented with a coding challenge related to Binary Search Trees (BSTs).
The challenge is to write a program that finds the kth largest element in a BST, and you are required
to implement an efficient solution.
Your task is to complete the code and ensure that it correctly identifies the kth largest element in the
given input tree.
Input Format
The first line of input consists of a sequence of integers representing the elements of the BST. The
input is terminated by -1.
The second line consists of an integer k, representing the position of the desired largest element.
Output Format
The output prints a single integer, which is the kth largest element in the BST.
1 ≤ Number of nodes in the BST ≤ 50 1 ≤ Values of nodes in the BST ≤ 150 1 ≤ k ≤ Number of nodes in
the BST Sample Input Sample Output
Q23.
Problem Statement
Sanjay is learning about queues in his data structures class and he wants to write a program that
counts the number of distinct elements in the queue. Your task is to guide him in this.
Example
Input:
45 33 29 45 45 46 39
Output:
Explanation:
The distinct elements in the queue are 45, 33, 29, 46, 39. So, the count is 5.
Input Format
The first line of input consists of an integer M, representing the number of elements in the queue.
The second line consists of M space-separated integers, representing the queue elements.
Output Format
The output prints an integer, representing the number of distinct elements in the queue.
1 ≤ M ≤ 20
Q24.
Problem Statement
Imagine you are part of a legal team responsible for reviewing contracts and legal documents. To
streamline the review process, you need a tool that can quickly check if specific legal terms or clauses
are included in a large text document.
Write a program that uses a linear search algorithm to search a given document (a sentence) for the
presence of a specific legal term or clause.
Input Format
The first line of input consists of a string S, the document (a single sentence) containing up to 1000
characters.
The second line consists of a string T, representing the legal term or clause to search for, which can
be up to 100 characters long.
Output Format
If the legal term or clause is found in the document, print "The word '[T]' is present in the given
sentence."
If the legal term or clause is not found, print "The word '[T]' is not present in the given sentence."
Q25.
Problem Statement
Imagine you are organizing a sorting contest for programmers. Participants are given an array of
integers to sort using the insertion sort algorithm with a twist.
Instead of simply sorting the array, participants are required to keep track of the number of swaps
they make during the sorting process.
Your task is to implement a program that takes in the participant's array and calculates the minimum
number of swaps they need to perform to sort the array using the selection sort algorithm.
Example 1
Input:
4321
Output:
Explanation:
Swap 4 with 1 and swap 3 with 2 to form the sorted array {1, 2, 3, 4}.
Example 2
Input:
10 19 6 3 5
Output:
Explanation:
Swap 10 with 3 and swap 19 with 5 to form the sorted array {3, 5, 6, 10, 19}.
Input Format
The first line of input consists of an integer n, representing the number of elements in the array.
The second line consists of n space-separated integers, denoting the elements of the array.
Output Format
The output prints an integer representing the minimum number of swaps required to sort the array
in strictly increasing order.
1 ≤ n ≤ 10
0 ≤ elements ≤ 100
Q26
Problem Statement
Determine whether a given undirected graph contains the Hamiltonian cycle or not.
A Hamiltonian cycle in an undirected graph is a path that visits each vertex exactly once. A
Hamiltonian cycle is a Hamiltonian path with an edge from the last vertex to the first vertex of the
Hamiltonian path.
Example Input:
01010
10111
01001
11001
01110
Output:
012430
Explanation:
Starting from vertex 0, all the vertices can be visited exactly once (0 - 1 - 2 - 4 - 3 - 0).
Input Format
The first line of input consists of an integer that represents the number of vertices (V).
The following lines of input consist of the V*V matrix, which represents the adjacency matrix of the
graph.
Output Format
The output prints If a Hamiltonian cycle exists, print the vertices in the cycle in order, starting and
ending at vertex 0.; otherwise, it prints that the "Hamiltonian path does not exist".
Constraints
3≤V≤5
Q27.
Problem Statement:
Inversion Count: For an array, the inversion count indicates how far (or close) the array is from being
sorted. If the array is already sorted, then the inversion count is 0. If an array is sorted in reverse
order, then the inversion count is the maximum.
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
Example 1:
Input:
N = 5, arr[] = {2, 4, 1, 3, 5}
Output:
Explanation:
Sequence 2, 4, 1, 3, and 5 has three inversions (2, 1), (4, 1), and (4, 3).
Example 2:
Input:
N=5
arr[] = {2, 3, 4, 5, 6}
Output:
Explanation:
Example 3:
Input:
Output:
Explanation:
As all the elements of the array are the same, there is no inversion count.
Input Format
The second line of the input is the list of space-separated integer values.
Output Format
Constraints
Q28.
Problem Statement
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s
such that every character in t (including duplicates) is included in the window. If there is no such
substring, return an empty string.
Examples
Output: BANC
Explanation: The minimum window substring BANC includes 'A', 'B', and 'C' from string t.
Input: s = a, t = a
Output: a
Input: s = a, t = aa
Output:
Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has
one 'a', return an empty string.
Input Format
The first line contains the string s, which is the source string.
The second line contains the string t, which is the target string whose characters must be included in
the window.
Output Format
The output is a single line containing the minimum window substring of s containing all t characters.
If no such window exists, output an empty string.
Constraints
m == s.length
n == t.length
1 ≤ m, n ≤ 105
s and t consist of uppercase and lowercase English letters.
Q2G.
Problem Statement
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
["123", "132", "213", "231", "312", "321"]
Input Format
The first line of input consists of an integer value 'n', representing the number of digits in the
permutation.
The second line of input consists of an integer value 'k', representing the position of the permutation
to be found.
Output Format
The output displays the kth permutation of the first n positive integers.
In this scenario, the given test cases will fall under the following constraints:
1 ≤ n ≤ 9 1 ≤ k ≤ n! Q30.
Problem Statement
Roshan invested all day in developing test data for DC. He couldn’t make it work, so he had a nervous
breakdown and can’t even see clearly anymore. Every time he winks(blinks) while reading, the letters
in a word get mingled up so that the letters from the second half of the word (the shorter half, if the
length is an odd number) “jump in” between the letters from the first half in the following way:
• The final letter “jumps in” the middle of the 1st and the 2nd letter
• The second final letter “jumps in” the middle of the 2nd and the 3rd letter
• The ith letter from the end “jumps in” the middle of the ith and the (i+1)th letter from the
starting
For this case, the word “abcdef” would become “afbecd” after winking.
If Roshan winks again, the same thing happens. After three winks, the word becomes “adfcbe”.
Roshan has decided to write a program to help him figure out what’s correctly written on the screen.
Unfortunately, after a day’s work, he’s too tired, and he needs your help. You are given N, the
number of winks, and the word Roshan sees on the screen. Write a program to solve the mystery for
Roshan and figure out what was actually the word before he winked N times.
Input Format
The first line of input contains a positive integer N, the number of times Roshan blinked. The second
line of input contains the word W from the screen.
The word will consist only of small letters of the English alphabet.
Output Format
The output displays the original word before Roshan blinked N times.
1 ≤ N ≤ 109
3 ≤ length(W) ≤ 103
Q31.
Problem Statement
You are given two strings order and s. All the characters of order are unique and were sorted in some
custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if
a character x occurs before a character y in order, then x should occur before y in the permuted
string.
Example 1:
Output: "cbad"
Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba",
"cbda" are also valid outputs.
Example 2:
Output: "bcad"
Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The
character "d" in s does not appear in order, so its position is flexible.
Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c",
"a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this
rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain
their order.
Input Format
The first line of input consists of the string order, representing the custom order of characters. The
second line of input consists of the string s, representing the input string.
Output Format
The output prints the sorted string according to the custom order specified by order.
1 ≤ order.length ≤ 26
1 ≤ s.length ≤ 200
order and s consist of lowercase English letters. All the characters of order are unique.
Q32.
Problem Statement:
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example 1:
Input: n=9
nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Example 2:
Output: 1
Example 3:
Input: n=5
nums = [5,4,-1,7,8]
Output: 23
Input Format
The first line consists of an integer n, representing the number of elements in the array nums.
The second line consists of n space-separated integers, representing the elements of the array nums.
Output Format
The output prints an integer, representing the sum of the subarray with the largest sum.
1 ≤ n ≤ 20
Q33.
Problem Statement
Given an array, the task is to find the sum of the maximum sum by alternating subsequences starting
with the first element. Here alternating sequence means first decreasing, then increasing, then
decreasing,... For example, 10, 5, 14, and 3 are alternating sequences.
Example Input:
438538
Output:
28
Explanation:
The alternating subsequence (starting with the first element) that has the maximum sum is {4, 3, 8, 5,
8}
Input Format
The first line contains an integer n, representing the number of elements in the array.
The second line contains n space-separated integers, representing the elements of the array.
Output Format
The output displays a single integer representing the maximum sum of an alternating subsequence
from the given array.
1 ≤ n ≤ 10
1 ≤ elements ≤ 100
You are given N terrain segments. Each segment i has a height Li. You want to make the terrain
strictly decreasing, i.e., L1 > L2 > ... > LN.
On day D, a team can reduce the height of any segment by 2^(D-1). You may assign the team to any
segment any number of times (even multiple times on different days).
Find the minimum number of days required to make the terrain strictly decreasing. Constraints:
● 2 ≤ N ≤ 10^5
N L1 L2
... LN
Output:
A magical road needs to be strictly increasing in height to avoid monster attacks. You’re given heights
H[0...N-1] and can cast spells to increase any segment’s height.
On day D, the spell increases a chosen segment by 2^(D-1). You can cast multiple spells on any
segment and on any day.
Find the minimum number of days required to make the entire array strictly increasing.
Question 3: Mountain Array Transformation (Pattern Matching + Brute Force) You’re given an array A
of N integers. Transform it into a mountain array, defined as:
● As you move from either end to the middle, each next value must increase by 1
● The peak value(s) can be same or different, but the pattern must rise and fall symmetrically
Find the minimum number of elements to change to achieve a mountain array. QUESTION 4: n the
stock market, a person buys a stock and sells it on some future date. You are given an array prices[]
representing stock prices on different days and a positive integer k, find out the maximum profit a
person can make in at-most k transactions.
A transaction consists of buying and subsequently selling a stock and new transaction can start only
when the previous transaction has been completed.
Examples :
2nd transaction : Buy at 5 and sell at 80. Total Profit will be 12 + 75 = 87.
Output: 0 Constraints:
1 ≤ prices.size() ≤ 103
1 ≤ k ≤ 200
1 ≤ prices[i] ≤ 103
Question 5:
Altaf has recently learned about number bases and is becoming fascinated.
Altaf learned that for bases greater than ten, new digit symbols need to be introduced, and that the
convention is to use the first few letters of the English alphabet. For example, in base 16, the digits
are 0123456789ABCDEF. Altaf thought that this is unsustainable; the English alphabet only has 26
letters, so this scheme can only work up to base 36. But this is no problem for Altaf, because Altaf is
very creative and can just invent new digit symbols when she needs them. (Altaf is very creative.)
Altaf also noticed that in base two, all positive integers start with the digit 1! However, this is the
only base where this is true. So naturally, Altaf wonders: Given some integer N, how many bases b
are there such that the base-b representation of N starts with a 1?
INPUT FORMAT :
The first line of the input contains an integer T denoting the number of test cases. The description of
T test cases follows.
Each test case consists of one line containing a single integer N (in base ten). OUTPUT FORMAT :
For each test case, output a single line containing the number of bases b, or INFINITY if there are an
infinite number of them.
CONSTRAINTS :
SAMPLE INPUT : 4
11
24
SAMPLE OUTPUT : 4
14
Question 6:
Sam is handed a rectangular piece of paper with the dimensions h*w, where h denotes height and w
denotes width. Sam wants to fold the paper in the fewest possible moves such that its dimensions
are h1*w1. The paper could only be folded parallel towards its edges, and the dimensions should be
integers after folding. If h=8 and w=4, for example, fold the paper till it's h1, w1 = 6,1. First, fold the
long edge 6 units to the side, resulting in a 6*4 paper. And then, Fold the page in three folds along
the width 2 units edge to achieve a 6*1 page.
Input Format
First line contains an integer denotes h Seconds line contains an integer denotes w Third line
contains an integer denotes h1 Fourth line contains an integer denotes w1 Constraints
h1 <= h w1 <= w
Output Format
Sample Output:
Question 7:
Finding the shortest path in a graph is a problem that we can solve using dynamic programming.
Suppose we need to find the shortest path between the nodes ‘u’ and ‘v’. There is a node ‘x’ that falls
in the shortest path from node ‘u’ to ‘v’. Then we can find the answer using the shortest path from
‘u’ to ‘x’ and the shortest path from ‘x’ to ‘v’.
Question 8:
We have been given a binary matrix of R x C. we have to find the maximum area of the square
submatrix.
0000000
0011100
0011100
0011100
0000000
111
111
0000000
0000000
0011100
0011100
0011100
0000000
Sol Matrix: 0 0 0 0 0 0 0
0000000
0011100
0012200
0012300
0000000
0000000
Question 9:
You are given a multi story building, and some number of eggs. You want to know from which floors,
if you drop a egg, it will break.
It’s a Monday in Coders’ world. You are about to get a new problem. There is a building with floors 1
to ‘FLOORS’. You are given a basket full of identical eggs. ‘EGGS’ identical eggs. As the eggs are
identical, they follow the same properties. These properties are given below:
1. Each egg breaks only if it is dropped from a certain floor ‘EGGBREAKER’ or above.
2. An egg that is not broken after being dropped from a floor can be used to drop again.
3. Your task is to find the minimum number of egg drops required in the worst case to
find out the ‘EGGBREAKER’ floor.
Dropping from different floors leads to a different number of moves required to find the
‘EGGBREAKER’ floor.
Input
Enter Eggs: 2
Enter Floors: 6
Output
Question 10:
The Central Bureau of Investigation encrypts some papers for security reasons. The document is first
turned into lower case letter strings in this process. This string is now being encoded.
Encoding Procedures
● The string can be broken down into a list of non-empty substrings at random.
● Now that we have a list of strings, randomly pick some substrings and change them with
their lengths.
You are given two encoded strings, 'S1' and 'S2', consisting of lower case English letters and digits 1
to 9, and you have to tell if both strings are encoded from the same parent string. In other words,
return true if a parent string 'S' exists, which can be encoded as 'S1' and 'S2' both. Else return false.
EASY:
Question 1:
Ram went to fight for Coding Club. There were N fighters with various powers. There will be Q rounds
to fight and in each round, Ram's power will be varied. With power M, Ram can kill all the fighters
whose power is less than or equal to M(<=M). After each round, All the soldiers who are dead in the
previous round will reborn. Such that in each round there will be N fighters to fight. As Ram is weak
in mathematics, help him to count the number of fighters that he can kill in each round and the total
sum of their powers.
INPUT:
The second line contains an array of N numbers denoting the power of each fighter This third line
contains Q, which denotes the number of rounds.
Q lines follow, each line having one number denoting the power of Ram.
OUTPUT:
For each round, the output should be an array of two numbers. The first number should be the
number of fighters that Ram can beat, and the second number denotes the cumulative strength of all
the fighters that Ram can beat.
CONSTRAINTS:
1<=N<=10000
1<=power of Ram<=100
Case 1:
Input:
7
1234567
10
Output:
36
7 28
23
Case 2:
Input:
10 20 30 40 50
25
50
60
Output:
00
2 30
5 150
5 150
Case 3:
Input:
6
5 10 15 20 25 30
15
35
Output:
00
3 30
6 105
Question 2:
You are given a string s and a list dictionary[] of words. Your task is to determine whether the string s
can be formed by concatenating one or more words from the dictionary[].
Note: From dictionary[], any word can be taken any number of times and in any order. Constraints:
1 ≤ s.size() ≤ 3000
1 ≤ dictionary.size() ≤ 1000
1 ≤ dictionary[i].size() ≤ 100
Case 1:
Case 2:
Input: s = "ilikeabc", dictionary[] = ["i", "like", "man", "india", "abc"] Output: true
Case 3:
Input: s = "ilikemangoes", dictionary[] = ["i", "like", "man", "india", "abc"] Output: false
Question 3:
You’re a data compression engineer working on a custom text encoder. Your goal is to minimize the
weight of a string before storing it in a compressed database. Weight of a string is defined as: The
sum of squares of the frequency of each distinct character.
You're allowed to remove exactly k characters from the string (any characters, not necessarily
distinct). The objective is to minimize the weight after removals.
Constraints:
Input:
str = "abccc" k = 1
Output:
Case 2:
Input:
str = "aabcbcbcabcc" k = 3
Output:
27
Case 3:
Input:
str = "zzzzzz" k = 2
Output:
16
Question 4:
You're building a task scheduler for a project management system. Each task may depend on other
tasks being completed first. All its prerequisites must be finished before starting any task.
You're given: The total number of tasks N. A list of prerequisite relationships P, where each pair [A, B]
means: "To do task A, you must finish task B first."
You must determine if all the tasks are scheduled so that no prerequisite conflict prevents
completion. If yes, return "Yes" — all tasks can be completed.
Case 1:
Input:
N=4
P=3
Output:
Yes Case 2:
Input:
N=2
P=2
Output:
No Case 3:
Input:
N=6
P=5
prerequisites = [[1, 0], [2, 1], [3, 2], [4, 3], [5, 4]]
Output:
Yes
Question 5:
In the realm of binary encoding, a transmission protocol defines every integer as a fixed-length
bitstream. When converting one encoded signal a to another b, the transformation cost is measured
in bit mismatches — each mismatch represents a necessary flip to achieve identity.
Given two non-negative integers a and b, determine the minimum Hamming distance between their
binary representations — that is, count the number of individual bit positions at which the
corresponding bits differ when a is transformed into b.
Your goal is to compute the number of atomic bit-flip operations needed to make a exactly equal to
b. Constraints:
Case 1:
Input:
a = 10
b = 20
Output: 4
Case 2:
Input:
a = 20
b = 25
Output:
Case 3:
Input:
a = 1000
b = 1500
Output:
MEDIUM
Question 1:
In a chain of N mountain reservoirs, each dam holds water up to height Hᵢ. You may release water
from any dam down to any lower level; releasing from height h₁ to h₂ costs h₁–h₂ energy units. Your
goal is to make all reservoirs share the same water height at minimum total energy.
Constraints:
1 ≤ N ≤ 10⁵
1 ≤ Hᵢ ≤ 10⁹ Input:
H₁ H₂ … Hₙ
Output:
Case 1:
Input: 4
8363
Output: 11
Case 2: Input:
5
Output:
Case 3:
Input:
Output:
Question 2:
A lantern festival runs along a straight promenade divided into segments [Sᵢ, Eᵢ]. You need to install
light- beacons (at integer positions) so each segment has at least one beacon. Each beacon normally
costs 1 lantern package, but every second beacon at the exact same spot is free. Compute the
minimum number of packages needed.
Input:
S₁ E₁
Sₘ Eₘ
Output:
Constraints: 1 ≤ M ≤ 10⁵
1 ≤ Sᵢ< Eᵢ ≤ 10⁹
Case 1:
Input : 3
2 5
47
68
Output: 2
Case 2: Input:
1 10
1 10
Output:
Case 3:
Input:
12
3 4
56
Output:
Question 3:
A data center has N separate cable segments, each of length Lᵢ. To form one continuous cable, you
repeatedly join two segments into one; joining lengths a and b costs a + b (materials and labor).
Compute the minimum total cost to consolidate all segments into a single cable.
Input:
N
L₁ L₂ … Lₙ
Output:
Constraints: 1 ≤ N ≤ 10⁵
1 ≤ Lᵢ ≤ 10⁹
Case 1:
Input: 4
4 326
Output: 29
Case 2: Input: 1
10
Output:
Case 3:
Input:
5 55
Output:
25
Question 4:
A composer has written a melody string T (notes represented by lowercase letters). If they remove
up to K notes, they want the lexicographically smallest remaining melody (order of the others must
stay the same).
A lexicographically smallest string is one that would appear first in a dictionary: compare two strings
from the first character onward; at the first differing character, the string with the smaller character
is lexicographically smaller.
Input:
TK
Output:
Constraints:
1 ≤ |T| ≤ 10⁵
0 ≤ K < |T|
Case 1:
Input: dbcaab 2
Output: bcaab
Output:
Yx
Case 3:
Input:
abc 0
Output:
abc
Question 5:
The royal courier must deliver N decrees, one at a time. Decree i takes Tᵢ days to deliver and incurs a
daily displeasure penalty of Wᵢ gold coins per day until it’s delivered. When decree i finishes on day
Cᵢ, the palace pays a total penalty of Wᵢ × Cᵢ. Devise a delivery order to minimize the sum of all
penalties
Input:
T₁ W₁ T₂ W₂
Tₙ Wₙ
Output:
Constraints: 1 ≤ N ≤ 10⁵
Case 1:
Input: 3
34
1 100
22
Output: 128
Case 2: Input:
1 10
Output:
10
Case 3:
Input:
52
33
Output:
25
Question 6:
You are given a DNA sequence S of length N, made up of the characters A, C, G, and T.
You want to divide this string into K equal-length contiguous blocks (assume N % K == 0). Your task is
to mutate as few characters as possible so that all K blocks become the same.
A mutation means changing one character to another at a specific position. You are allowed to
mutate any character, but your goal is to minimize the total number of mutations across all blocks.
• S :: STRING The first line contains the DNA sequence. len(S) :: 1 → 2 * 10^5 Characters are
only from A, C, G, and T.
• K :: INTEGER The next line contains the integer K, the number of blocks. K :: 1 → len(S) It is
guaranteed that len(S) % K == 0.
Case#: 1
Input: ACGTACGT 2
Output: 0
Explanation: Split into blocks: ACGT and ACGT They are already identical. No mutations needed.
Case#: 2
Input: ACGTAGCT 2
Output: 2
Explanation: Blocks: ACGT and AGCT At position 2: G vs C → mutate one At position 3: T vs T → same
Minimum mutations needed = 2
Case#: 3
Input: AACCGGTT 4
Output: 6
Explanation: Blocks: AA, CC, GG, TT For each position (0 and 1), we want to align all to the most
frequent character.
Case#: 4
Input: ATCGATCA 2
Output: 1
Question - 7
You are managing a fleet of delivery vehicles. Each vehicle starts from a central depot and delivers
packages to customers. Every customer has a specific time window during which they must receive
their delivery.
Your task is to assign customers to vehicles and determine delivery routes such that:
A vehicle can wait at a customer location if it arrives early. All vehicles travel at a speed of 1 unit
distance per minute. There is no limit on the number of deliveries per vehicle unless time constraints
prevent it.
Parameters:
Customers :: LIST A list of N entries. Each customer is described by: (x, y, start_time, end_time)
where: (x, y) are 2D coordinates of the customer,
start_time and end_time define the allowed time window (in minutes). Each vehicle:
• May wait at the customer location if it arrives before the time window.
Case#: 1
Input:
00
1 0 0 10
2 0 5 15
3 0 10 20
Output:
Explanation:
• One vehicle can visit all 3 customers in sequence: (1,0) → (2,0) → (3,0)
• Total route: 0→1→2→3→0 → total distance = 6 [vehicle has to wait 3 mins at 2nd customer
and 4 mins at 3rd customer though for honouring time windows]
Case#: 2
Input:
3
00
10 0 0 5
20 0 0 5
30 0 0 5
Output:
-1
Explanation:
• Due to tight time windows and long distances, one vehicle cannot serve multiple customers.
• Each vehicle serves one customer and returns. Distances: Depot → (10,0) → Depot = 20
Total = 20 + 40 + 60 = 120 but due to time window [0,5] for all the customers, it is not feasible.
Question 8:
You have an interesting string S of length N. It is interesting because you can rearrange the
characters of this string in any order.
After rearranging the string once, you want to cut it into K contiguous segments such that each
segment is a palindrome. You cannot rearrange or modify the segments after cutting.
Your goal is to find the maximum number of palindromic segments you can obtain after
rearrangement and cutting.
Note: A palindrome is a string that reads the same forward and backward, such as "aba", "abba", or
"a".
Parameters:
• S :: STRING The first line contains a string S, denoting the string. len(S) :: 1 -> 2 * 10^5
Explanation: We can rearrange the string as "abc" + "cba" → both are palindromes. Hence, maximum
palindromic segments = 2.
Case#: 2
Input: aaabbbbcc
Output: 3
Explanation: Rearranged string = "bab" + "cac" + "bab" or similar. All three segments are
palindromes. Hence, answer is 3.
Explanation: Any rearrangement of the string cannot be divided into more than one palindrome
segment. Best option is to keep the whole string as one palindrome.
Question 9:
You are designing the stamina management system for a turn-based game. A character must defeat a
sequence of enemies, where each enemy requires a certain amount of stamina to defeat. The
character starts with full stamina and can either fight, skip, or use a potion. Your goal is to minimize
the number of potions used while defeating all enemies(can skip max K enemies).
If current stamina is less than cost[i], you must either: Skip the enemy (but you can only skip up to K
enemies in total), or
Use a potion to restore stamina back to S (can use multiple times). After fighting, stamina is reduced
by cost[i].
Parameters:
• cost :: LIST of INTEGER cost[i] is the stamina required to fight the i-th enemy 1 ≤ cost[i] ≤
1000
Compute the minimum number of potions the character needs to use to defeat all enemies, without
exceeding K skips.
Case#: 1
Input:
N=5
S = 10
K=1
cost = [4, 6, 8, 2, 5]
Output:
Explanation:
HARD:
Question 1:
There is a soccer team with n players, numbered from 0 to n-1. The team wants to pass the ball from
player 0 to player n-1, and each player can only pass forward, i.e., from a player i to another player j
such that j>i.
You are given a 2D array prob, where prob[i][j] represents the probability (a value between 0 and 1)
that thepass from player i to player j will succeed. Each player can
pass the ball to any player ahead (j > i), and your goal is to choose an optimal sequence of passes to
maximize the probability that player n-1 successfully receives the ball.
Your task is to calculate the maximum probability of successfully passing the ball from player 0 to
player n-1, by choosing the best sequence of passes.
Parameters:
- The first line contains an integer n, denoting the number of players. 2 ≤ n ≤ 100
The j-th number on the i-th line (where j > i) represents prob[i][j], the success probability of passing
from player i to player j.
Output:
- Return the maximum probability (a floating-point number) that player n-1 successfully
receives the ball, rounded to 6 decimal places.
Case#:1
Input:
0 0 0.7 0.5
0 0 0 0.6
0000
Output:
0.504000
Case#: 2
Input:
0 0.5 0.2
0 0 0.9
000
Output:
0.450000
Case#: 3
Input
0 0 0 0.8 0.3
0 0 0 0 0.9
00000
Output
0.302400
Question 2:
US Iron, a company that specializes in custom hand-forged iron, wants to reuse iron rod ends and
weld them into one longer rod. Given N iron rods of different lengths, you are asked to write a
program to find the minimum cost to weld all of them into a longer rod, knowing that the cost of
welding two iron rods is equal to the sum of their two lengths.
Parameters:
N : INTEGER
The first integer contains N, denoting the number of rods. 3 <= N <= 100
An array of N integers, each denoting the length of a rod. 1 <= array[i] <= 100
Input:
Each test case consists of one line containing one integer N representing the number of iron rods to
weld followed by N integers representing the length of each rod.
Output:
For each test case, output one line containing the minimum cost to weld all the iron rods into a single
rod.
Case#1:
Input:
21 29 18 33 9
Output:
247
Case2#:
Input:
63 11 42 21 35 53
Output:
549
Case#3:
Input:
7
2 11 15 20 7 17 6
Output:
205
Question 3:
There are ‘r’ red and ‘g’ green blocks for construction of the red-green tower. Red-green tower can
be built following next rules:
Let the red-green tower consist of n levels, then the first level of this tower should consist of n
blocks, second level — of n - 1 blocks, the third one — of n - 2 blocks, and so on — the last level of
such tower should consist of the one block. In other words, each successive level should contain one
block less than the previous one;
Each level of the red-green tower should contain blocks of the same color.
Let h be the maximum possible number of levels of red-green tower, that can be built out of r red
and g green blocks meeting the rules above. The task is to determine how many different red-green
towers having h levels can be built out of the available blocks.Two red-green towers are considered
different if there exists some level, that consists of red blocks in the one tower and consists of green
blocks in the other tower.
You are to write a program that will find the number of different red-green towers of height h
modulo 109 + 7.
Parameters:
The only line of input contains two integers r and g, separated by a single space — the number of
available red and green blocks respectively (0 ≤ r, g ≤ 2·105, r + g ≥ 1).
Output the only integer — the number of different possible red-green towers of height (h modulo
109 + 7).
Case#1:
Input
46
Output
Case#2 Input 9 7
Output
6
Case#3 1 1
Output
Question 4:
Winter is here in the North and the White Walkers are close. John Snow has an army consisting of n
soldiers. While the rest of the world is fighting for the Iron Throne, he will get ready for the attack of
the White Walkers.
He created a method to know how strong his army was. Let the i-th soldier’s strength be ai. For some
k he calls i1, i2, ..., ik a clan
and gcd(ai1, ai2, ..., aik) > 1 . He calls the strength of that clan k·gcd(ai1, ai2, ..., aik). Then he defines
the strength of his army by the sum of strengths of all possible clans.
Your task is to find the strength of his army. As the number may be very large, you have to print it
modulo 1000000007 (109 + 7).Greatest common divisor (gcd) of a sequence of integers is the
maximum possible integer so that each element of the sequence is divisible by it.
Parameters:
The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000000) — denoting the strengths of his
soldiers.
Print one integer — the strength of John Snow's army modulo 1000000007 (109 + 7).
Case#1:
Input
331
Output:
12
Case#2:
Input
4
2346
Output:
39
Case#3:
Input
7 14 21 2 5
Output:
140
Question 5:
There is a fun learning game devised by a teacher to help students learn Mathematics and English. In
this game, the teacher gives students a random sequence of uppercase letters. The task is to identify
the longest sequence of letters that are placed in correct alphabetical order relative to each other
(not necessarily consecutively).
For example, in the sequence `AFBGCE`, a correct relative sequence is `ABCE`. The letters don't need
to be adjacent in the original string, but they must appear in the same order.
Your task is to write a program that, given such a sequence, returns the length of the longest
subsequence of letters that are in the correct relative alphabetical order.
Parameters:
Output a single integer which represents the length of the longest subsequence where the letters are
in relative alphabetical order.
Constraints:
Output:
4
Output:
Case#3:
Input:
QWERTYUIOP
Output:
Description:
You have an array A of length N, initially all zeros. You will process Q operations of two types:
2. Query: For a given window size K, find the minimum value in each contiguous window of size
K over the current array.
Return all query answers in order of appearance; each query produces an array of length N−K+1.
Constraints:
• 1 ≤ N, Q ≤ 2·10^5
• 1 ≤ i ≤ N, −10^9 ≤ x ≤ 10^9
• 1≤K≤N
________________________________________
Samples
Sample 1
N = 5, Q = 4
Operations:
1) Update 3 5
2) Update 1 -2
3) Query K=3
4) Query K=5
Output:
[-2, 0, 0]
[-2]
________________________________________
Sample 2
N = 4, Q = 5
Ops:
1) Update 2 1
2) Update 4 -1
3) Query 2
4) Update 3 2
5) Query 3
Output:
[-1, -1]
First query on [0, 1, 0, -1] windows of size 2; second on [0 ,1 ,2 , -1] windows of size 3.
________________________________________
Sample 3
N = 3, Q = 3
Ops:
1) Query 1
2) Update 1 10
3) Query 2
Output:
[0, 0, 0]
[0, 0]
Description:
3. Sum p: compute the sum of values of all strings in the multiset that start with prefix p.
Constraints:
• 1 ≤ |s|,|p| ≤ 20
• 1 ≤ v ≤ 10^6
Samples
Sample 1
Ops:
Add "apple" 3
Add "app" 2
Sum "ap"
Remove "app" 2
Sum "app"
Output:
Sample 2
Ops:
Add "cat" 5
Add "car" 7
Sum "ca"
Sum "car"
Output:
12
7
Sample 3
Ops:
Add "dog" 4
Add "dog" 6
Remove "dog" 4
Sum "do"
Output:
Description:
You have N nodes numbered 1…N. You will receive M operations of two types, but you must answer
them offline:
• Query u v: at this point in time, are u and v in the same connected component?
Constraints:
• 1 ≤ N ≤ 10^5, 1 ≤ M ≤ 2·10^5
• 1 ≤ u, v ≤ N
________________________________________
Samples
Sample 1
N = 5, M = 5
Ops:
Connect 1 2
Query 1 3
Connect 2 3
Query 1 3
Query 4 5
Output:
NO
YES
NO
________________________________________
Sample 2
N = 3, M = 4
Ops:
Connect 1 2
Connect 2 3
Query 1 3
Query 1 1
Output:
YES
YES
________________________________________
Sample 3
N = 4, M = 6
Ops:
Query 1 4
Connect 3 4
Query 1 4
Connect 1 2
Connect 2 3
Query 1 4
Output:
NO
NO
YES
• Kth L R k: in the subarray A[L..R], find the k-th smallest element. If k > R−L+1, return −1.
Constraints:
• 1 ≤ N, Q ≤ 10^5
• 1 ≤ A[i], x ≤ 10^9
• 1 ≤ L ≤ R ≤ N, 1 ≤ k ≤ N
________________________________________
Samples
Sample 1
Ops:
Kth 1 5 2
Update 3 0
Kth 1 5 2
Kth 2 4 3
Output:
-1
________________________________________
Sample 2
Ops:
Kth 1 3 1
Update 2 1
Kth 1 3 2
Output:
2
________________________________________
Sample 3
Ops:
Kth 2 3 1
Update 4 5
Kth 1 4 4
Output:
20
-1
Description:
You have an array A of length N. You will process Q operations of two types:
Constraints:
• 1 ≤ N, Q ≤ 2·10⁵
• 1 ≤ A[i] ≤ 10⁹
• 1 ≤ i, j, L, R ≤ N
Samples
Input:
Ops:
1) RangeMin 2 4
2) Swap 2 4
3) RangeMin 2 4
4) RangeMin 1 5
Output:
1
Input:
Ops:
1) RangeMin 1 3
2) Swap 1 3
3) RangeMin 1 1
Output:
Input:
Ops:
1) Swap 1 4
2) RangeMin 1 3
3) Swap 2 3
4) RangeMin 2 4
5) RangeMin 3 3
Output:
Description:
You build a binary search tree (initially empty) by inserting N distinct keys in given order. Then
answer Q queries: for each x and k, find the k-th smallest element in the BST strictly greater than x. If
fewer than k such elements exist, return -1.
• 1 ≤ N, Q ≤ 10⁵
Samples
Input:
Queries:
1) (x=4, k=1)
2) (x=5, k=2)
3) (x=8, k=1)
Output:
-1
Input:
Queries:
Output:
20
30
10
Input:
Insert: [7,1,9,3]
Queries:
Output:
7
-1
Description:
You have a fixed-size circular buffer of capacity C (initially empty). Support Q operations:
Constraints:
• 1 ≤ C, Q ≤ 2·10⁵
• |x| ≤ 10⁹
Samples
Input:
C=3
Ops:
Enqueue 1
Enqueue 3
Max
Enqueue 2
Enqueue 5
Max
Output:
Input:
C=2
Ops:
Enqueue 4
Max
Enqueue -1
Max
Enqueue 2
Max
Output:
Input:
C=1
Ops:
Enqueue 7
Max
Enqueue 5
Max
Output:
Description:
1. SetCap c: change cache capacity to c. If current size > c, evict least-recently-used items until
size = c.
2. Put k v: insert or update key k with value v. If insertion causes overflow, evict LRU.
3. Get k: return value for key k, or -1 if not present. Accessing a key makes it MRU.
Constraints:
• 1 ≤ Q ≤ 2·10⁵
• Capacities: 1 ≤ c ≤ 2·10⁵
Samples
Input:
Ops:
SetCap 2
Put 1 100
Put 2 200
Get 1
Put 3 300
Get 2
Output:
100
-1
Input:
Ops:
SetCap 1
Put 5 50
Put 6 60
Get 5
Get 6
Output:
-1
60
Input:
Ops:
SetCap 3
Put 1 10
Put 2 20
Put 3 30
SetCap 2
Get 1
Get 3
Output:
-1
30
Description:
You’re given a base string S (length N). Process Q queries, each a pattern P. Determine whether P
appears as a contiguous substring in any cyclic rotation of S. Return YES or NO per query. Preprocess
S in O(N); answer each query in O(|P|).
Constraints:
• 1 ≤ N ≤ 2·10⁵, 1 ≤ Q ≤ 2·10⁵
Samples
1.
S = "abac"
Queries:
"cab"
"aca"
"baa"
Output:
YES
YES
NO
2.
S = "aaaa"
Queries:
"aaa"
"aaaaa"
"aa"
Output:
YES
NO
YES
3.
S = "xyz"
Queries:
"yzx"
"zy"
"xy"
Output:
YES
NO
YES
Description:
Given an array A of length N, answer Q queries of the form (L,R): return the number of distinct
elements in the subarray A[L..R]. Preprocess in O(N log N); answer each query offline in O((N+Q) log
N) via Fenwick or segment tree.
Constraints:
• 1 ≤ N, Q ≤ 2·10⁵
• 1 ≤ A[i] ≤ 10⁹
• 1≤L≤R≤N
Samples
1.
A = [1,2,1,3,2], Q=3
Queries:
(1,5)
(2,4)
(3,3)
Output:
3
2.
A = [5,5,5], Q=2
Queries:
(1,3)
(2,3)
Output:
3.
A = [1,2,3,4], Q=2
Queries:
(1,2)
(3,4)
Output:
Description:
Design a system that processes N daily stock prices one by one and reports the “span” for each day:
the number of consecutive days before today (inclusive) for which the price was ≤ today’s price.
Implement in O(N) overall with a stack.
Constraints:
• 1 ≤ N ≤ 2·10⁵
• 1 ≤ price ≤ 10⁹
Samples
1.
Output:
[1, 1, 1, 2, 1, 4, 6]
2.
Output:
[1, 2, 3]
3.
Output:
[1, 1, 1]
Description:
Implement a queue that supports persistence across versions. You have an initial empty queue
(version 0). Each operation creates a new version:
2. Dequeue v: on version v, dequeue front element (if non-empty), producing version v'.
All operations in O(1) amortized, using two stacks per version (persistent stacks).
Samples
1.
Ops:
Enqueue 0 5 → v1
Enqueue 1 3 → v2
Front 2 →?
Dequeue 2 → v3
Front 3 →?
Output:
2.
Ops:
Front 0 →?
Enqueue 0 1 → v1
Dequeue 1 → v2
Front 2 →?
Output:
-1
-1
3.
Ops:
Enqueue 0 2 → v1
Enqueue 1 4 → v2
Dequeue 2 → v3
Dequeue 3 → v4
Front 4 →?
Output:
-1
Description:
Given two sorted arrays A (length N) and B (length M), find the k-th smallest sum A[i]+B[j] among all
0 ≤ i < N, 0 ≤ j < M. Target O((N+M) log (N+M)) using a min-heap of candidate pairs.
Samples
1.
Output:
2.
Output:
3.
Description:
2. Query: report the total weight of the current minimum spanning forest.
Requires an online dynamic MST algorithm in O(log² N) amortized per operation, e.g., using a link-cut
tree or dynamic tree structure.
Samples
1.
N=4
Ops:
AddEdge 1 2 3
Query
AddEdge 2 3 1
AddEdge 3 4 2
Query
Output:
2.
N=3
Ops:
Query
AddEdge 1 2 5
Query
AddEdge 2 3 4
Query
Output:
0
5
3.
N=5
Ops:
AddEdge 1 2 2
AddEdge 2 3 2
AddEdge 3 4 2
AddEdge 4 5 2
Query
Output:
Description:
Samples
Ops:
h1 = MakeHeap
h2 = MakeHeap
Insert h1 5
Insert h2 3
Merge h1 h2
GetMin h1
Output:
2.
Ops:
h = MakeHeap
Insert h 10
Insert h 1
ExtractMin h
GetMin h
Output:
10
3.
Ops:
h1 = MakeHeap
Insert h1 7
h2 = MakeHeap
GetMin h2
Output:
-1 (empty heap)
Description:
Given a rooted tree of N nodes (root = 1) with initial values val[i]. Support Q operations:
2. SubtreeMax u: return the maximum value among all nodes in the subtree of u.
Constraints:
• 1 ≤ N, Q ≤ 2·10⁵
• 1 ≤ val[i], x ≤ 10⁹
Samples
1.
Tree: 1–2,1–3,3–4; val=[5,3,7,2]
Ops:
SubtreeMax 1 → 7
SubtreeMax 3 → 7
Update 4 10
SubtreeMax 3 → 10
Output:
10
2.
Ops:
SubtreeMax 2 → 3
Update 3 0
SubtreeMax 2 → 2
Output:
3.
Ops:
SubtreeMax 1 → 4
Update 2 5
SubtreeMax 1 → 5
Output:
Constraints:
• 1 ≤ N, Q ≤ 2·10⁵
Samples
1.
N=3
Ops:
AddEdge 1 2
IsBipartite → ?
AddEdge 2 3
AddEdge 3 1
IsBipartite → ?
Output:
YES
NO
2.
N=4
Ops:
AddEdge 1 2
AddEdge 3 4
IsBipartite → ?
Output:
YES
3.
N=5
Ops:
AddEdge 1 2
AddEdge 2 3
AddEdge 1 3
IsBipartite → ?
Output:
NO
Description:
2. KthLargest k: return the k-th largest element seen so far; if fewer than k elements, return -1.
Achieve O(log k) per query by keeping a min-heap of size k for each distinct k requested (or using an
Order-Statistics Tree).
Samples
1.
Ops:
Add 5
Add 1
Add 10
KthLargest 2
Add 6
KthLargest 3
Output:
2.
Ops:
KthLargest 1
Add 7
KthLargest 1
Output:
-1
3.
Ops:
Add 3
Add 3
Add 3
KthLargest 2
Output:
Description:
Precompute Fibonacci modulo 10⁹+7. Given an array I of indices (1-based), support Q queries:
Use a Fenwick or segment tree, with O(log N) per query and point updates if desired.
Samples
1.
I = [1,2,3,4,5]
Queries:
SumFib 2 4
SumFib 1 5
Output:
2+3+5 = 10
1+2+3+5+8 = 19
2.
I = [10,10,10], Q=1
SumFib 1 3
Output:
3 * Fib(10)=3*55=165
3.
I = [6,7,8,9], Q=2
SumFib 1 2
SumFib 3 4
Output:
8+13=21
21+34=55
Description:
Use binary-lifting with dynamic table resizing or link-cut trees for O(log N) per op.
Samples
1.
Ops:
AddNode 1 → node2
AddNode 1 → node3
AddNode 2 → node4
LCA 4 3
Output:
2.
Ops:
AddNode 1 →2
AddNode 2 →3
AddNode 3 →4
LCA 3 4
Output:
3.
Ops:
AddNode 1 →2
AddNode 1 →3
AddNode 2 →4
AddNode 2 →5
LCA 4 5
Output:
Description:
Given a tree of N nodes (rooted arbitrarily), each node has a value val[i]. Support Q queries:
• KthOnPath u v k: find the k-th largest value among the nodes on the (unique) path from u to
v. If fewer than k nodes, return -1.
Achieve O(log² N) per query using Heavy-Light Decomposition plus a persistent segment tree (or
order-statistics tree) on each chain.
Constraints:
• 1 ≤ N, Q ≤ 2·10⁵
• 1 ≤ val[i] ≤ 10⁹
Samples
1.
Queries:
KthOnPath 2 4 1
KthOnPath 2 4 2
KthOnPath 2 4 3
Output:
2.
Queries:
KthOnPath 1 3 2
KthOnPath 1 3 3
Output:
3.
Queries:
KthOnPath 2 4 2
Output:
Description:
Implement in O(log N) per op using a segment tree with rolling-hash (both forward and backward).
Constraints:
• 1 ≤ N, Q ≤ 2·10⁵
• c is a lowercase letter
Samples
1.
S = "abca", Q=4
IsPal 1 4 → ?
Update 4 'a'
IsPal 1 4 → ?
Update 2 'b'
IsPal 1 3 → ?
Output:
NO
YES
YES
2.
S = "racecar", Q=2
IsPal 1 7
IsPal 2 6
Output:
YES
YES
3.
S = "abcde", Q=3
IsPal 1 3
Update 2 'a'
IsPal 1 3
Output:
NO
YES
Description:
Implement in O(log N·log M) per op using a 2D segment tree with lazy propagation.
Constraints:
Samples
1.
Matrix 2×3:
[1 2 3
4 5 6]
Q=3
AddRect 1 2 2 3 10
RectMax 1 1 2 2
RectMax 2 2 2 3
Output:
12
16
2.
AddRect 1 1 3 3 5
RectMax 2 2 3 3
Output:
3.
AddRect 1 2 1 3 -1
RectMax 1 1 1 4
Output:
Description:
1. Insert x: add x to M.
All operations in O(log N) using a balanced BST or a Fenwick tree over compressed coordinates.
Constraints:
• 1 ≤ Q ≤ 2·10⁵
• −10⁹ ≤ x, L, R ≤ 10⁹
Samples
1.
Ops:
Insert 5
Insert 3
CountRange 2 5
Erase 3
CountRange 2 5
Output:
2.
Ops:
CountRange 1 10
Insert 1
Insert 1
CountRange 1 1
Output:
3.
Ops:
Insert 2
Insert 4
Insert 2
Erase 2
CountRange 2 3
Output:
1
24.Layered Rectangle Merge Queries
You are given a list of axis-aligned rectangles on a 2D grid. A rectangle is represented by its bottom-
left and top-right coordinates. Perform Q queries, each asking how many rectangles intersect with a
query rectangle. Rectangles can overlap, and intersection includes edge-sharing.
Input:
• Each rectangle: x1 y1 x2 y2
Output:
Samples:
Input:
1144
2255
3063
2233
0011
Output:
You are given an array representing power levels. You can drop (remove) at most one element from
the array. Find the maximum sum of any contiguous subarray after removing one element (or none).
Input:
• Array A of N elements.
Output:
Output: 4
Output: -1
Output: 11
You are given a string S. You can perform at most K merge operations, where two adjacent equal
characters can be merged into one. Find the length of the shortest compressed prefix you can
achieve.
Input:
• String S
• Integer K
Output:
Samples:
Input: abaaab, 2
Input: aabbccdd, 3
Output: 5
Input: abcdef, 0
Output: 6
Input:
Output:
Samples:
Input:
[5, 3, 2]
Output: 2
Input:
[1, 2, 3]
Edges: [(0,2)]
Output: -1
Given a stream of candidate votes and multiple queries, each asking whether there is a majority
candidate (occurs > 50%) in a given range. Optimize for large number of queries.
Input:
• Array of votes
Output:
Samples:
Input: [1,1,2,2,1,1]
Query: [1, 4]
Output: -1
Query: [0, 5]
Output: 1
Query: [2, 5]
Output: 1
Given an array A and a jump size J, you must compute the median of every window of size W taken
every J steps. Return the list of medians.
Input:
• Array A
• Integers W and J
Output:
Samples:
Output: [2, 4]
Output: [8,6,4,2]
You are given an array of integers. You can reverse at most one subarray of length exactly K. Return
the lexicographically smallest array possible.
Input:
• Integer array A
• Integer K
Output:
Samples:
makefile
Input: A = [3, 2, 1, 4], K = 3
Output: [1, 2, 3, 4]
Output: [4, 1, 5, 2, 3]
Output: [1, 2, 3, 4]
You are given a string. Repeatedly remove any adjacent pair of characters that are the same (case-
sensitive). Your goal is to return the final string after all such operations.
Input:
• String S
Output:
Samples:
Input: "abccba"
Output: ""
Input: "aabccdee"
Output: "b"
Input: "aabbccddeeffg"
Output: "g"
1) Given the array nums consisting of 2n elements in the form [x₁, x₂, ..., xₙ, y₁, y₂, ..., yₙ]. Return the
array in the form [x₁, y₁, x₂, y₂, ..., xₙ, yₙ].
Parameters:
nums :: LIST<INTEGER>
The array of integers arranged in the pattern [x₁, ..., xₙ, y₁, ..., yₙ]
nums.length == 2n
n :: INTEGER
The integer n such that the first n elements are x's and the next n elements are y's
nums[i] :: 1 → 10³
Case #1
Output: [2,3,5,4,1,7]
Since x₁=2, x₂=5, x₃=1 and y₁=3, y₂=4, y₃=7, the merged result is [2,3,5,4,1,7].
Case #2
Output: [1,4,2,3,3,2,4,1]
Case #3
Output: [1,2,1,2]
Letters are case sensitive, so 'a' is considered a different type of stone from 'A'.
Parameters:
jewels :: STRING
stones :: STRING
Case #1
Output: 3
Jewels are 'a' and 'A'. Stones are 'aAAbbbb'. There are 3 matching jewels: a, A, A.
Case #2
Output: 0
3) You are given an integer array prices where prices[i] is the price of the ith item in a shop.
If you buy the ith item, you receive a discount equivalent to prices[j] where j > i and prices[j] <=
prices[i].
If no such j exists, no discount is applied. Return an array answer where answer[i] is the final price
paid.
Parameters:
prices :: LIST<INTEGER>
prices[i] :: 1 → 1000
Case #1
Output: [4,2,4,2,3]
Discounts applied: 8→4 (discount 4), 4→2, 6→2, no discount for last two.
Case #2
Output: [1,2,3,4,5]
Case #3
Output: [9,0,1,6]
They can only buy one at a time and must return to the end of the line to buy more.
When someone has no more tickets to buy, they leave the queue.
Return the total time taken for the person initially at position k to finish buying their tickets.
Parameters:
tickets :: LIST<INTEGER>
The list representing the number of tickets each person wants to buy
tickets[i] :: 1 → 100
k :: INTEGER
0 <= k < n
Case #1
Output: 6
Case #2
Output: 8
The person at index 0 must cycle through the line several times to buy all 5 tickets.
5) Given the head of a singly linked list, return the middle node.
Parameters:
head :: LIST<INTEGER>
Node.val :: 1 → 100
Case #1
Output: [3,4,5]
Case #2
Output: [4,5,6]
Return the minimum number of streetlights needed to cover the full street, or -1 if not possible.
Parameters:
T :: INTEGER
1 <= T <= 10
N :: INTEGER
M :: INTEGER
Number of streetlights
C :: INTEGER ARRAY
R :: INTEGER
Case #1
Input:
10 4
2468
23
111
Output:
2
1
Case #2
Input:
51
Output:
-1
One light at position 1 can only cover up to 2, which is insufficient to cover all positions 1–5.
Given two integers startValue and target, return the minimum number of operations to reach target.
Parameters:
startValue :: INTEGER
Case #1
Output: 2
Case #2
Output: 2
Case #3
Output: 3
8) You have a 0-indexed binary string s representing white (0) and black (1) balls.
Return the minimum number of swaps needed to group all black balls (1s) to the right side.
Parameters:
s :: STRING
Case #1
Input: s = "101"
Output: 1
Case #2
Input: s = "100"
Output: 2
Case #3
Input: s = "0111"
Output: 0
Parameters:
values :: LIST<INTEGER>
labels :: LIST<INTEGER>
numWanted :: INTEGER
useLimit :: INTEGER
Output: 9
Case #2
Output: 12
Choose 5, 4, 3 (labels: 1, 3, 3)
Case #3
Output: 16
You are given an array tokens, where each token has a value.
Face-up: Lose tokens[i] power, gain 1 score (only if you have enough power).
Face-down: Gain tokens[i] power, lose 1 score (only if your score is at least 1).
Parameters:
tokens :: LIST<INTEGER>
power :: INTEGER
Case #1
Output: 0
Not enough power to play token face-up, and score is 0, so can't play face-down either.
Case #2
Output: 1
Play 100 face-up → power = 50, score = 1. Can't play 200 anymore.
Case #3
Output: 2
Sequence: Play 100 face-up → score 1 → play 400 face-down → gain 400 power → play 200 and 300
face-up → score = 2.
Parameters:
nums :: LIST<INTEGER>
nums[i] :: 0 → 100
Case #1
Output: 167
Case #2
Output: 10
Case #3
Output: 1
12) There is a strange printer that can only print one character at a time.
Parameters:
s :: STRING
Input: s = "aaabbb"
Output: 2
Case #2
Input: s = "aba"
Output: 2
13) You are given an array of boxes with colors represented as positive integers.
In each round, you may remove a group of contiguous boxes of the same color.
Parameters:
boxes :: LIST<INTEGER>
Case #1
Output: 23
Remove 2-2-2 for 9 pts, then 1-1 for 4, then others for 10 → total = 23.
Case #2
Output: 9
Output: 1
You must make exactly k moves, with no more than z left moves.
Parameters:
t :: INTEGER
n :: INTEGER
Length of array
k :: INTEGER
z :: INTEGER
a :: LIST<INTEGER>
Case #1
Input:
540
15432
541
15432
544
10 20 30 40 50
Output:
15
19
150
In the first testcase you are not allowed to move left at all. So you make four moves to the right and
obtain the score a1+a2+a3+a4+a5
In the second example you can move one time to the left. So we can follow these moves: right, right,
left, right. The score will be a1+a2+a3+a2+a3
In the third example you can move four times to the left but it's not optimal anyway, you can just
move four times to the right and obtain the score a1+a2+a3+a4+a5
15) You control a car on an infinite line, starting at position 0 with speed +1.
Given a target, return the shortest instruction sequence length to reach it.
Parameters:
target :: INTEGER
Case #1
Input: target = 3
Output: 2
"AA" → position: 0 → 1 → 3
Case #2
Input: target = 6
Output: 5
"AAARA" → position: 0 → 1 → 3 → 7 → 7 → 6
🧩 DATA STRUCTURES
Q1.
A text editor records your typing and allows you to revert or re-apply your recent changes.
When you undo an action, it remembers what was undone so that you can redo it later.
However, if you type new characters after undoing, the history of undone changes is erased.
Given these conditions, which combination of data structures best models this behaviour?
A) Two queues
B) Two stacks
C) A queue and a stack
D) A linked list and a queue
Q2.
Imagine two independent workers add items to a shared container, while two others remove
items from it. At one moment, all items placed have been taken out, but some workers are
still active.
What data structure and synchronization mechanism is most suitable to manage this scenario
without losing or duplicating items?
Q3.
You have a sequence of opening and closing brackets of various types. You want to confirm
whether the sequence is "well-formed," meaning every opening bracket is closed in the
correct order and type.
Which principle or method can you use to verify this correctness efficiently?
🧩 DATA STRUCTURES
Q1.
Answer: B) Two stacks
Explanation:
Undo/Redo history is best managed using two stacks — one for the undo actions and one for
redo. Undo pops from the undo stack and pushes to the redo stack. Typing new characters
clears the redo stack, which matches the scenario described.
Q2.
Answer: A) Circular buffer with semaphores
Explanation:
Q3.
Answer: B) Use a stack to track the last opened bracket
Explanation:
To verify well-formed bracket sequences, a stack is used to push opening brackets and pop
them when a matching closing bracket is found, ensuring correct order and type.
🌐 COMPUTER NETWORKS
Q4.
A server waits passively for a client to initiate a connection but does not actively attempt to
connect itself. When the client sends a connection request, the server acknowledges it.
What state does the server's connection hold while waiting for this request?
Q5.
A large parcel needs to be delivered across roads that only accept packages up to a certain
size. To complete delivery, the parcel is split into smaller packages, each with identifying
marks so they can be reassembled at the destination.
If the original parcel size is 4000 units and the maximum allowed package size is 1500 units,
how many smaller packages are needed?
A) 2
B) 3
C) 4
D) 5
Q6.
Your phone remembers the physical address of a friend's device to quickly send messages. If
you don't communicate with that friend for more than a minute, your phone forgets their
address.
ANSWERS
Q4.
Answer: B) Listening for incoming connection
Explanation:
The server that passively waits for connection requests is in the “LISTEN” state, ready to
accept incoming client connection requests.
Q5.
Answer: C) 4
Explanation:
(Corrected Answer: B)
Q6.
Answer: A) To save memory by removing unused entries
Explanation:
ARP cache or device address caches expire entries after inactivity to free memory and avoid stale
mappings, which is why the phone forgets the address after no communication.
🖥️ OPERATING SYSTEMS
Q7.
Consider a bakery with a limited number of loafs on a shelf. Bakers put new loaves on the
shelf, and customers take loaves away. The shelf can hold only three loaves at a time. If the
shelf is empty, customers wait; if the shelf is full, bakers wait.
If two bakers put loaves and one customer takes a loaf, how many loafs are left on the shelf
and how many bakers/customers are waiting?
Q8.
A worker frequently moves between rooms, but the rooms are too few compared to the
number of workers, causing constant moving in and out without much actual work done.
Two employees want to update the same document but must ensure no conflicts occur. They
can both read the document simultaneously but writing requires exclusive access.
ANSWERS
Q7.
Answer: B) Two loaves left; no one waiting
Explanation:
Initial shelf capacity = 3 loaves. Two bakers put loaves (2 added), one customer takes one
loaf out → total on shelf = 2. Since shelf capacity not exceeded and not empty, no one waits.
Q8.
Answer: B) Thrashing due to limited resources
Explanation:
Constant moving without work reflects thrashing — frequent swapping or resource
contention causing performance degradation.
Q9.
Answer: B) Use shared locks for reading and exclusive locks for writing
Explanation:
Readers-writers lock allows concurrent reads but exclusive write access, preventing conflicts
and ensuring data consistency.
Q2.
A scenario requires you to efficiently merge two sorted linked lists while preserving order.
What’s the best approach?
A) Concatenate then sort
B) Use two pointers to merge in O(n) time
C) Insert elements of one list into the other using binary search
D) Convert to arrays then merge
Answer: B
Q3.
A messaging app requires messages to be delivered in the order they were sent but can
tolerate delays. Which queue variant best suits this?
A) Priority Queue
B) Circular Queue
C) FIFO Queue
D) Deque
Answer: C
Q4.
You need a data structure that supports inserting and deleting elements at both ends
efficiently and also allows access from the middle. Which would you use?
A) Array
B) Deque implemented with doubly linked list
C) Stack
D) Binary Heap
Answer: B
Q5.
Which data structure would best support autocomplete suggestions by prefix matching for a
large dictionary?
A) Hash Map
B) Trie
C) Linked List
D) Graph
Answer: B
Q6.
An algorithm requires frequent insertions and deletions at arbitrary positions but low memory
overhead. Which linked list variant suits this?
A) Singly Linked List
B) Doubly Linked List
C) Circular Linked List
D) XOR Linked List
Answer: D
Q7.
To implement undo-redo functionality with time and space efficiency, which data structure
pair is most appropriate?
A) Two stacks
B) Two queues
C) One stack, one queue
D) One doubly linked list
Answer: A
Q8.
A system requires real-time task scheduling by priority. Tasks can be dynamically added and
removed. Which data structure is ideal?
A) Max Heap
B) Queue
C) Stack
D) Linked List
Answer: A
Q9.
You must detect if a directed graph contains cycles. Which algorithm or data structure helps
best?
A) Depth-first search with recursion stack
B) Breadth-first search
C) Disjoint Set Union
D) Topological sort on undirected graph
Answer: A
Q10.
Which structure best models an organization hierarchy where each employee can have
multiple subordinates but only one manager?
A) Binary Tree
B) General Tree
C) Graph
D) Linked List
Answer: B
🖥️ OPERATING SYSTEMS
Q11.
A process moves from ready to running state and back repeatedly because of a timer
interrupt, ensuring fair CPU sharing. What scheduling method is this?
A) First-Come-First-Served
B) Round Robin
C) Priority Scheduling
D) Multilevel Queue
Answer: B
Q12.
A system uses pages and segments for memory management, combining the benefits of both.
This is called:
A) Paging
B) Segmentation
C) Segmented Paging
D) Virtual Memory
Answer: C
Q13.
A process is waiting indefinitely because other processes hold resources it needs, and the
resources are waiting on each other. Which technique can prevent this?
A) Lock-free programming
B) Deadlock detection and recovery
C) Avoidance algorithms like Banker’s
D) Priority inversion
Answer: C
Q14.
In an OS, which of these avoids starvation by gradually increasing the priority of waiting
processes?
A) Aging
B) Thrashing
C) Context Switching
D) Swapping
Answer: A
Q15.
When a page fault occurs, what happens next?
A) The page is read from disk into memory
B) The process is terminated immediately
C) The OS ignores the fault
D) The CPU is reset
Answer: A
Q16.
Which synchronization tool allows only one thread to enter a critical section at a time?
A) Semaphore
B) Mutex
C) Barrier
D) Spinlock
Answer: B
Q17.
An OS monitors CPU, memory, and I/O resources and dynamically allocates them among
processes based on priority and demand. What is this called?
A) Multiprogramming
B) Resource Allocation
C) Process Scheduling
D) Memory Management
Answer: B
Q18.
Which condition is NOT necessary for deadlock?
A) Mutual exclusion
B) Hold and wait
C) Circular wait
D) Preemption
Answer: D
Q19.
In multithreaded programs, which condition causes two or more threads to wait forever for
resources?
A) Starvation
B) Deadlock
C) Race Condition
D) Livelock
Answer: B
Q20.
What is the OS feature that allows programs to use more memory than physically available?
A) Virtual Memory
B) Segmentation
C) Paging
D) Swapping
Answer: A
🌐 COMPUTER NETWORKS
Q21.
A client sends a message to a server using UDP, but the message gets lost. Why?
A) UDP is connectionless and unreliable
B) TCP guarantees delivery
C) DNS failure
D) IP routing error
Answer: A
Q22.
Which layer of the OSI model handles encryption and decryption?
A) Application
B) Presentation
C) Network
D) Transport
Answer: B
Q23.
When a device gets an IP address automatically in a network, it uses which protocol?
A) DNS
B) DHCP
C) ARP
D) ICMP
Answer: B
Q24.
A firewall filters packets based on IP addresses and ports. At which layer does this filtering
mostly happen?
A) Physical
B) Network
C) Transport
D) Data Link
Answer: C
Q25.
What is the primary purpose of ARP (Address Resolution Protocol)?
A) Map IP addresses to MAC addresses
B) Resolve domain names to IP addresses
C) Route packets
D) Detect network errors
Answer: A
Q26.
Which protocol is best suited for real-time video streaming?
A) TCP
B) UDP
C) FTP
D) SMTP
Answer: B
Q27.
How does a switch differ from a hub?
A) Switches forward packets to specific ports; hubs broadcast to all ports
B) Hubs route packets; switches only connect devices
C) Switches operate at Physical layer; hubs at Data Link layer
D) Hubs encrypt data; switches do not
Answer: A
Q28.
What technique reduces collisions in Ethernet?
A) CSMA/CD
B) Token Passing
C) ARP
D) Routing
Answer: A
Q29.
Which protocol handles error reporting in IP networks?
A) TCP
B) UDP
C) ICMP
D) ARP
Answer: C
Q30.
When you type a URL, which protocol first resolves it to an IP address?
A) DHCP
B) DNS
C) HTTP
D) FTP
Answer: B
◻ DESIGN AND ANALYSIS OF ALGORITHMS
Q31.
An algorithm uses divide-and-conquer, breaking the problem into two halves recursively.
What is its likely complexity?
A) O(n)
B) O(n log n)
C) O(n²)
D) O(log n)
Answer: B
Q32.
Which sorting algorithm is best for nearly sorted data?
A) QuickSort
B) Bubble Sort
C) Insertion Sort
D) Merge Sort
Answer: C
Q33.
An algorithm has a best case of O(n), average case O(n²). Which is it?
A) QuickSort
B) Merge Sort
C) Heap Sort
D) Counting Sort
Answer: A
Q34.
What technique improves performance by storing results of expensive function calls?
A) Memoization
B) Greedy Algorithm
C) Divide and Conquer
D) Brute Force
Answer: A
Q35.
What algorithmic approach tries all possible solutions to find the best?
A) Greedy
B) Dynamic Programming
C) Backtracking
D) Divide and Conquer
Answer: C
Q36.
You have a weighted graph. Which algorithm finds shortest paths from a single source to all
nodes?
A) Kruskal’s
B) Dijkstra’s
C) Prim’s
D) BFS
Answer: B
Q37.
Which data structure helps achieve O(1) average time complexity for insert, delete, and
search?
A) Array
B) Linked List
C) Hash Table
D) Binary Search Tree
Answer: C
Q38.
What technique reduces an exponential time brute force algorithm to polynomial time?
A) Greedy
B) Divide and Conquer
C) Dynamic Programming
D) Backtracking
Answer: C
Q39.
Which algorithm is NOT comparison-based?
A) QuickSort
B) Merge Sort
C) Counting Sort
D) Heap Sort
Answer: C
Q40.
For graphs with negative weights but no negative cycles, which shortest path algorithm is
suitable?
A) Dijkstra’s
B) Bellman-Ford
C) Floyd-Warshall
D) Prim’s
Answer: B
Q41.
You want to enforce that no two rows in a table have the same email. Which constraint
should you use?
A) Primary Key
B) Foreign Key
C) Unique Key
D) Check Constraint
Answer: C
Q42.
Which normal form removes transitive dependencies?
A) 1NF
B) 2NF
C) 3NF
D) BCNF
Answer: C
Q43.
In SQL, which command is used to create a new table?
A) INSERT
B) CREATE
C) SELECT
D) UPDATE
Answer: B
Q44.
Which of the following is NOT an ACID property?
A) Atomicity
B) Consistency
C) Isolation
D) Durability
E) Scalability
Answer: E
Q45.
Which index type is best for range queries?
A) Hash Index
B) B-Tree Index
C) Bitmap Index
D) No index
Answer: B
Q46.
What type of join returns all rows from both tables, matching where possible, filling with
NULLs if no match?
A) Inner Join
B) Left Join
C) Right Join
D) Full Outer Join
Answer: D
Q47.
Which SQL statement removes rows from a table but does not log individual row deletions for
rollback?
A) DELETE
B) TRUNCATE
C) DROP
D) UPDATE
Answer: B
Q48.
In transaction management, what prevents concurrent transactions from interfering?
A) Locking
B) Indexing
C) Normalization
D) Backup
Answer: A
Q49.
Which database type stores data in key-value pairs?
A) Relational
B) NoSQL
C) Object-oriented
D) Graph
Answer: B
Q50.
When designing a database, what’s the purpose of normalization?
A) Speed up queries
B) Eliminate redundancy and anomalies
C) Increase disk space
D) Encrypt data
Answer: B
1)
You are given a binary string S of length N. Your task is to generate a new binary string T of the same
length such that each corresponding character of T is different from the character at the same position in
S.
In other words, for each position ii (0≤i<N), the following condition must hold Ti≠Si.
Input Format
• The first line of input will contain a single integer T, denoting the number of test cases.
o The first line of each test case contains one integer N — the length of S.
Output Format
For each test case, output on a new line a binary string T of length NN, where Ti≠Si for all valid indices i.
Constraints
• 1≤T≤10^5
• 1≤N≤10
Sample 1:
Input
101
0011
Output:
1
010
1100
Explanation:
Test case 4: T→T[1100], since T0≠S0, T1≠S1, T2≠S2 and T3≠S3, T is a valid output.
2)
You are given a permutation P of length N. You are allowed to perform the following operation any
number of times:
• Choose any two numbers Pi and Pj such that the number of set bits (1s in their binary
representation) is the same, and swap them.
Determine if it is possible to sort the permutation in ascending order using this operation. If possible,
print Yes; otherwise, print No.
Input Format
• The first line of input will contain a single integer T, denoting the number of test cases.
o The first line of each test case contains a single integer N, denoting the length of the permutation
P.
o The second line contains NN space-separated integers P1,P2,P3,…,PN, denoting the permutation
P.
Output Format
For each test case, output on a new line the answer — YES it is possible to sort P in ascending order using
this operation, and NO otherwise.
Constraints
• 1≤T≤10^5
• 1≤N≤2⋅10^5
• P is a permutation of {1,2,3,…N}
• The sum of N over all test cases does not exceed 5⋅10^5
Sample 1:
Input
21
312
4132
Output
Yes
Yes
No
Yes
Explanation:
Test case 2: : We can swap P1 and P2 because both have exactly one 1 in their binary representations.
Test case 4: :
• We can swap P2 and P4 because both have exactly one 1 in their binary representations
[4,1,3,2]→i=2,j=4 -> [4,2,3,1]
• We can swap P1 and P4 because both have exactly one 1 in their binary representations
[4,2,3,1]→i=1,j=4 -> [1,2,3,4]
3)
There are N identical water bottles, each of which has a capacity of X liters.
The ith bottle initially contains Ai liters of water.
You want to go on a trip and want to carry all your water with you.
However, to not make packing a hassle, you also want to carry the least number of bottles with you.
You can transfer any amount of water from one bottle to another, provided there is no spillage and no
bottle contains more than X liters. Water from one bottle can be transferred to different bottles if you
wish to do that.
What is the minimum number of bottles that you can carry with you, while still having all your water?
Input Format
• The first line of input will contain a single integer T, denoting the number of test cases.
o The first line of each test case contains two space-separated integers N and X — the number of
bottles and capacity of each bottle in liters, respectively.
o The second line contains N space separated integers A1,A2,…,AN denoting the volume of water in
liters filled in each bottle.
Output Format
For each test case, output on a new line the minimum number of bottles that can be carried.
Constraints
• 1≤T≤100
• 1≤N≤100
• 1≤X≤1000
• 1≤Ai≤X
Sample 1:
Input
3 10
123
42
1221
Output
1
3
Explanation:
Test case 1: Transfer all the water from the second and third bottles into the first bottle.
The first bottle will now contain 6 liters of water (which is within its capacity of X=10), while the second
and third bottles will be empty.
Test case 2: Transfer one liter of water from the first bottle to the fourth bottle. The bottles now have
[0,2,2,2] liters of water.
We'll take only the second, third, and fourth bottles - for three in total.
4)
Toofan wanted to write the string "ADVITIYA", but accidentally wrote the 8-letter string S instead. He
wants to correct his mistake with the minimum number of steps.
In one step, Toofan can choose an index ii (1≤i≤N), and change Si to the next letter in the alphabet.
Find the minimum number of steps required to convert the string S into "ADVITIYA".
Input Format
• The next T lines each contain a string S consisting of exactly 8 uppercase English letters.
Output Format
• For each test case, output a single integer on a new line — the minimum number of steps to
convert S into "ADVITIYA".
Constraints
• 1≤T≤1000
• S has length 8.
Sample 1:
Input
ADVITIYA
ADVITIAA
Output
24
Explanation:
Test case 2: "ADVITIAA" can be turned into "ADVITIYA" in 24 steps, by repeatedly operating on the 7-th
character.
That is, "ADVITIAA" becomes "ADVITIBA", then "ADVITICA", then "ADVITIDA", and so on till it reaches
"ADVITIYA".
5)
Chef has X ones (1s) and Y twos (2s) in his collection. He wants to arrange all of them into the smallest
possible palindrome number using all of these ones (1s) and twos (2s).
________________________________________
A palindromic number is a number that remains the same when its digits are reversed.
Input Format
• The first line of input will contain a single integer T, denoting the number of test cases.
• The first and only line of each test case will contain two space-separated integers X, and Y — the
amount of ones (1s) and twos (2s) respectively.
Output Format
For each test case, output on a new line the smallest possible palindrome number using X ones (1s) and Y
twos (2s).
Constraints
• 1≤T≤50
• 0≤X,Y≤10
• 2≤X+Y≤10
Sample 1:
Input
20
22
Output
11
1221
Explanation:
Test case 1: The only palindrome number that can be formed using 2 ones (1s) is 11.
Test case 22: Two possible palindromic numbers can be formed using 2 ones (1s) and 2 twos (2s) which
are 1221 and 2112.
The smaller palindromic number is 1221, so that is the answer for this case.
You are playing a mobile game with B% battery on your phone. There are N power moves available in the
game, and each move drains Ci percent of the battery.
You can perform each power move at most 2 times, because they have cooldown restrictions.
You want to know the minimum number of power moves required to fully drain your battery (i.e., battery
becomes 0 or below). If it is not possible even after using each move 2 times, return -1.
Input Format:
• First line: An integer B — initial battery percentage.
1 ≤ B ≤ 10^5
1 ≤ N ≤ 10^5
• Next N lines: Each line contains an integer Ci — battery drained by power move i.
1 ≤ Ci ≤ 10^5
Output Format:
Case#: 1
Input:
Output:
Explanation:
Use 2nd move (4) and 1st move (2) → 4 + 4 = 8 → Battery becomes -1
2 moves
Case#: 2
Input:
15
Output:
-1
Explanation:
import java.util.*;
moves.add(drain);
moves.add(drain);
}
// Sort descending to use max battery drain moves first
moves.sort(Collections.reverseOrder());
int remainingBattery = B;
int count = 0;
remainingBattery -= move;
count++;
if (remainingBattery <= 0)
return count;
return -1;
int B = scanner.nextInt();
int N = scanner.nextInt();
int[] C = new int[N];
C[i] = scanner.nextInt();
System.out.println("Output:");
System.out.println(result);
Problem Statement:
In the Kingdom of Light, G guardians are assigned to protect against M monsters invading in a line.
Each guardian has the same power level P, while each monster has an individual strength Si.
Battle Rules:
• If a guardian's current power > Si: the monster is defeated, and the guardian loses Si power.
• If a guardian's current power == Si: both guardian and monster are eliminated.
• If a guardian's current power < Si: the guardian is eliminated. The monster continues to the next
guardian (with its full health).
You can only remove monsters from the end to ensure the guardians win.
Task: Determine the minimum number of monsters to remove from the end to guarantee that all
remaining monsters can be defeated by the available guardians.
If the last guardian defeats or ties with the last monster, that counts as a victory.
Input Format:
Output Format:
An integer indicating the **minimum number of monsters to remove from the end**
Java Program:
import java.util.*;
// Simulate battles with a trimmed monster list (removing 'trim' monsters from end)
int guardians = G;
int power = P;
{
power -= strength;
i++;
guardians--;
power = P;
i++;
else
guardians--;
power = P;
return true;
if (canDefeatAll(monsters, G, P, mid))
ans = mid;
high = mid - 1;
else
low = mid + 1;
return ans;
int M = sc.nextInt();
int G = sc.nextInt();
int P = sc.nextInt();
monsters[i] = sc.nextInt();
}
Test Cases:
Case #1:
Input:
21543
Output:
Case #2:
Input:
333222
Output:
Case #3:
Input:
5246
Output:
Problem Statement:
You are given an array A of size N. You are allowed to perform at most one swap of two elements within
at most K positions of each other (i.e., |i - j| ≤ K).
Your task is to find the lexicographically largest array possible after performing such a swap (or no swap at
all).
Lexicographical Maximum:
An array X is said to be lexicographically larger than array Y if for the first differing position, Xi > Yi.
Input Format:
Output Format:
N integers representing the lexicographically largest array possible after at most one allowed swap
Java Program:
import java.util.*;
int N = A.length;
int maxIndex = i;
maxVal = A[j];
maxIndex = j;
}
// If a better value is found within range, swap and return
if (maxIndex != i)
A[i] = A[maxIndex];
A[maxIndex] = temp;
return A;
int N = sc.nextInt();
A[i] = sc.nextInt();
}
System.out.println("Enter max distance K:");
int K = sc.nextInt();
System.out.println("Resulting array:");
System.out.println(val);
Test Cases:
Case#: 1
Input:
12345
Output:
32145
Case#: 2
Input:
4321
3
Output:
4321
Case#: 3
Input:
514236
Output:
614235
Case#: 4
Input:
97543
Output:
97543
Problem Statement:
You are given an array Arr representing N dishes in a restaurant. Each value in the array denotes a dish
type.
Your friend can eat dishes in multiple rounds under the following rules:
1. In each round, your friend can only eat dishes of a single type (no mixing types).
2. The number of dishes in the next round must be strictly greater than the number of dishes in the
previous round.
3. Your friend cannot eat the same dish type again in another round.
Your task is to find the maximum number of dishes your friend can eat by following the rules above.
Input Format:
Output Format:
Java Program:
import java.util.*;
Collections.sort(counts);
int lastEaten = 0;
int totalEaten = 0;
totalEaten += count;
lastEaten = count;
lastEaten++;
totalEaten += lastEaten;
} else {
return totalEaten;
arr[i] = sc.nextInt();
Test Cases:
Case#1
Input:
1223333
Output:
Explanation:
Case#2
Input:
11122
Output:
5
Explanation:
Case#3
Input:
1111
Output:
Case#4
Input:
22223333
Output:
Explanation:
Problem Statement:
You are given a string S of length N. Your task is to divide the string into the maximum number of
contiguous substrings such that each substring contains the same frequency of characters as all the
others.
Unlike the previous problem, you cannot rearrange the characters. The substrings must appear in order,
and must be contiguous and have the same frequency map.
Input Format:
Output Format:
Test Cases:
Case#1:
Input:
aaabbbccc
Output:
Explanation: Split into "aaa" + "bbb" + "ccc" – each substring contains one character repeated three times.
Case#2:
Input:
abcabcabc
Output:
Explanation: Each substring "abc" has the same frequency map {a:1, b:1, c:1}
Case#3:
Input:
ababab`
Output:
3
Java Solution:
import java.util.*;
int n = s.length();
if (n % len != 0) continue;
if (!getFreq(part).equals(baseFreq)) {
valid = false;
break;
if (valid) {
return n / len;
return 1;
return map;
String s = sc.next();
maxBalancedSubstrings(s));
Test Cases
Case#1
Input:
aaabbbccc
Output:
Case#2
Input:
abcabcabc
Output:
Case#3
Input:
ababab
Output:
Case#4
Input:
abcdabcd
Output:
Case#5
Input:
zzzzzz
Output:
1. You're given n activities with start and end times. Select the maximum number of activities that
don't overlap. Only one activity can be selected at a time.
Output: 2
Output: 3
count = 1
end_time = activities[0][1]
count += 1
end_time = activities[i][1]
return count
# Test
2. Given coin denominations and a total amount, find the minimum number of coins needed to
make that amount using a greedy approach.
Output: 4
Output: 6
coins.sort(reverse=True)
count = 0
amount %= coin
return count
# Test
3. Each job has a profit and a deadline. Schedule jobs to maximize total profit, allowing only one job
at a time before its deadline.
Input: jobs = [(1, 4), (2, 1), (3, 1), (4, 1)]
Output: 6
Input: jobs = [(20, 2), (15, 2), (10, 1), (5, 3)]
Output: 40
Input: jobs = [(100, 2), (19, 1), (27, 2), (25, 1)]
Output: 127
def job_scheduling(jobs):
jobs.sort(reverse=True)
max_deadline = max(job[1] for job in jobs)
profit = 0
if not slots[j]:
slots[j] = True
profit += job[0]
break
return profit
# Test Cases
4. Find the length of the longest common subsequence between two strings.
Output: 4
Output: 4
Output: 3
for i in range(n):
for j in range(m):
if s1[i] == s2[j]:
dp[i+1][j+1] = dp[i][j] + 1
else:
return dp[n][m]
# Test Cases
print(lcs("ABCBDAB", "BDCABA")) # 4
print(lcs("AGGTAB", "GXTXAYB")) # 4
print(lcs("ABCDGH", "AEDFHR")) # 3
5. Given n items with weights and values, and a knapsack capacity W, return the maximum value
obtainable. Items cannot be split.
Input: W = 50, weights = [10, 20, 30], values = [60, 100, 120]
Output: 220
Output: 80
Output: 100
n = len(values)
dp = [[0] * (W + 1) for _ in range(n + 1)]
for w in range(W+1):
if weights[i-1] <= w:
else:
dp[i][w] = dp[i-1][w]
return dp[n][W]
# Test Cases
HACKWITHINFY 6 QUESTIONS
1. You have an interesting string S of length N. It is interesting because you can rearrange the characters
of this string in any order. You want to cut this string into some contiguous pieces such that after cutting,
all the pieces are equal.
You can’t rearrange the characters in the cut pieces or join the pieces together. You want to make the
number of pieces as large as possible. What is the maximum number of pieces you can get?
Note: You can observe that you may not want to cut the string at all, therefore the number of pieces is 1.
Hence, the answer always exists.
Parameters:
• S :: STRING
The first line contains a string, S, denoting the string. len(S) :: 1 -> 2 * 10^5
Examples:
Case #1:
Input:
zzzzz
Output:
Explanation: You can cut it into 5 pieces “z” + “z” + “z” + “z” + “z”.
Case #2:
Input:
ababcc
Output:
Explanation: Rearrange the string as abcabc. You can cut it into “abc” + “abc”, hence the answer is 2.
Case #3:
Input:
abccdcabacda
Output:
Solution :
JAVA
import java.util.*;
freq[c - 'a']++;
int gcd = 0;
if (f > 0) {
return gcd;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
return a;
System.out.println(maxPieces("zzzzz"));
System.out.println(maxPieces("ababcc"));
System.out.println(maxPieces("abccdcabacda"));
}
PYTHON
freq = Counter(s)
frequencies = list(freq.values())
# Test cases
def run_tests():
test_cases = [
result = max_pieces(test)
print(f"Input: {test}")
print(f"Output: {result}\n")
if __name__ == "__main__":
run_tests()
#include <stdio.h>
#include <string.h>
while (b) {
int temp = b;
b = a % b;
a = temp;
return a;
return result;
}
// Main function to find maximum number of equal pieces
freq[s[i] - 'a']++;
int first_non_zero = 0;
first_non_zero++;
if (freq[i] > 0) {
}
return result;
int main() {
// Test cases
"zzzzz",
"ababcc",
"abccdcabacda"
};
int num_tests = 3;
return 0;
C++
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <numeric>
private:
// Helper function to find GCD of two numbers using C++'s standard library
if (numbers.empty()) return 0;
return result;
public:
for (char c : s) {
freq[c]++;
if (count > 0) {
frequencies.push_back(count);
return findArrayGCD(frequencies);
};
void runTests() {
vector<string> testCases = {
"zzzzz",
"ababcc",
"abccdcabacda"
};
StringCutter solver;
}
int main() {
runTests();
return 0;
2. You are given an array A of size N. You are allowed to choose at most one pair of elements such that
distance (defined as the difference of their indices) is at most K and swap them.
Notes: An array x is lexicographically smaller than an array y if there exists an index i such that xi<yi, and
xj=yj for all 0≤j<i. Less formally, at the first index i in which they differ, xi<yi.
Parameters:
N :: INTEGER
N :: 1 -> 10^5
A :: INTEGER ARRAY
Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing A[i].
The next line contains an integer, K, denoting the upper bound on distance of index.
K :: 1 -> N
Example Cases:
Case #1
Input:
Output:
2
2
Here, as all the array values are equal, swapping will not change the final result.
Case #2
Input:
Output:
Here, A = [5, 4, 3, 2, 1], K = 3. We can swap elements at index 0 and index 3 to get A = [2, 4, 3, 5, 1].
Case #3
Input:
3
Output:
Here, A = [2, 1, 1, 1, 1], K = 3. We can swap elements at index 0 and index 3 to get A = [1, 1, 1, 2, 1].
Solution:
JAVA
import java.util.*;
int N = A.length;
int minIndex = i;
minValue = result[j];
minIndex = j;
}
// We only need to make one swap to get the lexicographically smallest array
if (minIndex != i) {
result[i] = result[minIndex];
result[minIndex] = temp;
break;
return result;
// Test cases
PYTHON
"""
Find the lexicographically smallest array possible after at most one swap
within distance K.
Args:
Returns:
list: The lexicographically smallest possible array after at most one swap
"""
N = len(A)
result = A.copy()
for i in range(N):
min_value = result[i]
min_index = i
min_value = result[j]
min_index = j
# We only need to make one swap to get the lexicographically smallest array
if min_index != i:
break
return result
print(f"K: {K}")
result = find_smallest_lex_array(A, K)
print(f"Result: {result}")
return result
# Test cases
def run_test_cases():
test_case([1, 2, 3, 4, 5], 2)
if __name__ == "__main__":
run_test_cases()
#include <stdio.h>
#include <stdlib.h>
printArray(A, N);
findSmallestLexArray(A, N, K, result);
printf("Result: ");
printArray(result, N);
free(result);
int main() {
testCase(test1, 3, 1);
testCase(test2, 5, 3);
testCase(test3, 5, 3);
return 0;
C++
#include <iostream>
#include <vector>
#include <algorithm>
class LexicographicalArray {
private:
std::vector<int> A;
int K;
int N;
public:
// Constructor
N = A.size();
std::vector<int> findSmallestLexArray() {
int minIndex = i;
minValue = result[j];
minIndex = j;
}
if (minIndex != i) {
std::swap(result[i], result[minIndex]);
break;
return result;
};
class TestRunner {
public:
LexicographicalArray::printArray(arr);
std::cout << "K: " << k << std::endl;
LexicographicalArray::printArray(result);
};
int main() {
TestRunner::runAllTests();
return 0;
3. You are the guard of a shop. Each time a person enters you not this informations.
You are given information of people leaving and entering shop in the form of binary string.
It is given that a person can enter or leave the shop any number of times.
Using the given info , find minimum possible distinct people you might have seen.
Constraints
1<=len(s)<=10^5
Sample Testcases --
Input-1: 000
Output : 3
Reason : Suppose at t=1, person1 leaves. Then at t=2 , person2 leaves. Then at t=3, Person 3 leaves.
Input-2 : 110011
Output : 2
Reason : At t=1, person1 enters and at t=2 person2 enters the shop . At t=3 , person1 leaves, At t=4,
person2 leaves . At t=5, person1 again enters. At t=6, person2 enter the shop again . Thus the minimum
number of distinct person is 2.
Input-3: 10101
Output : 1
Reason : At t=1, Person1 enters the shop. At t=2, person 1 leaves . At, t=3 person1 enters. At t=4, person1
leaves.
At t=5, person1 enters . The minimum number of distinct person seens are 1.
Solution:
C++
#include <bits/stdc++.h>
int main()
ll one = 0 ;
ll zero = 0 ;
string s ;
cin>>s ;
int i = 0 ;
while(i<s.size())
if(s[i]=='1')
ll k = zero;
if(k>=1)
zero--;
one++;
else
one++;
else
ll k = one;
if(k>=1)
one--;
zero++;
else
zero++;
i++;
cout<<(one+zero);
return 0;
4. Find the subsequence from an array with highest score. Score is the sum of f(x) for all the elements of
the subsequence.
f(x) = number of divisors of 'x'.
For , a[i] and a[i+1] in the selected subsequence , one of the following should be true :
a[i] = 2*a[i+1]
or
a[i] = 3*a[i+1]
or
or
or
Input :
10
2 3 4 5 6 12 18 36 9 99
Output :
28
Solution:
C++
#include <bits/stdc++.h>
ll divi[200006];
ll fin[200005];
void findDivisors(ll n)
{
for (int i = 1; i <= n; i++) {
divi[i * j]++;
int main()
ll r = 0 ;
int n = 100000+7;
findDivisors(n);
cin>>n;
int i = 1 ;
while(i<=n)
int x ;
cin>>x ;
ll current = divi[x] ;
ll maxi = 0 ;
if(x%2==0)
maxi = max(maxi,fin[x/2]);
if(x%3==0)
maxi = max(maxi,fin[x/3]);
maxi = max(maxi,fin[x-1]);
maxi = max(maxi,fin[x+1]);
maxi = max(maxi,fin[2*x]);
maxi = max(maxi,fin[3*x]);
fin[x] = max(fin[x],answer);
//cout<<fin[x]<<'\n';
r = max(fin[x],r);
i++;
cout<<r ;
return 0;
GREEDY ALGORITHM
5. Fathima has a numeric string. She has to split the numeric string into two or more integers, such that
If it is possible to separate a given numeric string then print “Possible” followed by the first number of the
increasing sequence, else print “Not Possible“
For Ex:
Case 1 :
Output: Possible 79
Case 2:
String can be splitted into '1','2' and '4''. The difference between 1 and 2 is 1, but 2 and 4 is 2. So it can't
satisfy the condition. The output will be "Not Possible"
Input Format
Input the String( Which contains only numbers. Alphabets and Special characters are not allowed)
Output Format
Display "Possible" followed by the first number of the increasing sequence. If not display "Not Possible"
Constraints
Sample Input 1
7980
Sample Output 1
Possible79
Solution:
JAVA
// string in an Increasing
// sequence if possible
import java.io.*;
import java.util.*;
class GFG {
if (len == 1) {
System.out.println("Not Possible");
return;
int flag = 0;
s1 = str.substring(0, i + 1);
num1 = Long.parseLong((s1));
num2 = num1 + 1;
// back to string s2
s2 = Long.toString(num2);
int k = i + 1;
while (flag == 0) {
int l = s2.length();
// if s2 is not a substring
if (k + l > len) {
flag = 1;
break;
if ((str.substring(k, k + l).equals(s2))) {
flag = 0;
num2++;
k = k + l;
if (k == len)
break;
s2 = Long.toString(num2);
l = s2.length();
if (k + 1 > len) {
flag = 1;
break;
else
flag = 1;
if (flag == 0) {
System.out.println("Possible"
break;
System.out.println("Not Possible");
break;
// Driver Code
public static void main(String args[])
String str;
str =in.next();
split(str);
Dynamic Programming
6. The Revolutionary group in Germany have decided to destroy the House of Hitler. There are two
Revolutionary groups in Germany, and person of each Revolutionary group has a unique String ID
associated with him/her . The first group is of size N, and the second group is of size M. Let the array of
String ID's of first group be denoted by A [ ], and that of second group be denoted by B [ ] .
Hitler has decoded the pattern of these Revolutionary groups, and has decided to stop the chaos. He will
choose an equal size subarray from both the arrays.
So, let the subarray from the first group array A [ ] be Ai, Ai+1, …. Ai+X-1.
And, let the subarray from the second array B [ ] be Bj, Bj+1, ….Bj+X-1.
• Find Longest Common substring (LCS) of Ai+u and Bj+X-1-u , where 0<=u<=X-1.
You need to help the Government in finding all possible number of combinations of equal sized subarrays
in A [ ] and B[ ] which are satisfying the above mentioned condition.
Two combinations are different if they are of different size, or in case atleast one constituent index is
different.
Input Format
First line contains 2 space separated integers N and M, denoting the size of two arrays A[ ] and B [ ]
respectively.
Output Format
Constraints
1 ≤ N,M ≤ 2000
1 ≤ | Ai | ≤ 5000
1 ≤ | Bi | ≤ 5000
1 ≤ K ≤ 5000
Sample Input 1
33
aab
aba
jgh
bad
dea
cef
Sample Output 1
Solution:
C++
#include <bits/stdc++.h>
#define pb push_back
int a[2005][2005];
int lft[2005][2005];
int rght[2005][2005];
int up[2005][2005];
int dwn[2005][2005];
int diagUp[2005][2005];
int diagDwn[2005][2005];
int i, j;
for (i = 0, j = 0; i < seg[p].size() && j < seg[q].size(); ) {
seg[ind].pb(seg[p][i]);
++i;
else {
seg[ind].pb(seg[q][j]);
++j;
seg[ind].pb(seg[p][i]);
++i;
seg[ind].pb(seg[q][j]);
++j;
seg[ind].clear();
if (l == r) {
seg[ind].pb(v2[l]);
return;
int m = (l+r)/2;
int p = 2*ind;
int q = p+1;
create_seg_tree(l, m, p);
create_seg_tree(m+1, r, q);
merge(p, q, ind);
if (y < l || r < x)
return 0;
int m = (l+r)/2;
int p = 2*ind;
int q = p+1;
int dp[5005][5005];
int i, j, ans = 0;
dp[i][j] = 0;
if (A[x][i-1] == B[y][j-1])
dp[i][j] = dp[i-1][j-1] + 1;
return ans;
int main()
int tmp = 0;
tmp += A[i].size();
tmp = 0;
tmp += B[i].size();
if (!a[i][j])
continue;
up[i][j] = up[i-1][j] + 1;
lft[i][j] = lft[i][j-1] + 1;
diagUp[i][j] = diagUp[i-1][j+1] + 1;
if (!a[i][j])
continue;
dwn[i][j] = dwn[i+1][j] + 1;
rght[i][j] = rght[i][j+1] + 1;
diagDwn[i][j] = diagDwn[i+1][j-1] + 1;
i = size_of_array_A;
j = x;
v1.clear(); v2.clear();
--i;
++j;
v2[i] = i - v2[i] + 1;
j = i + v1[i] - 1;
i = x;
j = 1;
v1.clear(); v2.clear();
--i;
++j;
}
for (i = 0; i < v2.size(); ++i)
v2[i] = i - v2[i] + 1;
j = i + v1[i] - 1;
return 0;
Question 1:
Find the intersection of two sorted arrays OR in other words, given 2 sorted arrays, find all the elements
which occur in both arrays.
NOTE: For the purpose of this problem ( as also conveyed by the sample case ), assume that elements that
appear more than once in both arrays should be included multiple times in the final output.
Problem Constraints
Input Format
Output Format
Input 1:
A: [1 2 3 3 4 5 6]
B: [3 3 5]
Input 2:
A: [1 2 3 3 4 5 6]
B: [3 5]
Example Output
Output 1: [3 3 5]
Output 2: [3 5]
Example Explanation
Explanation 1:
Explanation 2:
Question2:
Where:
Find the minimum number of conference rooms required so that all meetings can be done.
Note :- If a meeting ends at time t, another meeting starting at time t can use the same conference room
Problem Constraints
Input Format
Output Format
Return the minimum number of conference rooms required so that all meetings can be done.
Example Input
Input 1:
[5, 10]
[15, 20]
Input 2:
A= [ [1, 18]
[18, 23]
[15, 29]
[4, 15]
[2, 11]
[5, 13]
Example Output
Output 1:
Output 2:
Example Explanation
Explanation 1:
Meeting one can be done in conference room 1 form 0 - 30.
Meeting three can be done in conference room 2 form 15 - 20 as it is free in this interval.
Explanation 2:
Meeting three can be done in conference room 2 from 15 - 29 as it is free in this interval.
Meeting two can be done in conference room 4 from 18 - 23 as it is free in this interval.
Question3:
You are giving candies to these children subjected to the following requirements:
2. Children with a higher rating get more candies than their neighbors.
Problem Constraints
Input Format
The first and only argument is an integer array A representing the rating of children.
Output Format
Example Input
Input 1:
A = [1, 2]
Input 2:
A = [1, 5, 2, 1]
Example Output
Output 1:
Output 2:
Example Explanation
Explanation 1:
The candidate with 1 rating gets 1 candy and candidate with rating 2 cannot get 1 candy as 1 is its
neighbor.
Explanation 2:
Question 4:
There is a street of length xxx whose positions are numbered 0, 1,…,x Initially there are no traffic lights,
but n sets of traffic lights are added to the street one after another.
Your task is to calculate the length of the longest passage without traffic lights after each addition.
Input
The first input line contains two integers xxx and n: the length of the street and the number of sets of
traffic lights.
Then, the next line contains n integers p1,p2,…,pn: the position of each set of traffic lights. Each position
is distinct.
Output
Print the length of the longest passage without traffic lights after each addition.
Example
Input:
83
362
Output:
533
Question5:
You are given n cubes in a certain order, and your task is to build towers using them. Whenever two cubes
are one on top of the other, the upper cube must be smaller than the lower cube.
You must process the cubes in the given order. You can always either place the cube on top of an existing
tower, or begin a new tower. What is the minimum possible number of towers?
Input
The next line contains nnn integers k1,k2,…,kn: the sizes of the cubes.
Output
Example
Input:
38215
Output:
Problem Statement:
You are given n jobs where every job has a deadline and profit associated with it. Each job takes a single
unit of time, and only one job can be scheduled at a time. Maximize total profit if jobs are scheduled
before their deadlines.
Constraints:
Output Format:
• Two integers: total number of jobs done and total profit earned
Test Case:
Input:
4 20
1 10
1 40
1 30
Output:
2 70
Solution Logic:
• Try placing each job in the latest available time slot before its deadline using a disjoint-set or
simple array for tracking
Python
def job_sequencing(jobs):
count, total_profit = 0, 0
for d, p in jobs:
if not slots[j]:
slots[j] = True
count += 1
total_profit += p
break
n = int(input())
res = job_sequencing(jobs)
print(*res)
Java
import java.util.*;
deadline = d;
profit = p;
int maxDeadline = 0;
Arrays.sort(jobs);
if (!slots[j]) {
slots[j] = true;
count++;
profit += job.profit;
break;
C
#include <stdio.h>
#include <stdlib.h>
typedef struct {
} Job;
int main() {
int n;
scanf("%d", &n);
Job jobs[n];
int maxDeadline = 0;
maxDeadline = jobs[i].deadline;
if (!slots[j]) {
slots[j] = 1;
count++;
profit += jobs[i].profit;
break;
return 0;
Problem Statement:
Given the stock prices for n days and an integer k, find the maximum profit you can make with at most k
transactions. You may not engage in multiple transactions at the same time (i.e., you must sell the stock
before you buy again).
Constraints:
Input Format:
Output Format:
Input:
26
326503
Output:
Solution Logic:
• Use a DP table dp[k+1][n] where dp[i][j] is the max profit using i transactions until day j
Python
n = len(prices)
if n == 0: return 0
max_diff = -prices[0]
return dp[k][n-1]
k, n = map(int, input().split())
print(max_profit(k, prices))
Java
import java.util.*;
int n = prices.length;
if (n == 0) return 0;
return dp[k][n-1];
System.out.println(maxProfit(k, prices));
#include <stdio.h>
int dp[k+1][n];
dp[i][j] = 0;
return dp[k][n-1];
int main() {
int k, n;
int prices[n];
return 0;
Problem Statement:
You're managing a memory block with m units of memory and n processes. Each process has a memory
requirement and a priority value. Allocate memory to as many high-priority processes as possible without
exceeding the total memory m. A process can only be either completely included or excluded.
Constraints:
Input Format:
Output Format:
Test Case:
Input:
4 10
4 70
2 60
6 90
3 30
Output:
160
Solution Logic:
Python
n, m = map(int, input().split())
total_priority = 0
for mem, pri in processes:
if m >= mem:
m -= mem
total_priority += pri
print(total_priority)
Java
import java.util.*;
class Process {
mem = m; pri = p;
double ratio() {
if (m >= p.mem) {
m -= p.mem;
total += p.pri;
System.out.println(total);
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double ratio;
} Process;
double r1 = ((Process*)a)->ratio;
double r2 = ((Process*)b)->ratio;
int main() {
int n, m;
int total = 0;
if (m >= p[i].mem) {
m -= p[i].mem;
total += p[i].pri;
printf("%d\n", total);
return 0;
Problem Statement:
Given a string s and a cost array cost[] where cost[i] is the cost of deleting the i-th character, find the
minimum total deletion cost required to convert the string into a palindrome.
Constraints:
Input Format:
• Line 1: String s
• Line 2: Array cost of size len(s)
Output Format:
Test Case:
Input:
abcbda
123456
Output:
Solution Logic:
Python
s = input()
n = len(s)
j = i + length - 1
if s[i] == s[j]:
dp[i][j] = dp[i+1][j-1]
else:
Java
import java.util.*;
String s = sc.next();
int n = s.length();
int j = i + len - 1;
if (s.charAt(i) == s.charAt(j))
dp[i][j] = dp[i+1][j-1];
else
System.out.println(dp[0][n-1]);
C
#include <stdio.h>
#include <string.h>
int main() {
char s[1001];
scanf("%s", s);
int n = strlen(s);
int j = i + l - 1;
if (s[i] == s[j])
dp[i][j] = dp[i+1][j-1];
else
printf("%d\n", dp[0][n-1]);
return 0;
Problem Statement:
You are given n intervals where each interval has a start time, end time, and an associated weight. Select
a set of non-overlapping intervals such that the total weight is maximized.
This is a classic optimization problem where greedy won't work, and dynamic programming with binary
search or coordinate compression is necessary.
Constraints:
Input Format:
• Line 1: Integer n
Output Format:
Test Case:
Input:
1 3 50
2 5 20
4 6 70
6 7 60
Output:
180
Explanation: Choose intervals (1,3), (4,6), (6,7) with weights 50+70+60 = 180
Solution Logic:
• For each interval i, use binary search to find the last non-overlapping interval j with end[j] <=
start[i]
• Use DP:
Python
import bisect
n = int(input())
dp = [0] * (n + 1)
s, e, w = intervals[i-1]
idx = bisect.bisect_right(ends, s) - 1
print(dp[n])
Java
import java.util.*;
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
return ans;
int n = sc.nextInt();
Arrays.sort(arr);
System.out.println(dp[n]);
}
}
#include <stdio.h>
#include <stdlib.h>
typedef struct {
} Interval;
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
return ans;
int main() {
int n;
scanf("%d", &n);
Interval arr[n];
dp[0] = 0;
printf("%lld\n", dp[n]);
return 0;
Given an array of integers, find the length of the longest strictly increasing subsequence. A subsequence is
a sequence that can be derived from the array by deleting some or no elements without changing the
order of the remaining elements.
Example:
Input:
Output:
Explanation:
Step-by-step:
1. Create a DP array `dp` where `dp[i]` will store the length of the LIS ending at index `i`.
2. Initialize each value in `dp` as 1, because the minimum LIS ending at any element is 1 (the element
itself).
3. For each element `nums[i]`, loop through all previous elements `nums[j]` where `j < i`.
4. If `nums[j] < nums[i]`, then `nums[i]` can extend the subsequence ending at `nums[j]`.
Code (Python):
python
def length_of_lis(nums):
n = len(nums)
for i in range(n):
for j in range(i):
Test Case:
python
Output: 4
Problem-2: Activity Selection Problem (or Interval Scheduling Maximum Subset)
Problem Statement:
You are given `n` activities with their start and end times. Select the maximum number of activities that
can be performed by a single person, assuming that a person can only work on one activity at a time.
Example:
Input:
start = [1, 3, 0, 5, 8, 5]
end = [2, 4, 6, 7, 9, 9]
Output:
Explanation:
3. Select activities such that the start time of the current activity is greater than or equal to the end time
of the last selected activity.
Code (Python):
python
count = 1
last_end = activities[0][1]
count += 1
last_end = activities[i][1]
return count
Test Case:
python
start = [1, 3, 0, 5, 8, 5]
end = [2, 4, 6, 7, 9, 9]
print(activity_selection(start, end))
Output: 4
Problem Statement:
Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has
the **largest sum** and return its sum.
This is the Divide and Conquer version of the famous Kadane's Algorithm problem.
Example:
Input:
Explanation:
The subarray `[4, -1, 2, 1]` has the largest sum = `6`.
2. Recursively find the maximum subarray sum in the left and right halves.
Code (Python):
python
left_sum = float('-inf')
sum_ = 0
sum_ += arr[i]
sum_ = 0
sum_ += arr[i]
if left == right:
return arr[left]
return max(
Wrapper function
def find_max_subarray_sum(nums):
Test Case:
python
Output: 6
Problem Statement:
Given an undirected, weighted graph represented as an adjacency list or matrix, implement Prim's
algorithm to find the minimum cost to connect all nodes (i.e., the total weight of the MST).
Example:
Input:
Number of vertices:
(0, 1, 2)
(0, 3, 6)
(1, 2, 3)
(1, 3, 8)
(1, 4, 5)
(2, 4, 7)
(3, 4, 9)
Output:
Explanation:
The MST includes edges with weights: `2 (0-1)`, `3 (1-2)`, `5 (1-4)`, `6 (0-3)` → total = 16
python
import heapq
for u, v, w in edges:
graph[u].append((w, v))
graph[v].append((w, u))
visited = [False] * n
mst_cost = 0
while min_heap:
weight, u = heapq.heappop(min_heap)
if visited[u]:
continue
mst_cost += weight
visited[u] = True
if not visited[v]:
return mst_cost
Test Case:
python
n=5
edges = [
(0, 1, 2),
(0, 3, 6),
(1, 2, 3),
(1, 3, 8),
(1, 4, 5),
(2, 4, 7),
(3, 4, 9)
Output: 16
Problem Statement:
Given a weighted, directed graph and a source vertex, find the shortest distance from the source to all
other vertices using Dijkstra’s algorithm.
Example:
Input:
Number of vertices: 5
Edges:
(0, 1, 10)
(0, 4, 5)
(1, 2, 1)
(1, 4, 2)
(2, 3, 4)
(3, 0, 7)
(4, 1, 3)
(4, 2, 9)
(4, 3, 2)
Source vertex: 0
Output:
[0, 8, 9, 7, 5]
Explanation:
From node `0`, the shortest paths to nodes `1`, `2`, `3`, and `4` have costs `8`, `9`, `7`, and `5`, respectively.
python
import heapq
for u, v, w in edges:
graph[u].append((v, w))
dist = [float('inf')] * n
dist[source] = 0
while min_heap:
current_dist, u = heapq.heappop(min_heap)
continue
return dist
Test Case:
python
n=5
edges = [
(0, 1, 10),
(0, 4, 5),
(1, 2, 1),
(1, 4, 2),
(2, 3, 4),
(3, 0, 7),
(4, 1, 3),
(4, 2, 9),
(4, 3, 2)
source = 0
Problem Statement:
Given a string s, remove exactly one character such that the resulting string is lexicographically smallest.
Return the modified string.
Input Format:
Output Format:
Input: abcda
Output: abca
Input: aaa
Output: aa
Input: edcba
Output: dcba
Python
def smallestString(s):
for i in range(len(s)-1):
return s[:-1]
# Read input
s = input()
rint(smallestString(s))
Java
import java.util.Scanner;
#include <stdio.h>
#include <string.h>
if (j != i) printf("%c", s[j]);
printf("\n");
int main() {
char s[101];
scanf("%s", s);
smallestString(s);
return 0;
C++
#include <iostream>
int main() {
string s;
cin >> s;
Problem Statement:
Given a number n, count how many numbers from 1 to n have a digit sum divisible by 3.
Input Format:
Output Format:
• A single integer: the count of numbers from 1 to n whose digit sum is divisible by 3.
Input: 15
Output: 5
Input: 20
Output: 6
Input: 30
Output: 10
Python
def countDiv3(n):
n = int(input())
print(countDiv3(n))
Java
import java.util.Scanner;
int count = 0;
temp /= 10;
if (sum % 3 == 0) count++;
return count;
int n = sc.nextInt();
System.out.println(countDiv3(n));
#include <stdio.h>
int digitSum(int n) {
int sum = 0;
while(n) {
sum += n % 10;
n /= 10;
return sum;
int countDiv3(int n) {
int count = 0;
if (digitSum(i) % 3 == 0)
count++;
return count;
int main() {
int n;
scanf("%d", &n);
printf("%d\n", countDiv3(n));
return 0;
C++
#include <iostream>
int digitSum(int n) {
int sum = 0;
while(n) {
sum += n % 10;
n /= 10;
return sum;
int countDiv3(int n) {
int count = 0;
if (digitSum(i) % 3 == 0)
count++;
return count;
int main() {
int n;
cin >> n;
Problem Statement:
You are given a target amount V and an array of coin denominations (e.g., [1, 2, 5, 10, 20, 50, 100, 500,
2000]). Find the minimum number of coins required to make that amount.
Input Format:
Output Format:
Input: 70
Input: 121
Output: 3 // (100 + 20 + 1)
Input: 999
Python
def minCoins(V):
count = 0
for c in coins:
if V == 0:
break
count += V // c
V %= c
return count
print(minCoins(int(input())))
Java
import java.util.Scanner;
int count = 0;
if (V == 0) break;
count += V / coin;
V %= coin;
return count;
int V = sc.nextInt();
System.out.println(minCoins(V));
#include <stdio.h>
int minCoins(int V) {
int coins[] = {2000, 500, 100, 50, 20, 10, 5, 2, 1};
int count = 0;
if (V == 0) break;
count += V / coins[i];
V %= coins[i];
return count;
int main() {
int V;
scanf("%d", &V);
printf("%d\n", minCoins(V));
return 0;
C++
#include <iostream>
int minCoins(int V) {
int count = 0;
if (V == 0) break;
count += V / coin;
V %= coin;
}
return count;
int main() {
int V;
cin >> V;
Problem Statement:
You are given n activities with start and end times. Select the maximum number of activities that can be
performed by a single person, assuming that a person can only work on a single activity at a time.
Input Format:
• Next n lines: Two integers start and end (start time and end time of each activity)
Output Format:
Input:
12
34
06
57
89
59
Output:
4
Explanation:
Input:
10 20
12 25
20 30
Output:
Input:
13
24
35
06
Output:
Python
def activitySelection(activities):
count = 1
last_end = activities[0][1]
count += 1
last_end = activities[i][1]
return count
n = int(input())
print(activitySelection(activities))
Java
import java.util.*;
class Main {
int count = 1;
count++;
end = arr[i][1];
return count;
}
public static void main(String[] args) {
int n = sc.nextInt();
activities[i][0] = sc.nextInt();
activities[i][1] = sc.nextInt();
System.out.println(activitySelection(activities));
#include <stdio.h>
#include <stdlib.h>
typedef struct {
} Activity;
int main() {
int n;
scanf("%d", &n);
Activity acts[n];
count++;
last_end = acts[i].end;
printf("%d\n", count);
return 0;
C++
#include <iostream>
#include <vector>
#include <algorithm>
struct Activity {
};
bool compare(Activity a, Activity b) {
int main() {
int n;
cin >> n;
vector<Activity> acts(n);
int count = 1;
count++;
last_end = acts[i].end;
You are given n jobs. Each job has an ID, a deadline, and a profit. Only one job can be scheduled at a time.
A job earns profit only if it is finished on or before its deadline. Schedule jobs to maximize total profit.
Input Format:
Output Format:
Input:
a 4 20
b 1 10
c 1 40
d 1 30
Output:
2 70
Input:
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output:
3 142
Input:
x 3 10
y 2 20
z 1 30
Output:
2 50
Python
def jobSequencing(jobs):
profit, count = 0, 0
if not slots[j]:
slots[j] = True
count += 1
profit += job[2]
break
res = jobSequencing(jobs)
print(res[0], res[1])
Java
import java.util.*;
class Job {
String id;
this.id = id;
this.deadline = d;
this.profit = p;
int maxDeadline = 0;
if (!slot[j]) {
slot[j] = true;
count++;
profit += job.profit;
break;
int n = sc.nextInt();
String id = sc.next();
int d = sc.nextInt();
int p = sc.nextInt();
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char id[2];
} Job;
int main() {
int n;
scanf("%d", &n);
Job jobs[n];
int max_deadline = 0;
max_deadline = jobs[i].deadline;
memset(slot, 0, sizeof(slot));
if (!slot[j]) {
slot[j] = 1;
count++;
profit += jobs[i].profit;
break;
return 0;
C++
#include <iostream>
#include <vector>
#include <algorithm>
struct Job {
string id;
int deadline;
int profit;
};
int main() {
int n;
cin >> n;
vector<Job> jobs(n);
int max_deadline = 0;
if (!slot[j]) {
slot[j] = true;
count++;
profit += job.profit;
break;
cout << count << " " << profit << endl;
}
1. Problem: "Minimum XOR Sum of Two Arrays"
You are given two arrays nums1 and nums2 of length n. You need to assign each element in nums1 to a
unique element in nums2, forming a 1-to-1 mapping. Your goal is to minimize the sum of XORs for each
assigned pair.
Input:
Output:
• Integer — the minimum possible XOR sum after assigning each element of nums1 to a unique
element in nums2.
Example:
Input:
nums1 = [1, 2]
nums2 = [2, 3]
Output:
Explanation:
1. 1^2 + 2^3 = 1 + 1 = 2
2. 1^3 + 2^2 = 2 + 0 = 2
Minimum = 2
Constraints Recap:
Python code:
def minimumXORSum(nums1, nums2):
n = len(nums1)
dp = [float('inf')] * (1 << n)
for j in range(n):
Time Complexity:
• O(n² * 2^n)
Space Complexity:
2.Traveling Salesman Problem (TSP) The Traveling Salesman Problem (TSP) is a classic problem in
optimization where you need to find the shortest possible path that visits every node exactly once and
returns to the starting node.
Example Problem:
Problem: Given a set of cities, and the distances between each pair of cities, find the shortest possible
route that visits each city exactly once and returns to the origin city.
10 0 35 25
15 35 0 30
20 25 30 0]
Expected Output:
• The minimum cost to visit all cities and return to the starting city.
dist=[0 29 20 21
29 0 15 17
20 15 0 28
21 17 28 0]
Expected Output:
• The minimum cost to visit all cities and return to the starting city.
dist=[0 10 15 20 25
10 0 35 25 30
15 35 0 30 35
20 25 30 0 40
25 30 35 40 0]
Expected Output:
• The minimum cost to visit all cities and return to the starting city.
12 0 22 30 13 23
18 22 0 15 35 20
29 30 15 0 28 10
12 13 35 28 0 18
25232010180]
Expected Output:
• The minimum cost to visit all cities and return to the starting city.
dist=[0 10 15
10 0 25
15 25 0]
Expected Output:
• The minimum cost to visit all cities and return to the starting city.
Code:
import sys
def tsp_dp(dist):
n = len(dist)
if memo[city][visited] != -1:
return memo[city][visited]
min_cost = sys.maxsize
memo[city][visited] = min_cost
return min_cost
# Start from the first city (city 0) and visit no other cities
return dfs(0, 1)
dist1 = [
dist2 = [
[0, 29, 20, 21],
dist3 = [
dist4 = [
dist5 = [
[10, 0, 25],
[15, 25, 0]
expected output:
• Minimum cost: 80
• Minimum cost: 69
• Minimum cost: 95
• Minimum cost: 50
Problem Statement:
You are given a positive integer N (can be up to 10⁶ digits, so it's a string). Find the next greater number
formed with the same set of digits.
Constraints:
Input/Output Examples:
Example 1:
Input:
N = "534976"
Output:
536479
Example 2:
Input:
N = "9876543210"
Output:
-1
Example 3:
Input:
N = "1234567899999999999"
Output:
1234567979999999999
Code:
def next_greater_number(n_str):
arr = list(n_str)
n = len(arr)
i=n-2
i -= 1
if i == -1:
return "-1" # Already largest permutation
j=n-1
j -= 1
# Final result
result = ''.join(arr)
if result[0] == '0':
return result
Problem Statement:
Given a list of integers nums[] (which may contain duplicate numbers and negative numbers), determine
if it can be partitioned into two subsets such that:
2. Subset sizes must be balanced (i.e., both subsets must have at least one element).
Input:
• A list of integers nums[] where 1 <= len(nums) <= 10^6 and -10^3 <= nums[i] <= 10^3.
Output:
Code:
def can_partition(nums):
total_sum = sum(nums)
if total_sum % 2 != 0:
target = total_sum // 2
offset = sum(x < 0 for x in nums) * 1000 # Shift all numbers >0 by 1000
dp = [False] * (target + 1)
return dp[target]
Problem Description:
Given a string s, you need to find the minimum number of cuts needed to partition s into substrings such
that every substring is a palindrome.
For example:
• Input: s = "aab"
• Output: 1
o Explanation: You can split "aab" into two substrings: "aa" and "b". Both "aa" and "b" are
palindromes.
Code:
n = len(s)
# dp[i] will store the minimum cuts required for the substring s[0:i+1]
dp = [0] * n
for i in range(n):
isPalindrome[j][i] = True
dp[i] = minCuts
return dp[n - 1]
# Test cases
test_cases = [
"aab", # 1 cut: "aa" and "b"
"ababbbabbababa" # 3 cuts
for s in test_cases:
Question 1:
Find the intersection of two sorted arrays OR in other words, given 2 sorted arrays, find all the elements
which occur in both arrays.
NOTE: For the purpose of this problem ( as also conveyed by the sample case ), assume that elements that
appear more than once in both arrays should be included multiple times in the final output.
Problem Constraints
Input Format
Output Format
Input 1:
A: [1 2 3 3 4 5 6]
B: [3 3 5]
Input 2:
A: [1 2 3 3 4 5 6]
B: [3 5]
Example Output
Output 1: [3 3 5]
Output 2: [3 5]
Example Explanation
Explanation 1:
Explanation 2:
Question2:
Where:
Find the minimum number of conference rooms required so that all meetings can be done.
Note :- If a meeting ends at time t, another meeting starting at time t can use the same conference room
Problem Constraints
1 <= N <= 105
Input Format
Output Format
Return the minimum number of conference rooms required so that all meetings can be done.
Example Input
Input 1:
[5, 10]
[15, 20]
Input 2:
A= [ [1, 18]
[18, 23]
[15, 29]
[4, 15]
[2, 11]
[5, 13]
Example Output
Output 1:
Output 2:
Example Explanation
Explanation 1:
Meeting three can be done in conference room 2 form 15 - 20 as it is free in this interval.
Explanation 2:
Meeting three can be done in conference room 2 from 15 - 29 as it is free in this interval.
Meeting two can be done in conference room 4 from 18 - 23 as it is free in this interval.
Question3:
You are giving candies to these children subjected to the following requirements:
4. Children with a higher rating get more candies than their neighbors.
Problem Constraints
Input Format
The first and only argument is an integer array A representing the rating of children.
Output Format
Example Input
Input 1:
A = [1, 2]
Input 2:
A = [1, 5, 2, 1]
Example Output
Output 1:
Output 2:
Example Explanation
Explanation 1:
The candidate with 1 rating gets 1 candy and candidate with rating 2 cannot get 1 candy as 1 is its
neighbor.
Explanation 2:
Question 4:
There is a street of length xxx whose positions are numbered 0, 1,…,x Initially there are no traffic lights,
but n sets of traffic lights are added to the street one after another.
Your task is to calculate the length of the longest passage without traffic lights after each addition.
Input
The first input line contains two integers xxx and n: the length of the street and the number of sets of
traffic lights.
Then, the next line contains n integers p1,p2,…,pn: the position of each set of traffic lights. Each position
is distinct.
Output
Print the length of the longest passage without traffic lights after each addition.
Example
Input:
83
362
Output:
533
Question5:
You are given n cubes in a certain order, and your task is to build towers using them. Whenever two cubes
are one on top of the other, the upper cube must be smaller than the lower cube.
You must process the cubes in the given order. You can always either place the cube on top of an existing
tower, or begin a new tower. What is the minimum possible number of towers?
Input
The next line contains nnn integers k1,k2,…,kn: the sizes of the cubes.
Output
Example
Input:
38215
Output:
Given an amount of n Rupees and an infinite supply of each of the denominations {1, 2, 5, 10} valued
coins/notes, The task is to find the minimum number of coins needed to make the given amount.
Examples:
Input: n= 39
Output: 6
Input: n = 121
Output: 13
The intuition would be to take coins with greater value first. This can reduce the total number of coins
needed. Start from the largest possible denomination and keep adding denominations while the
remaining value is greater than 0.
Python:
count =0
# Find denominations
n -= denomination[i]
count +=1
return count
if __name__ == '__main__':
n = 39
print(findMin(n, denomination))
Output: 6
2. Minimum sum of two numbers formed from digits of an array (Medium)
Given an array of digits (values are from 0 to 9), the task is to find the minimum possible sum of two
numbers formed using all digits of the array.
Examples:
Output: “604”
Output: “82”
Python Code:
i = len(s1) - 1
j = len(s2) - 1
carry = 0
res = []
total = carry
if i >= 0:
total += int(s1[i])
if j >= 0:
total += int(s2[j])
res.append(str(total % 10))
carry = total // 10
i -= 1
j -= 1
res.pop()
def minSum(arr):
count = [0] * 10
count[num] += 1
s1 = []
s2 = []
firstNum = True
# Traverse count array from 0 to 9
if firstNum:
s1.append(str(digit))
firstNum = False
else:
s2.append(str(digit))
firstNum = True
count[digit] -= 1
if not s1:
s1.append("0")
if not s2:
s2.append("0")
if __name__ == "__main__":
arr = [6, 8, 4, 5, 2, 3, 0]
print(minSum(arr))
Output: 604
The task is to determine the minimum total cost required to cut the board into squares optimally.
Examples:
Output: 42
Output: 15
Python Code:
x.sort()
y.sort()
hCount, vCount = 1, 1
i, j = len(x) - 1, len(y) - 1
totalCost = 0
vCount += 1
i -= 1
else:
hCount += 1
j -= 1
while i >= 0:
vCount += 1
i -= 1
while j >= 0:
hCount += 1
j -= 1
return totalCost
# Driver Code
if __name__ == "__main__":
m, n = 6, 4
x = [2, 1, 3, 1, 4]
y = [4, 1, 2]
print(minimumCostOfBreaking(m, n, x, y))
Output: 42
Given a positive integer K, the task is to find the minimum number of operations of the following two
types, required to change 0 to K.
Examples:
Input: K = 1
Output: 1
Input: K = 4
Output: 3
Python Code:
def minOperation(k):
# dp is initialised
dp = [0] * (k + 1)
dp[i] = dp[i - 1] + 1
return dp[k]
# Driver Code
if __name__ == '__main__':
k = 12
print(minOperation(k))
Output: 5
The three stacks s1, s2 and s3, each containing positive integers, are given. The task is to find the
maximum possible equal sum that can be achieved by removing elements from the top of the stacks.
Elements can be removed from the top of each stack, but the final sum of the remaining elements in all
three stacks must be the same. The goal is to determine the maximum possible equal sum that can be
achieved after removing elements.
Note: The stacks are represented as arrays, where the first index of the array corresponds to the top
element of the stack.
Examples:
Output: 5
s2 = [4, 5]
s3 = [2, 1]
Output: 0
Python Code:
def max_sum(s1, s2, s3):
sum1 = sum(s1)
sum2 = sum(s2)
sum3 = sum(s3)
while True:
return 0
return sum1
sum1 -= s1[top1]
top1 += 1
sum2 -= s2[top2]
top2 += 1
else:
sum3 -= s3[top3]
top3 += 1
s1 = [3, 2, 1, 1, 1]
s2 = [4, 3, 2]
s3 = [1, 1, 4, 1]
print(max_sum(s1, s2, s3))
Output: 5
Q.3 . Find minimum time to finish all jobs with given constraints (Hard)
Given an array job[], where each element represents the time required to complete a specific job. There
are k identical assignees available to complete these jobs, and each assignee takes t units of time to
complete one unit of a job. The task is to determine the minimum time required to complete all jobs
while following these constraints:
• Each assignee can only be assigned jobs that are contiguous in the given array. For example, an
assignee can be assigned jobs (job[1], job[2], job[3]) but not (job[1], job[3]) (skipping job[2]).
• A single job cannot be divided between two assignees. Each job must be assigned to exactly one
assignee.
Examples:
Output: 75
Output: 50
Python Code:
def GetMax(job):
res = job[0]
res = job[i]
return res
cnt = 1
curr = 0
i=0
curr = 0
cnt += 1
else:
# current assignee
curr += job[i]
i += 1
start, end = 0, 0
# job duration
for j in job:
end += j
start = max(start, j)
ans = end
# feasible time
end = mid - 1
else:
start = mid + 1
return ans * t
if __name__ == "__main__":
k, t = 4, 5
print(FindMinTime(job, k, t))
Output: 75
In one operation, you can replace the character at any position with the next or previous letter in the
alphabet (wrapping around so that 'a' is after 'z'). For example, replacing 'a' with the next letter results in
'b', and replacing 'a' with the previous letter results in 'z'. Similarly, replacing 'z' with the next letter results
in 'a', and replacing 'z' with the previous letter results in 'y'.
Return the length of the longest palindromic subsequence of s that can be obtained after performing at
most k operations.
Example 1:
Input: s = "abced", k = 2
Output: 3
Explanation:
Example 2:
Input: s = "aaazzz", k = 4
Output: 6
Explanation:
Constraints:
TEST
Python
class test:
@cache
def dfs(i: int, j: int, k: int) -> int:
if i > j:
return 0
if i == j:
return 1
d = abs(s[i] - s[j])
t = min(d, 26 - d)
if t <= k:
return res
s = list(map(ord, s))
n = len(s)
ans = dfs(0, n - 1, k)
dfs.cache_clear()
return ans
Java
class test {
private char[] s;
private Integer[][][] f;
this.s = s.toCharArray();
int n = s.length();
}
private int dfs(int i, int j, int k) {
if (i > j) {
return 0;
if (i == j) {
return 1;
if (f[i][j][k] != null) {
return f[i][j][k];
if (t <= k) {
f[i][j][k] = res;
return res;
C++
class test {
public:
int n = s.size();
auto dfs = [&](this auto&& dfs, int i, int j, int k) -> int {
if (i > j) {
return 0;
if (i == j) {
return 1;
if (f[i][j][k] != -1) {
return f[i][j][k];
if (t <= k) {
};
};
You are given two integer arrays, nums1 and nums2, of the same length.
Return the maximum number of matching indices after performing any number of right shifts on nums1.
A right shift is defined as shifting the element at index i to index (i + 1) % n, for all indices.
Example 1:
Input: nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]
Output: 6
Explanation:
If we right shift nums1 2 times, it becomes [1, 2, 3, 1, 2, 3]. Every index matches, so the output is 6.
Example 2:
Output: 3
Explanation:
If we right shift nums1 3 times, it becomes [5, 3, 1, 1, 4, 2]. Indices 1, 2, and 4 match, so the output is 3.
Constraints:
• nums1.length == nums2.length
Tests
Python3
class test:
n = len(nums1)
ans = 0
for k in range(n):
ans = max(ans, t)
return ans
Java
class test {
int n = nums1.length;
int ans = 0;
int t = 0;
if (nums1[(i + k) % n] == nums2[i]) {
++t;
return ans;
C++
class test {
public:
int n = nums1.size();
int ans = 0;
int t = 0;
if (nums1[(i + k) % n] == nums2[i]) {
++t;
}
return ans;
};
1. For each character, multiply its position in the reversed alphabet ('a' = 26, 'b' = 25, ..., 'z' = 1) with
its position in the string (1-indexed).
Example 1:
Input: s = "abc"
Output: 148
Explanation:
'a' 26 1 26
'b' 25 2 50
'c' 24 3 72
Example 2:
Input: s = "zaza"
Output: 160
Explanation:
'z' 1 1 1
'a' 26 2 52
'z' 1 3 3
'a' 26 4 104
Constraints:
Tests
Python3
class test:
ans = 0
x = 26 - (ord(c) - ord("a"))
ans += i * x
return ans
Java
class test {
int n = s.length();
int ans = 0;
ans += i * x;
return ans;
C++
class test {
public:
int reverseDegree(string s) {
int n = s.length();
int ans = 0;
ans += i * x;
return ans;
};
HIGHEST-RANKED ITEMS
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop.
The integers in the grid represent the following:
• 1 represents an empty cell that you can freely move to and from.
• All other positive integers represent the price of an item in that cell. You may also freely move to
and from these item cells.
You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col]
indicates that you start at the position (row, col) and are interested only in items with a price in the range
of [low, high] (inclusive). You are further given an integer k.
You are interested in the positions of the k highest-ranked items whose prices are within the given price
range. The rank is determined by the first of these criteria that is different:
1. Distance, defined as the length of the shortest path from the start (shorter distance has a higher
rank).
2. Price (lower price has a higher rank, but it must be in the price range).
Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there
are fewer than k reachable items within the price range, return all of them.
Example 1:
Output: [[0,1],[1,1],[2,1]]
With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).
Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).
Example 2:
Output: [[2,1],[1,2]]
With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).
Thus, the 2 highest ranked items in the price range are (2,1) and (1,2).
Example 3:
Output: [[2,1],[2,0]]
With a price range of [2,3], we can take items from (2,0) and (2,1).
Thus, the 2 highest ranked items in the price range are (2,1) and (2,0).
Note that k = 3 but there are only 2 reachable items within the price range.
Constraints:
• m == grid.length
• n == grid[i].length
• pricing.length == 2
• start.length == 2
• grid[row][col] > 0
• 1 <= k <= m * n
Tests
Python3
class Test:
def highestRankedKItems(
) -> List[List[int]]:
m, n = len(grid), len(grid[0])
q = deque([(row, col)])
pq = []
grid[row][col] = 0
step = 0
while q:
step += 1
for _ in range(len(q)):
x, y = q.popleft()
for a, b in pairwise(dirs):
nx, ny = x + a, y + b
grid[nx][ny] = 0
q.append((nx, ny))
pq.sort()
Java
class Test {
public List<List<Integer>> highestRankedKItems(
int m = grid.length;
int n = grid[0].length;
grid[row][col] = 0;
int nx = x + dirs[j];
if (0 <= nx && nx < m && 0 <= ny && ny < n && grid[nx][ny] > 0) {
grid[nx][ny] = 0;
}
}
pq.sort((a, b) -> {
});
ans.add(List.of(pq.get(i)[2], pq.get(i)[3]));
return ans;
C++
class Test {
public:
queue<pair<int, int>> q;
q.push({row, col});
vector<tuple<int, int, int, int>> pq;
grid[row][col] = 0;
int sz = q.size();
q.pop();
int nx = x + dirs[j];
if (0 <= nx && nx < m && 0 <= ny && ny < n && grid[nx][ny] > 0) {
grid[nx][ny] = 0;
q.push({nx, ny});
sort(pq.begin(), pq.end());
vector<vector<int>> ans;
ans.push_back({get<2>(pq[i]), get<3>(pq[i])});
}
return ans;
};
GOOD TRIPLET
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0,
1, ..., n - 1].
A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1
and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the
index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that
pos1x < pos1y < pos1z and pos2x < pos2y < pos2z.
Example 1:
Output: 1
Explanation:
There are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3).
Out of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good
triplet.
Example 2:
Output: 4
Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).
Constraints:
• n == nums1.length == nums2.length
For this problem, we first use pos to record the position of each number in nums2, and then process each
element in nums1 sequentially.
Consider the number of good triplets with the current number as the middle number. The first number
must have already been traversed and must appear earlier than the current number in nums2. The third
number must not yet have been traversed and must appear later than the current number in nums2.
Take nums1 = [4,0,1,3,2] and nums2 = [4,1,0,2,3] as an example. Consider the traversal process:
1. First, process 4. At this point, the state of nums2 is [4,X,X,X,X]. The number of values before 4 is 0,
and the number of values after 4 is 4. Therefore, 4 as the middle number forms 0 good triplets.
2. Next, process 0. The state of nums2 becomes [4,X,0,X,X]. The number of values before 0 is 1, and
the number of values after 0 is 2. Therefore, 0 as the middle number forms 2 good triplets.
3. Next, process 1. The state of nums2 becomes [4,1,0,X,X]. The number of values before 1 is 1, and
the number of values after 1 is 2. Therefore, 1 as the middle number forms 2 good triplets.
4. ...
5. Finally, process 2. The state of nums2 becomes [4,1,0,2,3]. The number of values before 2 is 4,
and the number of values after 2 is 0. Therefore, 2 as the middle number forms 0 good triplets.
We can use a Binary Indexed Tree (Fenwick Tree) to update the occurrence of numbers at each position in
nums2, and quickly calculate the number of 1s to the left of each number and the number of 0s to the
right of each number.
A Binary Indexed Tree, also known as a Fenwick Tree, efficiently supports the following operations:
1. Point Update update(x, delta): Add a value delta to the number at position x in the sequence.
2. Prefix Sum Query query(x): Query the sum of the sequence in the range [1, ..., x], i.e., the prefix
sum at position x.
Both operations have a time complexity of O(logn). Therefore, the overall time complexity is O(nlogn),
where n is the length of the array nums1. The space complexity is O(n).
Python3
class BinaryIndexedTree:
self.n = n
self.c = [0] * (n + 1)
@staticmethod
def lowbit(x):
return x & -x
self.c[x] += delta
x += BinaryIndexedTree.lowbit(x)
s=0
while x > 0:
s += self.c[x]
x -= BinaryIndexedTree.lowbit(x)
return s
class Test:
ans = 0
n = len(nums1)
tree = BinaryIndexedTree(n)
p = pos[num]
left = tree.query(p)
return ans
Java
class Test {
int n = nums1.length;
pos[nums2[i]] = i + 1;
long ans = 0;
int p = pos[num];
tree.update(p, 1);
return ans;
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
while (x <= n) {
c[x] += delta;
x += lowbit(x);
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
return s;
C++
class BinaryIndexedTree {
public:
int n;
vector<int> c;
BinaryIndexedTree(int _n)
: n(_n)
, c(_n + 1) {}
while (x <= n) {
c[x] += delta;
x += lowbit(x);
int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
return s;
int lowbit(int x) {
};
class Test {
public:
int n = nums1.size();
vector<int> pos(n);
int p = pos[num];
tree->update(p, 1);
return ans;
};
Problem Statement:
Given a string s, remove exactly one character such that the resulting string is lexicographically smallest.
Return the modified string.
Input Format:
Output Format:
• A single string which is lexicographically smallest after removing one character.
Input: abcda
Output: abca
Input: aaa
Output: aa
Input: edcba
Output: dcba
Python
def smallestString(s):
for i in range(len(s)-1):
return s[:-1]
# Read input
s = input()
rint(smallestString(s))
Java
import java.util.Scanner;
System.out.println(smallestString(input));
#include <stdio.h>
#include <string.h>
if (j != i) printf("%c", s[j]);
printf("\n");
}
int main() {
char s[101];
scanf("%s", s);
smallestString(s);
return 0;
C++
#include <iostream>
string smallestString(string s) {
int main() {
string s;
cin >> s;
Problem Statement:
Given a number n, count how many numbers from 1 to n have a digit sum divisible by 3.
Input Format:
• A single integer n (1 ≤ n ≤ 1000)
Output Format:
• A single integer: the count of numbers from 1 to n whose digit sum is divisible by 3.
Input: 15
Output: 5
Input: 20
Output: 6
Input: 30
Output: 10
Python
def countDiv3(n):
n = int(input())
print(countDiv3(n))
Java
import java.util.Scanner;
int count = 0;
if (sum % 3 == 0) count++;
return count;
int n = sc.nextInt();
System.out.println(countDiv3(n));
#include <stdio.h>
int digitSum(int n) {
int sum = 0;
while(n) {
sum += n % 10;
n /= 10;
return sum;
int countDiv3(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (digitSum(i) % 3 == 0)
count++;
return count;
int main() {
int n;
scanf("%d", &n);
printf("%d\n", countDiv3(n));
return 0;
C++
#include <iostream>
int digitSum(int n) {
int sum = 0;
while(n) {
sum += n % 10;
n /= 10;
return sum;
int countDiv3(int n) {
int count = 0;
if (digitSum(i) % 3 == 0)
count++;
return count;
int main() {
int n;
cin >> n;
Problem Statement:
You are given a target amount V and an array of coin denominations (e.g., [1, 2, 5, 10, 20, 50, 100, 500,
2000]). Find the minimum number of coins required to make that amount.
Input Format:
Output Format:
Input: 70
Input: 121
Output: 3 // (100 + 20 + 1)
Input: 999
Python
def minCoins(V):
count = 0
for c in coins:
if V == 0:
break
count += V // c
V %= c
return count
print(minCoins(int(input())))
Java
import java.util.Scanner;
int count = 0;
if (V == 0) break;
count += V / coin;
V %= coin;
return count;
}
public static void main(String[] args) {
int V = sc.nextInt();
System.out.println(minCoins(V));
#include <stdio.h>
int minCoins(int V) {
int count = 0;
if (V == 0) break;
count += V / coins[i];
V %= coins[i];
return count;
int main() {
int V;
scanf("%d", &V);
printf("%d\n", minCoins(V));
return 0;
C++
#include <iostream>
using namespace std;
int minCoins(int V) {
int count = 0;
if (V == 0) break;
count += V / coin;
V %= coin;
return count;
int main() {
int V;
cin >> V;
Problem Statement:
You are given n activities with start and end times. Select the maximum number of activities that can be
performed by a single person, assuming that a person can only work on a single activity at a time.
Input Format:
• Next n lines: Two integers start and end (start time and end time of each activity)
Output Format:
12
34
06
57
89
59
Output:
Explanation:
Input:
10 20
12 25
20 30
Output:
Input:
13
24
35
06
Output:
Python
def activitySelection(activities):
count = 1
last_end = activities[0][1]
count += 1
last_end = activities[i][1]
return count
n = int(input())
print(activitySelection(activities))
Java
import java.util.*;
class Main {
count++;
end = arr[i][1];
return count;
int n = sc.nextInt();
activities[i][0] = sc.nextInt();
activities[i][1] = sc.nextInt();
System.out.println(activitySelection(activities));
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int start, end;
} Activity;
int main() {
int n;
scanf("%d", &n);
Activity acts[n];
count++;
last_end = acts[i].end;
printf("%d\n", count);
return 0;
}
C++
#include <iostream>
#include <vector>
#include <algorithm>
struct Activity {
};
int main() {
int n;
cin >> n;
vector<Activity> acts(n);
int count = 1;
count++;
last_end = acts[i].end;
Problem Statement:
You are given n jobs. Each job has an ID, a deadline, and a profit. Only one job can be scheduled at a time.
A job earns profit only if it is finished on or before its deadline. Schedule jobs to maximize total profit.
Input Format:
Output Format:
Input:
a 4 20
b 1 10
c 1 40
d 1 30
Output:
2 70
Input:
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output:
3 142
Input:
x 3 10
y 2 20
z 1 30
Output:
2 50
Python
def jobSequencing(jobs):
if not slots[j]:
slots[j] = True
count += 1
profit += job[2]
break
n = int(input())
res = jobSequencing(jobs)
print(res[0], res[1])
Java
import java.util.*;
class Job {
String id;
this.id = id;
this.deadline = d;
this.profit = p;
}
}
int maxDeadline = 0;
if (!slot[j]) {
slot[j] = true;
count++;
profit += job.profit;
break;
int n = sc.nextInt();
String id = sc.next();
int d = sc.nextInt();
int p = sc.nextInt();
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char id[2];
} Job;
int main() {
int n;
scanf("%d", &n);
Job jobs[n];
int max_deadline = 0;
max_deadline = jobs[i].deadline;
memset(slot, 0, sizeof(slot));
if (!slot[j]) {
slot[j] = 1;
count++;
profit += jobs[i].profit;
break;
return 0;
}
C++
#include <iostream>
#include <vector>
#include <algorithm>
struct Job {
string id;
int deadline;
int profit;
};
int main() {
int n;
cin >> n;
vector<Job> jobs(n);
int max_deadline = 0;
}
sort(jobs.begin(), jobs.end(), compare);
if (!slot[j]) {
slot[j] = true;
count++;
profit += job.profit;
break;
cout << count << " " << profit << endl;
Question 1:
Ramu has N dishes of different types arranged in a row: A1,A2,…,AN where Ai denotes the type of the ith
dish. He wants to choose as many dishes as possible from the given list but while satisfying two
conditions:
Ramu wants to know which type of dish he should choose from, so that he can pick the maximum number
of dishes.
Example :
For type 1, Ramu can choose at most four dishes. One of the ways to choose four dishes of type 1 is
A1,A4, A7 and A9.
For type 2, Ramu can choose at most two dishes. One way is to choose A3 and A5.
So in this case, Ramu should go for type 1, in which he can pick more dishes.
INPUT FORMAT:
• The first line contains T, the number of test cases. Then the test cases follow.
• For each test case, the first line contains a single integer N.
OUTPUT FORMAT
For each test case, print a single line containing one integer ― the type of the dish that Ramu should
choose from. If there are multiple answers, print the smallest one.
CONSTRAINTS :
Sample Input :
12212
111111
12223421
Sample Output :
1
C++
#include<bits/stdc++.h>
int main()
cin>>t;
cin>>n;
cin>>item[x];
int j = 0, max = 0;
while (j < n)
int c = 1;
int k = j + 1;
while (k < n) {
c += 1;
k += 1;
if (max < c) {
max = c;
itemtype = item[j];
j += 1;
return 0;
Java:
import java.util.*;
int t = s.nextInt();
{
int n = s.nextInt();
item[i]= s.nextInt();
int j = 0,max = 0;
while(j< n)
int c = 1;
int k = j+1;
while(k< n)
c+=1;
k+=1;
k+=1;
if (max< c)
max=c;
itemType = item[j];
}
j+=1;
System.out.println(itemType);
Python:
t = int(input())
for _ in range(t):
n = int(input())
max_count = 0
item_type = item[0]
j=0
while j < n:
c=1
k=j+1
while k < n:
c += 1
if k < n - 1 and item[k] == item[k + 1]:
k += 1
k += 1
if max_count < c:
max_count = c
item_type = item[j]
j += 1
print(item_type)
Question 2:
There are three piles of stones. The first pile contains a stones, the second pile contains b stones and the
third pile contains c stones. You must choose one of the piles and split the stones from it to the other two
piles; specifically, if the chosen pile initially contained s stones, you should choose an integer k (0≤k≤s),
move k stones from the chosen pile onto one of the remaining two piles and s−k stones onto the other
remaining pile. Determine if it is possible for the two remaining piles (in any order) to contain x stones
and y stones respectively after performing this action.
INPUT FORMAT :
• The first line of the input contains a single integer T denoting the number of test cases. The
description of T test cases follows.
• The first and only line of each test case contains five space-separated integers
a,b,c, x and y.
OUTPUT FORMAT :
For each test case, print a single line containing the string “YES” if it is possible to obtain piles of the given
sizes or “NO” if it is impossible.
CONSTRAINTS :
12324
32565
24262
6 5 2 12 1
SAMPLE OUTPUT :
YES
NO
YES
NO
Test case 1: You can take the two stones on the second pile, put one of them on the first pile and the
other one on the third pile.
Test case 3: You can choose the first pile and put all stones from it on the second pile.
C++:
#include<bits/stdc++.h>
int main ()
int t;
cin >> t;
while (t--)
int a, b, c, x, y;
cin >> a >> b >> c >> x >> y;
if ((a + b + c) != (x + y))
else
if (y < min (a, min (b, c)) || x < min (a, min (b, c)))
else
Java:
import java.util.Scanner;
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
if ((a + b + c) != (x + y)) {
System.out.println("NO");
} else {
System.out.println("NO");
} else {
System.out.println("YES");
sc.close();
Python:
t = int(input())
for i in range(t):
a, b, c, x, y = map(int, input().split())
if (a + b + c) != (x + y):
print("NO")
else:
print("NO")
else:
print("YES")
Question 3:
Altaf has recently learned about number bases and is becoming fascinated.
Altaf learned that for bases greater than ten, new digit symbols need to be introduced, and that the
convention is to use the first few letters of the English alphabet. For example, in base 16, the digits are
0123456789ABCDEF. Altaf thought that this is unsustainable; the English alphabet only has 26 letters, so
this scheme can only work up to base 36. But this is no problem for Altaf, because Altaf is very creative
and can just invent new digit symbols when she needs them. (Altaf is very creative.)
Altaf also noticed that in base two, all positive integers start with the digit 1! However, this is the only
base where this is true. So naturally, Altaf wonders: Given some integer N, how many bases b are there
such that the base-b representation of N starts with a 1?
INPUT FORMAT :
The first line of the input contains an integer T denoting the number of test cases. The description of T
test cases follows.
Each test case consists of one line containing a single integer N (in base ten).
OUTPUT FORMAT :
For each test case, output a single line containing the number of bases b, or INFINITY if there are an
infinite number of them.
CONSTRAINTS :
11
24
SAMPLE OUTPUT :
14
C++:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
tem = tem * i;
if(tem > (long long int)1e12) {
break;
v[j].push_back(tem);
int t;
cin >> t;
while(t--) {
cin >> m;
if(m == 1) {
continue;
}
return 0;
Java:
import java.util.*;
long tem = i;
tem = tem * i;
break;
v[j].add(tem);
int t = sc.nextInt();
while (t-- > 0) {
long m = sc.nextLong();
if (m == 1) {
System.out.println("INFINITY");
continue;
long ans = (m + 1) / 2;
long p = m / 2 + 1;
System.out.println(ans);
sc.close();
}
}
Python:
tem = i
tem = tem * i
break
v[j].append(tem)
t = int(input())
for _ in range(t):
m = int(input())
if m == 1:
print("INFINITY")
continue
ans = (m + 1) // 2
p = m // 2 + 1
print(ans)
Greedy algorithms
Chef has gone shopping with his 5-year old son. They have bought N items so far. The items are numbered
from 1 to N, and the item i weighs Wi grams.
Chef's son insists on helping his father in carrying the items. He wants his dad to give him a few items.
Chef does not want to burden his son. But he won't stop bothering him unless he is given a few items to
carry. So Chef decides to give him some items. Obviously, Chef wants to give the kid less weight to carry.
However, his son is a smart kid. To avoid being given the bare minimum weight to carry, he suggests that
the items are split into two groups, and one group contains exactly K items. Then Chef will carry the
heavier group, and his son will carry the other group.
Help the Chef in deciding which items should the son take. Your task will be simple. Tell the Chef the
maximum possible difference between the weight carried by him and the weight carried by the kid.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow.
The first line of each test contains two space-separated integers N and K. The next line contains N space-
separated integers W1, W2, ..., WN.
Output:
For each test case, output the maximum possible difference between the weights carried by both in
grams.
Constraints:
• 1 ≤ T ≤ 100
• 1 ≤ K < N ≤ 100
• 1 ≤ Wi ≤ 100000 (105)
Sample 1:
Input
52
8 4 5 2 10
83
11111111
Output
17
Explanation:
Case #1: The optimal way is that Chef gives his son K=2 items with weights 2 and 4. Chef carries the rest of
the items himself. Thus the difference is: (8+5+10) - (4+2) = 23 - 6 = 17.
Case #2: Chef gives his son 3 items and he carries 5 items himself.
C:
#include <stdio.h>
#include <stdlib.h>
int main() {
int t;
scanf("%d", &t);
while (t--) {
int n, k;
int arr[n];
scanf("%d", &arr[i]);
totalSum += arr[i];
// Sum of the first K smallest numbers (S1) and last K largest numbers (S2)
sumOfKSmallest += arr[i];
return 0;
}
Java:
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef {
arr[i] = sc.nextInt();
totalSum += arr[i];
Arrays.sort(arr);
// Sum of the first K smallest numbers (S1) and last K largest numbers (S2)
System.out.println(Math.max(diff1, diff2));
Python:
def main():
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
total_sum = sum(arr)
sum_of_k_smallest = sum(arr[:k])
sum_of_k_largest = sum(arr[-k:])
print(max(diff1, diff2))
if __name__ == "__main__":
main()
There are N students standing in a row and numbered 1 through N from left to right. You are given a
string S with length N, where for each valid i, the i-th character of S is 'x' if the i-th student is a girl or 'y'
if this student is a boy. Students standing next to each other in the row are friends.
The students are asked to form pairs for a dance competition. Each pair must consist of a boy and a girl.
Two students can only form a pair if they are friends. Each student can only be part of at most one pair.
What is the maximum number of pairs that can be formed?
Input
• The first line of the input contains a single integer T denoting the number of test cases. The
description of T test cases follows.
• The first and only line of each test case contains a single string S.
Output
For each test case, print a single line containing one integer ― the maximum number of pairs.
Constraints
• 1≤ T ≤ 100
• 1≤ N ≤ 105
• ∣S∣ = N
• the sum of N over all test cases does not exceed 3⋅105
Subtasks
Sample 1:
Input
xy
xyxxy
yy
Output
Explanation:
Example case 1: There is only one possible pair: (first student, second student).
Example case 2: One of the ways to form two pairs is: (first student, second student) and (fourth student,
fifth student).
Another way to form two pairs is: (second student, third student) and (fourth student, fifth student).
C:
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100005 // Maximum number of students
// Function to solve the problem of forming maximum pairs for the dance competition
void findMaximumPairs() {
// If both students are the same (both 'x' or both 'y'), no new pair can be formed
} else {
// If the current student and the previous one are different, we can form a pair
// The maximum pairs will be either the same as the previous student or the pairs formed by
pairing these two students
int main() {
while (testCases--) {
Java:
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
int t = sc.nextInt();
while(t-->0)
String s = sc.next();
int c = 0;
for(int i=0;i<s.length();i++)
if(i>0)
if((s.charAt(i)=='x'&&s.charAt(i-1)=='y')||(s.charAt(i)=='y'&&s.charAt(i-1)=='x')){
c++;
i++;
System.out.println(c);
Python:
def find_maximum_pairs():
# If both students are the same (both 'x' or both 'y'), no new pair can be formed
dp[i] = dp[i - 1]
else:
# If the current student and the previous one are different, we can form a pair
# The maximum pairs will be either the same as the previous student or the pairs formed by pairing
these two students
print(dp[total_students - 1])
def main():
for _ in range(T):
if __name__ == "__main__":
main()
Dynamic programming
1.Count Subarrays
Given an array A1,A2,...,AN, count the number of subarrays of array A which are non-decreasing.
A subarray ]A[i,j] is non-decreasing if Ai+1≤+2≤... Ai ≤ Ai+1≤ Ai+2≤...≤Aj. You have to count the total
number of such subarrays.
Input
• The first line of input contains an integer T denoting the number of test cases. The description of T
test cases follows.
• The first line of each test case contains a single integer N denoting the size of array.
• The second line contains N space-separated integers 1A1, 2 A 2, ..., AN denoting the elements of
the array.
Output
For each test case, output in a single line the required answer.
Constraints
• 1≤T≤5
• 1 ≤ N ≤ 105
• 1 ≤ Ai ≤ 109
Subtasks
Sample 1:
Input
1423
Output
Explanation:
Example case 1.
Example case 2.
def count_increasing_subsequences(test_cases):
for _ in range(test_cases):
n = int(input().strip())
ans = 1
dp = [1] * n
dp[i] += dp[i - 1]
ans += dp[i]
print(ans)
if __name__ == "__main__":
test_case = int(input().strip())
count_increasing_subsequences(test_case)
C:
#include <stdio.h>
#include <stdlib.h>
int main() {
int testCase;
scanf("%d", &testCase);
while (testCase--) {
long long n;
scanf("%lld", &n);
// Initialize dp array to 1
dp[i] = 1;
scanf("%lld", &arr[i]);
ans += dp[i];
}
printf("%lld\n", ans);
free(arr);
free(dp);
return 0;
Java:
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef {
long n = Long.parseLong(br.readLine());
long ans = 1;
arr[i] = Long.parseLong(st.nextToken());
ans += dp[i];
System.out.println(ans);
2. Sums in a Triangle
Given an integer N, let us consider a triangle of numbers of N lines in which a number a11 appears in the
first line, two numbers a21 and a22 appear in the second line, three numbers a31, a32 and a33 appear in
the third line, etc. In general, i numbers 1,2…ai1,ai2…ai i appear in the ith line for all 1≤ I ≤ N. Develop a
program that will compute the largest of the sums of numbers that appear on the paths starting from the
top towards the base, so that:
• on each path the next number is located on the row below, more precisely either directly below
or below and one place to the right.
Input Format
• The first line of the input contains an integer T, the number of test cases.
• Then T test cases follow. Each test case starts with an integer N, the number of rows. Then N lines
follow where in ith line contains i integers 1,2 ai1,ai2…aii.
Output Format
For each test case print the maximum path sum in a separate line.
Constraints
• 1 ≤ T ≤1000
1 ≤ N < 100
Sample 1:
Input
21
123
12
412
2311
Output
Explanation:
Test case 1:
Test case 2:
C:
#include <stdio.h>
void solve() {
scanf("%lld", &n);
long long int ar[n + 1][n + 1];
scanf("%lld", &ar[i][j]);
dp[n][j] = ar[n][j];
dp[i][j] = ar[i][j] + (dp[i + 1][j] > dp[i + 1][j + 1] ? dp[i + 1][j] : dp[i + 1][j + 1]);
printf("%lld\n", dp[1][1]);
int main() {
scanf("%lld", &t);
solve();
return 0;
}
Java:
import java.util.*;
class Codechef {
long t = scanner.nextLong();
solve(scanner);
scanner.close();
long n = scanner.nextLong();
ar[i][j] = scanner.nextLong();
System.out.println(dp[1][1]);
Python:
def solve():
n = int(input())
ar = []
for i in range(n):
ar.append(row)
# Initialize the dp array
for j in range(n):
print(dp[0][1])
if __name__ == "__main__":
t = int(input())
for _ in range(t):
solve()
Problem -1: Minimum cost to cut the stick
Problem Description: We are given a stick of length N and a CUTS array of size C. The stick has markings as
shown, and the CUTS array depicts the marking at which the stick needs to be cut (shown in red).
Input Format:
2. The second input is an integer C representing the number of cuts to be made on the stick.
3. The third input is an array of C integers where each integer denotes the position at which the stick
needs to be cut.
Output Format:
The output should be a single integer representing the minimum cost required to cut the stick according
to the given positions.
Example-1:
Input:
10
247
Output:
20
Example-2:
Input:
14
Output:
Explanation:
For each test case:
• The third input represents the CUTS array, which contains the positions of the cuts on the stick.
The output is the minimum cost to cut the stick where the cost is the length of the segment being cut.
TestCases:
Test Case 1:
Stick length = 10
CUTS = [2, 4, 7]
Expected result: 20
Test Case 2:
Stick length = 5
CUTS = [1, 4]
Expected result: 8
Test Case 3:
Stick length = 8
CUTS = [2, 5]
Expected result: 12
Test Case 4:
Stick length = 12
CUTS = [3, 8]
Expected result: 18
Test Case 5:
Stick length = 6
CUTS = [1, 3, 5]
Expected result: 10
Test Case 6:
Stick length = 15
Test Case 7:
Stick length = 20
Expected result: 60
Test Case 8:
Stick length = 50
Test Case 9:
Stick length = 30
Expected result: 80
Java:
import java.util.*;
// Base case
if (i > j) {
return 0;
if (dp[i][j] != -1) {
return dp[i][j];
cuts.add(n);
cuts.add(0);
Collections.sort(cuts);
Arrays.fill(row, -1);
int c = cuts.size();
int n = 7;
C++
#include <bits/stdc++.h>
if (i > j) {
return 0;
if (dp[i][j] != -1) {
return dp[i][j];
// Modify the cuts array by adding 0 at the beginning and 'n' at the end.
cuts.push_back(n);
cuts.insert(cuts.begin(), 0);
sort(cuts.begin(), cuts.end());
int main() {
int c = cuts.size();
int n = 7;
cout << "The minimum cost incurred is: " << minimumCost(n, c, cuts) << endl;
return 0;
Python
cuts.sort()
# Base case
if i > j:
return 0
if dp[i][j] != -1:
return dp[i][j]
mini = float('inf')
dp[i][j] = mini
return mini
return f(1, c)
if __name__ == "__main__":
cuts = [3, 5, 1, 4]
c = len(cuts)
n=7
Problem Description:
Given a total amount amount and a list of coins (available denominations), find the number of distinct
ways to make up that amount using any number of coins from the list. You may use each coin
denomination an unlimited number of times.
Concept:
This is a variation of the Unbounded Knapsack problem and can be solved using Dynamic Programming.
Input Format:
Output Format:
One integer – the total number of ways to make the given amount.
Example:
Input:
123
Output:
4
Explanation: The four ways are:
1+1+1+1
1+1+2
2+2
1+3
Python
dp = [0] * (amount + 1)
return dp[amount]
# Input
amount = int(input())
n = int(input())
print(count_ways(amount, coins))
Java
import java.util.*;
public class CoinChange {
dp[0] = 1;
return dp[amount];
int n = sc.nextInt();
coins[i] = sc.nextInt();
System.out.println(countWays(amount, coins));
#include <stdio.h>
int countWays(int coins[], int n, int amount) {
dp[0] = 1;
return dp[amount];
int main() {
int amount, n;
scanf("%d", &amount);
scanf("%d", &n);
int coins[n];
scanf("%d", &coins[i]);
return 0;
Test Cases
Problem Description:
Given a string S, generate all unique permutations of the string in lexicographical order.
Input Format:
Output Format:
Print all unique permutations of the string, one per line, in lexicographical order.
Example:
Input:
abc
Output:
abc
acb
bac
bca
cab
cba
Python
def string_permutations(s):
perm_set = sorted(set(permutations(s)))
for p in perm_set:
print("".join(p))
# Input
s = input().strip()
string_permutations(s)
Java
import java.util.*;
if (str.length() == 0) {
result.add(ans);
return;
System.out.println(s);
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
*x = *y;
*y = tmp;
}
if (l == r) {
result[(*index)] = strdup(str);
(*index)++;
} else {
int main() {
char str[100];
scanf("%s", str);
int n = strlen(str);
int size = 1;
int index = 0;
permute(str, 0, n - 1, result, &index);
printf("%s\n", result[i]);
free(result[i]);
free(result);
return 0;
Test Cases
3 a a
4 ab ab, ba
6 aaa aaa
10 abac aabc, aacb, abac, abca, acab, acba, baac, baca, bcaa, caab, caba, cbaa
Problem-4: Maximum Product Subarray
Problem Description:
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the
largest product, and return that product.
Key Insight:
This problem is similar to the maximum subarray sum problem (Kadane’s Algorithm), but with a twist:
Input Format:
Output Format:
Example:
Input:
2 3 -2 4
Output:
Python
def max_product(nums):
if not nums:
return 0
max_so_far = min_so_far = result = nums[0]
if num < 0:
return result
# Input
n = int(input())
print(max_product(nums))
Java
import java.util.*;
if (nums[i] < 0) {
max_so_far = min_so_far;
min_so_far = temp;
return result;
int n = sc.nextInt();
nums[i] = sc.nextInt();
System.out.println(maxProduct(nums));
C
#include <stdio.h>
if (nums[i] < 0) {
max_so_far = min_so_far;
min_so_far = temp;
return result;
}
int main() {
int n;
scanf("%d", &n);
int nums[n];
scanf("%d", &nums[i]);
return 0;
Test Cases
1 4
2 5
-2 0 -1 3 4 12 [3,4] = 12
3 3
-2 3 -4 24 [-2, 3, -4] = 24
4 6
-1 -3 -10 0 60 -2 60 [60]
5 1
0 0 Zero product
6 2
-2 -3 6 [-2, -3] = 6
7 3
020 2 [2]
8 4
1 2 3 4 24 Entire array
9 5
10 6
Problem Description:
Find the minimum number of railway platforms required so that no train has to wait.
Core Logic:
We want to track the number of trains at the station at any moment. We:
Input Format:
Second line: n space-separated arrival times (in 24-hour format, e.g., 900 for 9:00 AM).
Output Format:
One integer: minimum number of platforms needed.
Example:
Input:
Output:
Python
arrival.sort()
departure.sort()
n = len(arrival)
platforms = 1
max_platforms = 1
i = 1 # arrival pointer
j = 0 # departure pointer
platforms += 1
i += 1
else:
platforms -= 1
j += 1
# Input
n = int(input())
print(find_min_platforms(arrival, departure))
Java
import java.util.*;
Arrays.sort(arr);
Arrays.sort(dep);
int n = arr.length;
int i = 1, j = 0;
platforms++;
i++;
} else {
platforms--;
j++;
}
return maxPlatforms;
int n = sc.nextInt();
System.out.println(findPlatforms(arrival, departure));
#include <stdio.h>
#include <stdlib.h>
}
int findMinPlatforms(int arr[], int dep[], int n) {
int i = 1, j = 0;
platforms++;
i++;
} else {
platforms--;
j++;
maxPlatforms = platforms;
return maxPlatforms;
int main() {
int n;
scanf("%d", &n);
return 0;
Test Cases
1 900 940 950 1100 1500 1800 910 1200 1120 1130 1900 2000 3 Max 3 trains at station
around 950
3 1000 1015 1030 1045 1020 1035 1050 1100 2 Overlaps between each arrival
4 900 905 915 925 930 940 950 955 4 All overlap
9 1200 1210 12251230 1240 12503 All trains overlap at different points
10 900 1100 1230 1500 1000 1130 1300 1600 1 No overlapping trains
Sample 1:
A diligent student has S hours to study for upcoming exams. There are C subjects to study. Studying
subject i for one hour increases their understanding by Ui units. Due to time constraints and diminishing
returns, the student can study each unique subject for a maximum of 2 hours. The student wants to
achieve a total understanding of at least T units. Calculate the minimum total study hours required to
reach a total understanding of T or more. If it's impossible to reach a total understanding of T even after
studying each subject for the maximum allowed time, return -1.
Parameters:
• U: INTEGER ARRAY (Array of size C, where U[i] is the understanding gained per hour of studying
subject i, 1≤U[i]≤105)
Test Cases:
Case 1:
Input:
10
18
Output:
• S=10
• C=2
• U=[5,3]
• T=18
Study subject 0 for 2 hours (gain 2×5=10 understanding). Study subject 1 for 2 hours (gain 2×3=6
understanding). Total understanding = 10+6=16, which is less than 18. We need to study more. Since
we've reached the maximum time for each subject, it's impossible to reach the target. Oh wait, the
question asks for the minimum hours to reach at least T.
Let's rethink Case 1: Study subject 0 for 2 hours (10 understanding). Study subject 1 for 2 hours (6
understanding). Total 16. We haven't reached 18. The maximum understanding we can get is
2×5+2×3=16. Since this is less than 18, the answer should be -1.
Case 2:
Input:
Output:
2
• S=5
• C=3
• U=[2,1,4]
• T=7
Study subject 2 for 2 hours (gain 2×4=8 understanding). Total hours = 2, total understanding = 8 (which is
≥7).
Case 3:
Input:
12
Output:
-1
• S=3
• C=3
• U=[1,5,2]
• T=12
Study subject 1 for 2 hours (10 understanding, 2 hours). Study subject 2 for 1 hour (2 understanding, 1
hour). Total understanding = 12, total hours = 3.
Wait, the maximum understanding is 16, which is greater than 12. We need the minimum hours.
Let's re-rethink Case 3: Sort U in descending order: [5,2,1]. Study subject with U=5 for 2 hours (10
understanding, 2 hours). Remaining target = 12−10=2. Study subject with U=2 for 1 hour (2
understanding, 1 hour). Remaining target = 2−2=0. Total hours = 2+1=3.
Case 4:
Input:
Output
• S=6
• C=2
• U=[1,2]
• T=6
Study subject with U=2 for 2 hours (4 understanding, 2 hours). Remaining target = 6−4=2. Study subject
with U=1 for 2 hours (2 understanding, 2 hours). Remaining target = 2−2=0. Total hours = 2+2=4.
Solution:
def solve():
s = int(input())
c = int(input())
t = int(input())
print(-1)
return
total_understanding = 0
hours_studied = 0
study_counts = [0] * c
total_understanding += understanding_per_hour
hours_studied += 1
study_counts[original_index] += 1
if total_understanding >= t:
print(hours_studied)
return
# This part should ideally not be reached if the initial max_understanding check is correct
if total_understanding >= t:
print(hours_studied)
else:
print(-1)
solve()
Explanation of the Code:
1. Read Input: The code first reads the input values for S (total study hours), C (number of subjects),
the array U (understanding per hour for each subject), and T (target total understanding).
3. Check if Target is Reachable: If the max_understanding is less than the target understanding T, it's
impossible to reach the target, so the code prints -1 and returns.
4. Sort Subjects by Understanding Gain: The subjects are sorted in descending order based on the
understanding gained per hour (U[i]). This greedy approach prioritizes studying the subjects that provide
the most understanding per hour first, aiming to reach the target in the minimum number of hours. The
original index of each subject is also stored to keep track of the study limit per subject.
5. Iterate Through Subjects: The code iterates through the sorted subjects. For each subject:
• It checks if the student has studied this subject for less than 2 hours (study_counts[original_index]
< 2), if the total_understanding is still less than the target T, and if the hours_studied are within the total
available study hours S.
• If all these conditions are true, the student studies the subject for one hour, increasing the
total_understanding by understanding_per_hour, incrementing hours_studied, and updating the
study_counts for that subject.
• If the total_understanding reaches or exceeds the target T, the code prints the hours_studied and
returns.
6. Final Check (Safeguard): After the loop, there's a final check to see if the total_understanding has
reached the target. While the initial max_understanding check should prevent the target from being
unreachable within the time limit if a solution exists, this acts as a safeguard. If the target is reached, the
hours_studied are printed; otherwise, -1 is printed (although this scenario should ideally be caught by the
initial check).
2)
A student is collecting stickers from different series. There are N stickers in total, and their series are
represented by an array Series. If two stickers have the same value in Series, they belong to the same
series. The student wants to collect as many unique stickers as possible. They follow a specific collecting
pattern:
• They can start by collecting any number of unique stickers from one or more different series in
their first step.
• If they collect K unique stickers in one step, the next step they take must involve collecting 2∗K
unique stickers from entirely different series (none of the series can be the same as the ones collected
from in previous steps).
• They can never collect from a series they have collected from before.
Find the maximum total number of unique stickers the student can collect.
Parameters:
• Series: INTEGER ARRAY (Array of size N, where Series[i] denotes the series of the i-th sticker,
1≤Series[i]≤109)
Test Cases:
Case 1:
Input:
Output:
3
• Unique series: {1, 2, 3}. Number of unique stickers per series: 1 for each.
• Possible sequences:
• Start with 1 (from series 1) -> next must be 2 (1 from series 2, 1 from series 3). Total = 1 + 2 = 3.
• Start with 1 (from series 2) -> next must be 2 (1 from series 1, 1 from series 3). Total = 1 + 2 = 3.
• Start with 1 (from series 3) -> next must be 2 (1 from series 1, 1 from series 2). Total = 1 + 2 = 3.
• Start with 2 (1 from series 1, 1 from series 2) -> next must be 4 (impossible with only 1 unique
from series 3). Total = 2.
• Start with 2 (1 from series 1, 1 from series 3) -> next must be 4 (impossible with only 1 unique
from series 2). Total = 2.
• Start with 2 (1 from series 2, 1 from series 3) -> next must be 4 (impossible with only 1 unique
from series 1). Total = 2.
• Start with 3 (1 from series 1, 1 from series 2, 1 from series 3) -> next must be 6 (impossible). Total
= 3.
Case 2:
Input:
10
Output:
4
• Unique series: {1, 2, 3, 4}. Number of unique stickers per series: 1 for each.
• Possible sequences:
• Start 1 (series 1) -> next 2 (series 2 & 3) -> next 4 (series 4 - impossible). Total = 3.
• Start 1 (series 1) -> next 2 (series 2 & 4) -> next 4 (series 3 - impossible). Total = 3.
• Start 1 (series 1) -> next 2 (series 3 & 4) -> next 4 (series 2 - impossible). Total = 3.
• Start 1 (series 2) -> next 2 (series 1 & 3) -> next 4 (series 4 - impossible). Total = 3.
• Start 1 (series 2) -> next 2 (series 1 & 4) -> next 4 (series 3 - impossible). Total = 3.
• Start 1 (series 2) -> next 2 (series 3 & 4) -> next 4 (series 1 - impossible). Total = 3.
• Start 1 (series 3) -> next 2 (series 1 & 2) -> next 4 (series 4 - impossible). Total = 3.
• Start 1 (series 3) -> next 2 (series 1 & 4) -> next 4 (series 2 - impossible). Total = 3.
• Start 1 (series 3) -> next 2 (series 2 & 4) -> next 4 (series 1 - impossible). Total = 3.
• Start 1 (series 4) -> next 2 (series 1 & 2) -> next 4 (series 3 - impossible). Total = 3.
• Start 1 (series 4) -> next 2 (series 1 & 3) -> next 4 (series 2 - impossible). Total = 3.
• Start 1 (series 4) -> next 2 (series 2 & 3) -> next 4 (series 1 - impossible). Total = 3.
Case 3:
Input:
1
Output:
• Can only start with 1, cannot proceed as there are no other series.
Case 4:
Input:
Output:
This sticker collection problem captures the essence of the original restaurant dish problem with the
constraints of sequential steps, doubling the count, and not repeating the "type" (series). The goal
remains to maximize the total number of unique items collected.
Solution:
def solve():
n = int(input())
unique_series_counts = Counter(series)
unique_series = set(series)
num_unique_series = len(unique_series)
max_stickers = 0
nonlocal max_stickers
num_remaining = len(remaining_series)
find_max_stickers(
collected_series | set(next_group),
current_stickers + next_collection_size,
next_collection_size * 2
# Try starting with collecting 's' unique stickers from 's' different series
solve()
Q3)
You are given an array A of size N containing integers. You are allowed to choose at most one pair of
adjacent elements (distance of 1) and swap them. Find the lexicographically smallest array possible after
performing at most one such swap.
Parameters:
Test Cases:
Case 1:
Input:
Output:
231
• N=3
• A=[3,2,1]
Case 2:
Input:
Output:
1234
• N=4
• A=[1,2,3,4]
Case 3:
Input:
Output:
1231
• N=4
• A=[2,1,3,1]
Input:
Output:
15428
• N=5
• A=[5,1,4,2,8]
• Single Modification: You are allowed to perform at most one operation (one swap in both
problems).
• Constraint on the Operation: The swap has a constraint (distance at most K in the original,
distance exactly 1 in this similar question).
• Lexicographical Ordering: The goal is to find the lexicographically smallest array after the allowed
operation.
• Checking Possibilities: The core logic to solve both involves trying all valid single swaps and
comparing the resulting arrays lexicographically to find the smallest one.
Solution :
def solve():
n = int(input())
best_a = list(a)
temp_a = list(a)
best_a = temp_a
print(*best_a)
# Test Case 1
input1_n = 3
input1_a = [3, 2, 1]
original_input = __builtins__.input
solve()
__builtins__.input = original_input
print("-" * 20)
# Test Case 2
print("Test Case 2:")
input2_n = 4
input2_a = [1, 2, 3, 4]
original_input = __builtins__.input
solve()
__builtins__.input = original_input
print("-" * 20)
# Test Case 3
input3_n = 4
input3_a = [2, 1, 3, 1]
original_input = __builtins__.input
solve()
__builtins__.input = original_input
print("-" * 20)
# Test Case 4
input4_n = 5
input4_a = [5, 1, 4, 2, 8]
solve()
__builtins__.input = original_input
print("-" * 20)
You are given an array A of size N containing positive integers. You can rearrange the elements of this
array in any order. You want to partition this rearranged array into some contiguous subarrays such that
all the subarrays have the same sum. You want to make the number of subarrays as large as possible.
What is the maximum number of subarrays you can get?
Parameters:
Test Cases:
Case 1:
Input:
2
1
Output:
• We can partition it into 3 subarrays with sum 37 (not possible with integers).
• Rearrange as [1,2,1,2,1]. Sum = 7. Not divisible by any number > 1. Output should be 1.
Case 2:
Input:
Output:
Case 3:
Input:
4
1
Output:
• We can partition it into 4 subarrays with sum 4/4=1: [1], [1], [1], [1].
Case 4:
Input:
Output:
• We can partition it into 4 subarrays with sum 12/4=3: [1,1,1], [1,2], [2,1], [2] - No.
Solution :
import math
def solve():
n = int(input())
a = list(map(int, input().split()))
total_sum = sum(a)
max_subarrays = 1
if total_sum % num_subarrays == 0:
if n % num_subarrays == 0:
required_counts = Counter()
for x in a:
required_counts[x] += 1
possible = True
for _ in range(num_subarrays):
current_subarray_counts = Counter()
current_subarray_sum = 0
temp_counts = required_counts.copy()
elements_added = 0
current_subarray_counts[val] += 1
current_subarray_sum += val
temp_counts[val] -= 1
elements_added += 1
possible = False
break
else:
required_counts -= current_subarray_counts
if possible:
print(max_subarrays)
# Test Case 1
print("Case #1:")
input1_n = 5
input1_a = [1, 2, 1, 2, 1]
original_input = __builtins__.input
solve()
__builtins__.input = original_input
print("-" * 20)
# Test Case 2
print("Case #2:")
input2_n = 6
input2_a = [1, 2, 3, 1, 2, 3]
original_input = __builtins__.input
solve()
__builtins__.input = original_input
print("-" * 20)
# Test Case 3
print("Case #3:")
input3_n = 4
input3_a = [1, 1, 1, 1]
original_input = __builtins__.input
solve()
__builtins__.input = original_input
print("-" * 20)
# Test Case 4
print("Case #4:")
input4_n = 8
input4_a = [1, 1, 2, 2, 1, 1, 2, 2]
original_input = __builtins__.input
__builtins__.input = original_input
print("-" * 20)
You are given an array of size N. You need to transform this array into a valley.
By valley, we mean:
• As you move from both ends to the center, each next element should be exactly one less than the
previous until a minimum is reached in the middle.
• Think of the array shape like a valley, decreasing toward the center and then mirroring back up.
The array should be symmetric and the difference between adjacent elements must be exactly 1 as you
approach the center.
✅ Examples of valleys:
• [3, 2, 1, 2, 3] ✅
• [5, 4, 3, 4, 5] ✅
• [6, 5, 4, 4, 5, 6] ✅
❌ Not valleys:
• [3, 2, 0, 2, 3] ❌ (jumps by 2)
Your Task:
Find the minimum number of elements that should be changed in order to make the array a valley.
You can make any changes (including making elements negative or zero).
Input Format:
• The first line contains an integer N — the number of elements in the array.
1 ≤ N ≤ 10^5
Output Format:
• A single integer — the minimum number of changes required to convert the array into a valley.
Test Cases:
Test Case 1:
makefile
CopyEdit
Input:
12345
Output:
Test Case 2:
makefile
CopyEdit
Input:
2234322
Output:
3
Test Case 3:
makefile
CopyEdit
Input:
443322
Output:
def solve():
n = int(input())
min_changes = n
for peak in range(1, 2 * 10**5 + 2): # Iterate through a reasonable range of peak values
temp_arr = [0] * n
changes = 0
possible = True
for i in range(mid):
if expected <= 0:
possible = False
break
temp_arr[i] = expected
changes += 1
if not possible:
continue
if mid < n:
temp_arr[mid] = peak
changes += 1
if expected <= 0:
possible = False
break
temp_arr[i] = expected
changes += 1
if possible:
print(min_changes)
if __name__ == "__main__":
solve()
Q1)
The lead role in Joker is that of Mannar Mannan, a mentally unsound and poor activist who thinks he is
the people-appointed President of India. Mannan falls in love with Malliga, courts her and wins her over
and they get married. Soon , they are expecting a child and they are very excited about it. As most other
to-be parents, they choose to consult astrologers to help with choosing the right name for their baby.
Naming a baby based on his or her sun sign or raashi is considered to bring good luck. The astrologer tells
them that it is good to name their kid such that the kid’s name is the smallest substring in dad’s name
containing all characters of mom’s name efficiently. Can you help them in shortlisting the names by
writing a program to find the smallest substring in string1 containing all characters of string2 efficiently.
[Hint : i.e Find the smallest window in string 1 containing all characters of string 2] ]
Input Format
Input consists of 2 strings. The first string corresponds to String 1 The second string corresponds to String
2. The maximum length of the strings is 100.
Constraints
--
Output Format
Output consists of a string. Assume that it is always possible to find the desired string.
Sample Input 0
thisisateststring
tist
Sample Output 0
tstri
Sample Input 1
this is a pen
npe
Sample Output 1
pen
Sample Input 2
this is a pen
htis
Sample Output 2
this
Sample Input 3
thandapani
ana
Sample Output 3
anda
Sample Input 4
gokulkumar
kom
Sample Output 4
okulkum
Sample Input 5
amphisoft
pit
Sample Output 5
phisoft
Sample Input 6
Sample Output 6
t stri
Sample Input 7
this
Sample Output 7
this
Sample Input 8
pradeep
ap
Sample Output 8
pra
Q2)
In the land of Rhyme, the King and his people always speak in rhymes. They are so accustomed in
conversing using rhymes that at one point it became monotonous. So what was once a source of
happiness and amusement is now creating a strange emotion within the heart of the people. The
productivity of the people has become less and more importantly, the happiness index of the land has
plummeted. The experts have investigated the whole matter and reported that speaking in rhyme is not
the problem; it is the monotony of the same thing that is affecting the people. In fact they suggested
changing the definition of rhyme slightly. One of their recommendations is to introduce a new concept of
"richness" in a sentence.
A sentence would be termed rich if it starts and ends with the same word! The King seems to like this
definition. But he is finding it difficult to even say a simple meaningful sentence that is "rich". The King
became quite anxious. Your boss, King’s ICT adviser, suggested that a competition among the general
people should be thrown where the participants would have to submit a piece (story/poem/essay etc.)
full of rich sentences. Then the richest pieces would be judged and be awarded. The King made a decree
accordingly. Your boss was ordered to formulate a judging scheme for the pieces and write a program
immediately to do the judgment. And as usual he formulated something and asked you to implement
that. What he has asked you to do is as follows. You will take as input a piece as a character array. And
output another array where each position will give the richness of the piece up to that position.
“But you said to calculate the richness at each position”! You inquired.
“Yes, of course! When you calculate up to a position, you will have to assume that the piece ends at that
position.” Your boss smiled. He seemed to be quite happy in formulating this.
You asked again, "Don't I need to think about the word boundaries?"
“Not now, my son. We will think about it later. Do it without considering word boundaries for now. You
will consider the input character by character”. He assured you. He seemed all the more content with his
own formulation and probably was not seeing the possible pitfalls. He continued, "And one other point;
richness of the first position would always be 0."
Meaningful, you thought. But you had to ask a final question. “How would you then finally compute the
richness of the total piece using all these information? What will be the formula?”
Your boss seemed perplexed. He did not think this through, as it seemed. So, he said, “You need not
worry about that. Do as I said. Just remember that the input size could be quite large.”
You knew that you have to stop asking and start coding now. “Yes, boss!” you said. You also realized the
implication of the last direction of your boss. Few years back there was another competition on literary
works. And the size of some pieces was 4 million characters!
Input Format
Input contains a string of lowercase English letters. Assume the total length of input is less than 1000
Constraints
--
Output Format
Output a line containing several integers, separated by space. The number of integers must be same as
the length of the input string. The Integer at a specific position must represent the richness of the input
string up to that position. Refer sample input and output for formatting details.
Sample Input 0
accb
Sample Output 0
0000
Sample Input 1
dacbbcbcbcbcdcbbbcbcbcbcbcbcdacbbcbcdcbbbcbcdcbbdcbb
Sample Output 1
0000000000001000000000000000123456781000000010001000
Sample Input 2
abababbbbaaabbbbbababab
Sample Output 2
00123400011120000123456
Sample Input 3
atofpgrwk
Sample Output 3
000000000
Sample Input 4
dacc
Sample Output 4
0000
Sample Input 5
cbda
Sample Output 5
0000
Sample Input 6
ababbacdbacdbacd
Sample Output 6
0012010001000100
Sample Input 7
bdblhc
Sample Output 7
001000
Sample Input 8
jgojeqp
Sample Output 8
0001000
Sample Input 9
dcbb
Sample Output 9
0000
Sample Input 10
fdcdd
Sample Output 10
00000
Sample Input 11
oebmgoca
Sample Output 11
00000100
Q3)
SMS language or textese (also known as txt-speak, txtese, chatspeak, txt, txtspk, txtk, txto, texting
language, txt lingo, SMSish, txtslang,or txt talk) is a term for the abbreviations and slang commonly used
with mobile phone text messaging.
Many grandpa's have started sending SMSes to their grand children. But they are not familiar with the
SMS lingo.
Can you help them by writing a program that would convert a given text in proper English to SMS lingo?
Consider only the 4 words listed above.
Input Format
Input consists of a single string. Assume that the maximum length of the string is 200 and all letters are in
lower-case.
Constraints
--
Output Format
Output consists of a single string.
Sample Input 0
Sample Output 0
Sample Input 1
Sample Output 1
Sample Input 2
Sample Output 2
s u come in
Sample Input 3
Sample Output 3
Sample Input 4
Sample Output 4
Q4)
The lead role in Joker is that of Mannar Mannan, a mentally unsound and poor activist who thinks he is
the people-appointed President of India. Mannan falls in love with Malliga, courts her and wins her over
and they get married. Soon , they are expecting a child and they are very excited about it. As most other
to-be parents, they choose to consult astrologers to help with choosing the right name for their baby.
Naming a baby based on his or her sun sign or raashi is considered to bring good luck. The astrologer tells
them that it is good to name their kid such that the kid’s name is an interleaving of the mom’s name and
dad’s name.
Can you help them in shortlisting the names by writing a program to find whether string C is an
interleaving of strings A and B? [Hint : C is said to be interleaving A and B, if it contains all characters of A
and B and order of all characters in individual strings is preserved.
ABCD
ACBD
ACDB
CABD
CADB
CDAB
Input Format
Input consists of 3 strings. The first string corresponds to A. The second string corresponds to B. The third
string corresponds to C. Assume that there are no common characters between strings A and B. All input
strings consist of only upper case alphabets. The maximum length of the strings is 100.
Constraints
--
Output Format
Sample Input 0
AB
CD
ACBD
Sample Output 0
YES
Sample Input 1
PUNITHA
SOJ
SPAUONJITH
Sample Output 1
NO
Sample Input 2
AB
CD
CDAB
Sample Output 2
YES
Sample Input 3
AB
CD
ACDB
Sample Output 3
YES
Sample Input 4
AB
CD
ABCG
Sample Output 4
NO
Sample Input 5
PRADEEP
SMITH
PSRMAIDETPH
Sample Output 5
NO
Sample Input 6
AB
CD
CABD
Sample Output 6
YES
Sample Input 7
AB
CD
BDCD
Sample Output 7
NO
Sample Input 8
PUNITHA
SOJ
SOJPUNITHA
Sample Output 8
YES
Sample Input 9
PUNITH
KANNAN
PUNITHAKANNAN
Sample Output 9
NO
Sample Input 10
AB
CD
BCAD
Sample Output 10
NO
Sample Input 11
PUNITHA
SOJ
PSUNIOTJHA
Sample Output 11
YES
Sample Input 12
PRADEEP
SMITH
PSRMAIDEETPH
Sample Output 12
YES
Sample Input 13
AB
CD
ABCD
Sample Output 13
YES
Sample Input 14
AB
CD
CADB
Sample Output 14
YES
Q5)
The lead role in Joker is that of Mannar Mannan, a mentally unsound and poor activist who thinks he is
the people-appointed President of India. Mannan falls in love with Malliga, courts her and wins her over
and they get married. Soon , they are expecting a child and they are very excited about it. They were
exhilarated to know that Malliga is carrying twins. As most other to-be parents, they choose to consult
astrologers to help with choosing the right name for their baby. Naming a baby based on his or her sun
sign or raashi is considered to bring good luck. The astrologer tells them that it is good to name the twins
in such a way that their names are isomorphic strings.
Can you help them in shortlisting the names by writing a program to find whether the two strings A and B
are isomorphic?
[Hint : Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every
character of str1 to every character of str2. And all occurrences of every character in ‘str1′ map to same
character in ‘str2′ Example : Input: String A = "aab", String B = "xxy" Output: YES 'a' is mapped to 'x' and 'b'
is mapped to 'y'.
Input: String A = "aab", String B = "xyz" Output: NO One occurrence of 'a' in str1 has 'x' in str2 and other
occurrence of 'a' has 'y'. Two words are called isomorphic if the letters in one word can be remapped to
get the second word. Remapping a letter means replacing all occurrences of it with another letter. The
ordering of the letters remains unchanged. No two letters may map to the same letter, but a letter may
map to itself. ]
Input Format
Input consists of 2 strings. The first string corresponds to A. The second string corresponds to B. The
maximum length of the strings is 100.
Constraints
--
Output Format
Sample Input 0
paper
title
Sample Output 0
YES
Sample Input 1
voter
seater
Sample Output 1
NO
Sample Input 2
punitha
pradeep
Sample Output 2
NO
Sample Input 3
aab
xyx
Sample Output 3
NO
Sample Input 4
owl
ant
Sample Output 4
YES
Sample Input 5
beep
soon
Sample Output 5
YES
Sample Input 6
cacccdaabc
cdcccaddbc
Sample Output 6
YES
Sample Input 7
cacccdaabc
bdbcadbbdc
Sample Output 7
NO
Sample Input 8
foo
bar
Sample Output 8
NO
Sample Input 9
aab
xxy
Sample Output 9
YES
Sample Input 10
cacccdaabc
bdbbbaddcb
Sample Output 10
YES
Sample Input 11
abca
zbxz
Sample Output 11
YES
Sample Input 12
ab
cd
Sample Output 12
YES
Sample Input 13
abca
opqr
Sample Output 13
NO
Sample Input 14
aab
xyz
Sample Output 14
NO
Sample Input 15
seater
voter
Sample Output 15
NO
Sample Input 16
ab
hh
Sample Output 16
NO
Sample Input 17
egg
add
Sample Output 17
YES
Q6)
Stickler is a thief and wants to loot money from a society of n houses placed in a line. He is a weird person
and follows a rule while looting the houses and according to the rule he will never loot two consecutive
houses. At the same time, he wants to maximize the amount he loots. The thief knows which house has
what amount of money but is unable to find the maximum amount he can end up with. He asks for your
help to find the maximum money he can get if he strictly follows the rule. Each house has a[i] amount of
money present in it.
Input Format
Each test case contains an integer n which denotes the number of elements in the array a[]. Next line
contains space separated n elements in the array a[].
Constraints
1<=n<=1000 1<=a[i]<=10000
Output Format
Print an integer which denotes the maximum amount he can take home.
Sample Input 0
5 5 10 100 10 5
Sample Output 0
110
Sample Input 1
123
Sample Output 1
Sample Input 2
10 10 10 10 10
Sample Output 2
30
Sample Input 3
110 10 10 100 90
Sample Output 3
210
Sample Input 4
10 30 20 20 10 30
Sample Output 4
80
Sample Input 5
0 0 0 100 0 0
Sample Output 5
100
Sample Input 6
4126
Sample Output 6
10
Q7)
Given a positive number x, print all Jumping Numbers smaller than or equal to x. A number is called as a
Jumping Number if all adjacent digits in it differ by 1. The difference between ‘9’ and ‘0’ is not considered
as 1. All single digit numbers are considered as Jumping Numbers. For example 7, 8987 and 4343456 are
Jumping numbers but 796 and 89098 are not.
Input Format
The first line of the input contains T denoting the number of testcases. Each testcase contain a positive
number 'x'.
Constraints
Output Format
All the jumping numbers less than 'x' are generated in increasing order of the most significant digit. See
example for better understanding.
Sample Input 0
2
10
50
Sample Output 0
0 1 10 2 3 4 5 6 7 8 9
0 1 10 12 2 21 23 3 32 34 4 43 45 5 6 7 8 9
Sample Input 1
30
Sample Output 1
0 1 10 12 2 21 23 3 4 5 6 7 8 9
Sample Input 2
40
Sample Output 2
0 1 10 12 2 21 23 3 32 34 4 5 6 7 8 9
Sample Input 3
200
Sample Output 3
Sample Input 4
300
Sample Output 4
Q8)
Given an array of size N , print the total count of sub-arrays having their sum equal to 0
Input Format
First line of the input contains an integer T denoting the number of test cases. Each test case consists of
two lines. First line of each test case contains an Integer N denoting the size of the array and the second
line contains N space separated integers.
Constraints
1<= N <= 10000 -100 <= A[i] <= 100 where i <= N
Output Format
Corresponding to each test case, print the total number of subarrays whose sum is equal to 0.
Sample Input 0
005500
10
6 -1 -3 4 -2 2 4 6 -12 -7
Sample Output 0
Sample Input 1
00550
6 -1 -3 4 -2 2 4 6 -12
Sample Output 1
Sample Input 2
2
4
0055
6 -1 -3 4 -2 2 4 6
Sample Output 2
Sample Input 3
010
6 -1 -3 4 -2 2 4 6
Sample Output 3
Sample Input 4
1 -1 2 -1 0
Sample Output 4
Q9)
A string with parentheses is well bracketed if all parentheses are matched: every opening bracket has a
matching closing bracket and vice versa.
Write a Python function wellbracketed(s) that takes a string s containing parentheses and returns True if s
is well bracketed and False otherwise.
Input Format
A single line string
Constraints
None
Output Format
Sample Input 0
22)
Sample Output 0
False
Sample Input 1
(a+b)(a-b)
Sample Output 1
True
Sample Input 2
(a(b+c)-d)((e+f)
Sample Output 2
False
Sample Input 3
(7(89)
Sample Output 3
False
Sample Input 4
(7(8()9()))
Sample Output 4
True
Sample Input 5
)1(
Sample Output 5
False
Q10)
A bigger N*N matrix is passed as the input. Also a smaller M*M matrix is passed as the input. The program
must print 'TRUE' if the smaller matrix elements can be found in the bigger matrix irrespective of their
position. Else program must print 'FALSE' in case of absence or duplication of any smaller matrix element.
Input Format:
Next N lines will contain the values in the N*N matrix with each value separated by one or more spaces.
Next M lines will contain the values in the M*M matrix with each value separated by one or more spaces.
Output Format:
Example1:
Input:
327591358243524
Output: TRUE
Example2: Input: 3 2 4 5 9 1 3 5 8 2 4 3 7 2 4
Output: FALSE
Input Format
Next N lines will contain the values in the N*N matrix with each value separated by one or more spaces.
Next M lines will contain the values in the M*M matrix with each value separated by one or more spaces.
Constraints
None
Output Format
Sample Input 0
3
459
135
824
35
24
Sample Output 0
TRUE
Sample Input 1
12345
6 7 8 9 10
20 21 22 23 24
11 12 13 14 15
12345
123
456
789
Sample Output 1
TRUE
Sample Input 2
12345
16 7 8 9 10
20 21 22 23 24
11 12 13 14 9
12345
123
456
789
Sample Output 2
FALSE
Sample Input 3
459
135
824
40 50
20 40
Sample Output 3
FALSE
Sample Input 4
123
456
789
122
455
788
Sample Output 4
FALSE
Sample Input 5
123
456
789
123
456
789
Sample Output 5
TRUE
Q11)
Given a keypad as shown in diagram, and a n digit number, list all words which are possible by pressing
these numbers.
1 2 3
abc def
4 5 6
7 8 9
* 0 #
Input Format
The first line of input contains an integer T denoting the number of test cases. The first line of each test
case is N,N is the number of digits. The second line of each test case contains D[i], N number of digits.
Constraints
1 ≤ T ≤ 10 1 ≤ N ≤ 5 2 ≤ D[i] ≤ 9
Output Format
Print all possible words from phone digits with single space.
Sample Input 0
234
Sample Output 0
adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi
Sample Input 1
5279
Sample Output 1
japw japx japy japz jaqw jaqx jaqy jaqz jarw jarx jary jarz jasw jasx jasy jasz jbpw jbpx jbpy jbpz jbqw jbqx
jbqy jbqz jbrw jbrx jbry jbrz jbsw jbsx jbsy jbsz jcpw jcpx jcpy jcpz jcqw jcqx jcqy jcqz jcrw jcrx jcry jcrz jcsw
jcsx jcsy jcsz kapw kapx kapy kapz kaqw kaqx kaqy kaqz karw karx kary karz kasw kasx kasy kasz kbpw
kbpx kbpy kbpz kbqw kbqx kbqy kbqz kbrw kbrx kbry kbrz kbsw kbsx kbsy kbsz kcpw kcpx kcpy kcpz kcqw
kcqx kcqy kcqz kcrw kcrx kcry kcrz kcsw kcsx kcsy kcsz lapw lapx lapy lapz laqw laqx laqy laqz larw larx lary
larz lasw lasx lasy lasz lbpw lbpx lbpy lbpz lbqw lbqx lbqy lbqz lbrw lbrx lbry lbrz lbsw lbsx lbsy lbsz lcpw
lcpx lcpy lcpz lcqw lcqx lcqy lcqz lcrw lcrx lcry lcrz lcsw lcsx lcsy lcsz
Sample Input 2
777
Sample Output 2
ppp ppq ppr pps pqp pqq pqr pqs prp prq prr prs psp psq psr pss qpp qpq qpr qps qqp qqq qqr qqs qrp qrq
qrr qrs qsp qsq qsr qss rpp rpq rpr rps rqp rqq rqr rqs rrp rrq rrr rrs rsp rsq rsr rss spp spq spr sps sqp sqq
sqr sqs srp srq srr srs ssp ssq ssr sss
Sample Input 3
1
123
Sample Input 4
234
Sample Output 4
adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi
Sample Input 5
23457
Sample Output 5
adgjp adgjq adgjr adgjs adgkp adgkq adgkr adgks adglp adglq adglr adgls adhjp adhjq adhjr adhjs adhkp
adhkq adhkr adhks adhlp adhlq adhlr adhls adijp adijq adijr adijs adikp adikq adikr adiks adilp adilq adilr
adils aegjp aegjq aegjr aegjs aegkp aegkq aegkr aegks aeglp aeglq aeglr aegls aehjp aehjq aehjr aehjs
aehkp aehkq aehkr aehks aehlp aehlq aehlr aehls aeijp aeijq aeijr aeijs aeikp aeikq aeikr aeiks aeilp aeilq
aeilr aeils afgjp afgjq afgjr afgjs afgkp afgkq afgkr afgks afglp afglq afglr afgls afhjp afhjq afhjr afhjs afhkp
afhkq afhkr afhks afhlp afhlq afhlr afhls afijp afijq afijr afijs afikp afikq afikr afiks afilp afilq afilr afils bdgjp
bdgjq bdgjr bdgjs bdgkp bdgkq bdgkr bdgks bdglp bdglq bdglr bdgls bdhjp bdhjq bdhjr bdhjs bdhkp bdhkq
bdhkr bdhks bdhlp bdhlq bdhlr bdhls bdijp bdijq bdijr bdijs bdikp bdikq bdikr bdiks bdilp bdilq bdilr bdils
begjp begjq begjr begjs begkp begkq begkr begks beglp beglq beglr begls behjp behjq behjr behjs behkp
behkq behkr behks behlp behlq behlr behls beijp beijq beijr beijs beikp beikq beikr beiks beilp beilq beilr
beils bfgjp bfgjq bfgjr bfgjs bfgkp bfgkq bfgkr bfgks bfglp bfglq bfglr bfgls bfhjp bfhjq bfhjr bfhjs bfhkp
bfhkq bfhkr bfhks bfhlp bfhlq bfhlr bfhls bfijp bfijq bfijr bfijs bfikp bfikq bfikr bfiks bfilp bfilq bfilr bfils cdgjp
cdgjq cdgjr cdgjs cdgkp cdgkq cdgkr cdgks cdglp cdglq cdglr cdgls cdhjp cdhjq cdhjr cdhjs cdhkp cdhkq
cdhkr cdhks cdhlp cdhlq cdhlr cdhls cdijp cdijq cdijr cdijs cdikp cdikq cdikr cdiks cdilp cdilq cdilr cdils cegjp
cegjq cegjr cegjs cegkp cegkq cegkr cegks ceglp ceglq ceglr cegls cehjp cehjq cehjr cehjs cehkp cehkq cehkr
cehks cehlp cehlq cehlr cehls ceijp ceijq ceijr ceijs ceikp ceikq ceikr ceiks ceilp ceilq ceilr ceils cfgjp cfgjq
cfgjr cfgjs cfgkp cfgkq cfgkr cfgks cfglp cfglq cfglr cfgls cfhjp cfhjq cfhjr cfhjs cfhkp cfhkq cfhkr cfhks cfhlp
cfhlq cfhlr cfhls cfijp cfijq cfijr cfijs cfikp cfikq cfikr cfiks cfilp cfilq cfilr cfils
Q12)
Given an integer N as the input, print the pattern as given in the Example Input/Output section.
Input Format : The first line contains N.
Input : 4
Input Format
Constraints
Output Format
Sample Input 0
Sample Output 0
1*2*3*4*17*18*19*20
--5*6*7*14*15*16
----8*9*12*13
------10*11
Sample Input 1
Sample Output 1
1*2*3*4*5*6*7*50*51*52*53*54*55*56
--8*9*10*11*12*13*44*45*46*47*48*49
----14*15*16*17*18*39*40*41*42*43
------19*20*21*22*35*36*37*38
--------23*24*25*32*33*34
----------26*27*30*31
------------28*29
Sample Input 2
Sample Output 2
1*2*3*4*5*6*37*38*39*40*41*42
--7*8*9*10*11*32*33*34*35*36
----12*13*14*15*28*29*30*31
------16*17*18*25*26*27
--------19*20*23*24
----------21*22
Sample Input 3
10
Sample Output 3
1*2*3*4*5*6*7*8*9*10*101*102*103*104*105*106*107*108*109*110
--11*12*13*14*15*16*17*18*19*92*93*94*95*96*97*98*99*100
----20*21*22*23*24*25*26*27*84*85*86*87*88*89*90*91
------28*29*30*31*32*33*34*77*78*79*80*81*82*83
--------35*36*37*38*39*40*71*72*73*74*75*76
----------41*42*43*44*45*66*67*68*69*70
------------46*47*48*49*62*63*64*65
--------------50*51*52*59*60*61
----------------53*54*57*58
------------------55*56
Sample Input 4
12
Sample Output 4
1*2*3*4*5*6*7*8*9*10*11*12*145*146*147*148*149*150*151*152*153*154*155*156
--13*14*15*16*17*18*19*20*21*22*23*134*135*136*137*138*139*140*141*142*143*144
----24*25*26*27*28*29*30*31*32*33*124*125*126*127*128*129*130*131*132*133
------34*35*36*37*38*39*40*41*42*115*116*117*118*119*120*121*122*123
--------43*44*45*46*47*48*49*50*107*108*109*110*111*112*113*114
----------51*52*53*54*55*56*57*100*101*102*103*104*105*106
------------58*59*60*61*62*63*94*95*96*97*98*99
--------------64*65*66*67*68*89*90*91*92*93
----------------69*70*71*72*85*86*87*88
------------------73*74*75*82*83*84
--------------------76*77*80*81
----------------------78*79
Sample Input 5
Sample Output 5
1*2*5*6
--3*4
Sample Input 6
20
Sample Output 6
1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20*401*402*403*404*405*406*407*408*40
9*410*411*412*413*414*415*416*417*418*419*420
--
21*22*23*24*25*26*27*28*29*30*31*32*33*34*35*36*37*38*39*382*383*384*385*386*387*388*
389*390*391*392*393*394*395*396*397*398*399*400
----
40*41*42*43*44*45*46*47*48*49*50*51*52*53*54*55*56*57*364*365*366*367*368*369*370*371
*372*373*374*375*376*377*378*379*380*381
------
58*59*60*61*62*63*64*65*66*67*68*69*70*71*72*73*74*347*348*349*350*351*352*353*354*35
5*356*357*358*359*360*361*362*363
--------
75*76*77*78*79*80*81*82*83*84*85*86*87*88*89*90*331*332*333*334*335*336*337*338*339*3
40*341*342*343*344*345*346
----------
91*92*93*94*95*96*97*98*99*100*101*102*103*104*105*316*317*318*319*320*321*322*323*32
4*325*326*327*328*329*330
------------
106*107*108*109*110*111*112*113*114*115*116*117*118*119*302*303*304*305*306*307*308*3
09*310*311*312*313*314*315
--------------
120*121*122*123*124*125*126*127*128*129*130*131*132*289*290*291*292*293*294*295*296*2
97*298*299*300*301
----------------
133*134*135*136*137*138*139*140*141*142*143*144*277*278*279*280*281*282*283*284*285*2
86*287*288
------------------
145*146*147*148*149*150*151*152*153*154*155*266*267*268*269*270*271*272*273*274*275*2
76
--------------------
156*157*158*159*160*161*162*163*164*165*256*257*258*259*260*261*262*263*264*265
----------------------166*167*168*169*170*171*172*173*174*247*248*249*250*251*252*253*254*255
------------------------175*176*177*178*179*180*181*182*239*240*241*242*243*244*245*246
--------------------------183*184*185*186*187*188*189*232*233*234*235*236*237*238
----------------------------190*191*192*193*194*195*226*227*228*229*230*231
------------------------------196*197*198*199*200*221*222*223*224*225
--------------------------------201*202*203*204*217*218*219*220
----------------------------------205*206*207*214*215*216
------------------------------------208*209*212*213
--------------------------------------210*211
Q13)
To encrypt the message Jill will first decide on the number of columns C to use. The Jill will pad the
message with letters chosen randomly so that they form a rectangular matrix. Finally Jill will write down
the message as encrypted by navigating the rows from left to right and then right to left. Write a program
which must accept the encrypted message M as input and then extract the original message from the
encrypted message based on the value of C.
Input Format: First line will contain the string value of encrypted message M. Second line will contain the
integer value of the column used for the encryption.
Output Format: First line will contain the string value of decrypted message along with any additional
padding letters.
Input Format
First line will contain the string value of encrypted message M. Second line will contain the integer value
of the column used for the encryption.
Constraints
Output Format
First line will contain the string value of decrypted message along with any additional padding letters.
Sample Input 0
midinadiazne
Sample Output 0
madeinindiaz
Sample Input 1
reegrenaggreciihunn1
Sample Output 1
raghuengineeringrec1
Sample Input 2
grgoooodfd9o
Sample Output 2
goodforgood9
Sample Input 3
TRANTORHGMOHEGMIELDWSIRP
Sample Output 3
THEPROGRAMMINGISTHEWORLD
Sample Input 4
topper
Sample Output 4
topper
Q14)
Given an array of distinct elements, rearrange the elements of array in zig-zag fashion in O(n) time. The
converted array should be in form a < b > c < d > e < f. Comparisons must be done in the relative order of
elements in the original array.
Input Format
The first line of input contains an integer N denoting the size of array. The second line contains N space-
separated integers A1, A2, ..., AN denoting the elements of the array.
Constraints
1 ≤ N ≤ 100 0 ≤A[i]<=10000
Output Format
Sample Input 0
4378621
Sample Output 0
3748261
Sample Input 1
1432
Sample Output 1
1423
Sample Input 2
123456
Sample Output 2
132546
Sample Input 3
123456
Sample Output 3
132546
Sample Input 4
11
Sample Output 4
Q15)
Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the
elements to its right side. The rightmost element is always a leader.
Input Format
The first line of input contains an integer T denoting the number of test cases. The description of T test
cases follows. The first line of each test case contains a single integer N denoting the size of array. The
second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Constraints
Output Format
16 17 4 3 5 2
12340
Sample Output 0
17 5 2
40
Sample Input 1
98 765 4321
Sample Output 1
987654321
Sample Input 2
123456789
Sample Output 2
Sample Input 3
11111
Sample Output 3
Sample Input 4
1
Sample Output 4
Q16)
Give a N*N square matrix, return an array of its anti-diagonals. Look at the example for more details.
For Example:
If the matrix is
123
456
789
[1],
[2, 4],
[3, 5, 7],
[6, 8],
[9]
Note: The input array given is in single line and you have to output the answer in one line only.
Input Format
The first line contains an integer T, depicting total number of test cases. Then following T lines contains an
integer N depicting the size of square matrix and next line followed by the value of array.
Constraints
1 ≤ T ≤ 30 1 ≤ N ≤ 20 0 ≤ A[i][j] ≤ 9
Output Format
Sample Input 0
12
34
123
456
789
Sample Output 0
1234
124357689
Sample Input 1
124357689
Sample Output 1
123456789
Sample Input 2
1234123412341234
Sample Output 2
1213214321432434
Sample Input 3
12345678912345678912345678912345678912345678912345678912345
6789123456789123456789
Sample Output 3
12132143215432165432176543218765432198765432198765432987654
3987654987659876987989
Sample Input 4
19
123456789
987654321
123456789
987654321
123456789
987654321
123456789
987654321
123456789
Sample Output 4
12938147295638165472974563818365472992745638118365472927456
3183654927451836927189
Sample Input 5
Sample Output 5
6
Sample Input 6
Q17)
A string is given which has letters from English alphabet and parentheses. The depth of a letter is defined
as the number of balanced parentheses it is surrounded by. Write a C program to find the depth of each
letter in the input string. Explanation:
(a(b)((cd)e)f)g
g is at depth 0 a and f are at depth 1 b and e are at depth 2 c and d are at depth 3
Input Format
An array of characters
Constraints
1) Input string can be of length 1 to 100. 2) The input will have only ‘(‘ , ‘)’ and letters from English
alphabet. 3) There will be no repetition of letters. 4) Only lowercase letters are used. 5) The letters can be
in any sequence. 6) The parentheses are always well balanced. Every '(' has a matching ')' that follows it
later in the string. Every ')' has a matching '(' before it in the input string. 7) Notice that there are no space
in the string.
Output Format
1) The depth of each letter separated by a space. 2) The order of the depth of the letters should be the
same order in which the letters appear in the input. 3)To mark the end of the output it should end with a
space and a ‘#’ character.
In this example, letters are appearing in the order p followed by r followed by q and s. They have depth of
0, 1, 2 and 1 respectively. Note that the depth is not printed in the order p,q,r,s (the alphabetical order)
but p,r,q,s (the order in which they appear in the input string).
Sample Input 0
(a(b)((cd)e)f)g
Sample Output 0
1233210#
Sample Input 1
a(b(c))(d)
Sample Output 1
0121#
Sample Input 2
a(b(c))(d(fe))
Sample Output 2
012122#
Sample Input 3
a(b(c))(d(f()e))
Sample Output 3
012122#
Sample Input 4
()
Sample Output 4
Sample Input 5
ab()(c(d(e(f)()(g)h)))
Sample Output 5
00123443#
Q18)
There is a class of N students and you have to find the top K marks scorers.You need to print the index of
the toppers of the class which will be same as the index of the student in the input array(use 0-based
indexing).First print the index of the students having highest marks then the students with second highest
and so on.If there are more than one students having same marks then print their indices in ascending
order.Suppose k = 2 and the students having highest marks have indices 0 and 5 and students having
second highest marks have indices 6 and 7 then output will be 0 5 6 7
Input Format
The first line of input consists of an integer T denoting the number of test cases .Each test case consists of
three lines first line consists of an integer N denoting the number of students of class second line consists
N spaced integers denoting the marks of students and third line consists of an integer K which denotes
the number of top scores you have to find.
Constraints
It is given that k will be such that its value will always be less than or equal to type of marks of students
Output Format
Single line output, denoting the indices of top k cores with space between them.
Sample Input 0
22131
Sample Output 0
301
Sample Input 1
472159
Sample Output 1
514
Sample Input 2
44444
Sample Output 2
0123401234
Sample Input 3
9 8 5 676655 45 98 1 1 1
Sample Output 3
35
Q19)
There are two singly linked lists in a system. By some programming error the end node of one of the
linked list got linked into the second list, forming a inverted Y shaped list. Write a program to get the point
where two linked lists merge.
Y ShapedLinked List
Above diagram shows an example with two linked list having 15 as intersection point.
Expected time complexity is O(m + n) where m and n are lengths of two linked lists
Input Format
You have to complete the method which takes two arguments as heads of two linked lists.
First line is number of test cases. Every test case has four lines. First line of every test case contains three
numbers, x (number of nodes before merge point in 1st list), y(number of nodes before merge point in
11nd list) and z (number of nodes after merge point). Next three lines contain x, y and z values.
Constraints
Output Format
The function should return data value of a node where two linked lists merge. If linked list do not merge
at any point, then it shoudl return -1.
Sample Input 0
232
10 20
30 40 50
5 10
230
10 20
30 40 50
Sample Output 0
-1
Sample Input 1
232
10 20
30 40 50
0 10
Sample Output 1
Sample Input 2
234
10 20
30 40 50
2 4 6 10
Sample Output 2
Sample Input 3
214
10 20
2 4 6 10
Sample Output 3
Sample Input 4
202
10 20
30
40
Sample Output 4
30
Sample Input 5
232
10 20
30 10 20
5 10
Sample Output 5
Q20)
There are 'n' ants on a 'n+1' length rod. The ants are numbered from 1 to n and are initially placed at
positions starting from position 1 till position n. They are moving either in left direction (denoted by '-1')
or in the right direction (denoted by '1'). Whenever an ant crosses the boundary of the rod it falls off the
rod. You are given the initial direction of the ants. Now, whenever two ants collide their direction
switches, i.e. the ant going in left direction ('-1) changes it's direction towards right ('1') and the ant going
in the right direction ('1') changes it's direction towards left ('-1'). Find last ant to fall off the rod. Note: In
case two ants are falling simultaneously in the end print the index of the lower indexed ant.
Input Format
Input Format: First line contains the integer 'n' denoting the total number of ants s.t. 1 <= n <= 1,000
Second line contains 'n' space separated numbers (either '1' or '-1') denoting the initial directions of the
ants.
Constraints
________________________________________
Output Format
Output Format: Output a single integer which is the index (lower index in case two ants are falling
simultaneously in the end) of the last ant to fall off the table.
Sample Input 0
11
Sample Output 0
Sample Input 1
1 -1 -1
Sample Output 1
Sample Input 2
-1 -1
Sample Output 2
Sample Input 3
1 1 -1 1 1 1 -1 1
Sample Output 3
3
Sample Input 4
10
1 -1 1 1 -1 1 -1 1 -1 -1
Sample Output 4
Sample Input 5
100
-1 -1 -1 -1 1 -1 -1 1 -1 1 -1 1 1 -1 -1 -1 1 -1 1 1 1 -1 1 1 1 -1 1 -1 1 -1 1 1 1 -1 -1 1 -1 -1 -1 1 -1 1 -1 1 -1 1 -1 1
1 1 1 1 -1 1 1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 -1 -1 1 1 1 1 -1 1 1 -1 -1 -1 -
1 1 1 -1
Sample Output 5
52
Sample Input 6
1000
1 1 1 -1 1 -1 1 -1 1 1 -1 -1 -1 1 -1 -1 1 -1 -1 1 -1 1 1 -1 -1 1 -1 -1 1 1 1 1 -1 1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 1 -1 1 -
1 -1 1 -1 1 -1 -1 1 -1 1 -1 -1 1 -1 1 1 1 -1 -1 1 -1 -1 -1 1 1 1 1 -1 1 1 1 -1 -1 1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 1
1 -1 -1 -1 1 1 1 1 1 -1 1 1 1 1 1 1 -1 1 1 -1 -1 1 1 -1 -1 -1 -1 -1 -1 -1 1 -1 1 -1 -1 -1 1 -1 -1 -1 -1 1 -1 1 1 -1 1 1 1
-1 -1 -1 -1 1 1 1 1 -1 1 -1 -1 1 1 1 -1 -1 1 1 -1 1 -1 1 -1 1 1 -1 1 1 1 -1 1 -1 -1 -1 1 -1 1 -1 1 1 1 1 1 -1 -1 1 -1 1 -
1 1 -1 -1 -1 1 -1 1 1 -1 -1 -1 -1 1 -1 -1 1 1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 -1 1 -1 -1 1 1 -1 1 -1 1 -1 1 -1 1 1 -1 1 1 1
1 -1 -1 -1 1 -1 1 -1 -1 1 1 -1 -1 1 1 1 1 -1 1 -1 1 1 1 1 1 1 -1 1 -1 -1 1 -1 -1 -1 1 1 1 -1 1 1 -1 -1 1 -1 -1 1 1 -1 1 -
1 -1 -1 1 1 1 1 1 -1 1 1 1 1 1 1 1 -1 1 1 -1 1 -1 -1 -1 -1 1 1 1 -1 1 -1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 -1 -1 -1 -1 -1 1 1 1
1 -1 1 -1 -1 1 -1 1 1 1 -1 -1 -1 1 -1 -1 1 -1 1 1 -1 -1 -1 1 -1 -1 -1 -1 -1 1 1 -1 1 -1 1 1 1 1 1 1 1 1 -1 -1 -1 1 -1 -1
1 1 1 1 -1 1 -1 -1 1 1 1 1 1 -1 -1 1 1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 1 1 1 1 1 -1 -1 -1 1 1 1 -1 1 1 -1 1 1 1 1 -1 1 1
-1 -1 -1 -1 1 -1 -1 -1 1 1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 -1 -1 1 -1 -1 -1 -1 1 -1 1 -1 -1 1 1 -1 1 1 -1 -1 1 1 -1 1 -1 1 -1
-1 1 1 -1 1 -1 -1 1 1 1 -1 -1 -1 1 1 1 -1 -1 -1 1 -1 -1 -1 -1 1 -1 1 1 1 -1 1 -1 -1 -1 -1 1 1 -1 1 1 1 -1 1 1 -1 1 -1 1 1
-1 -1 1 1 1 1 1 -1 1 1 -1 -1 -1 1 -1 1 -1 -1 1 1 -1 1 1 -1 -1 1 -1 -1 -1 -1 -1 1 -1 -1 1 1 1 1 -1 1 1 1 -1 1 -1 -1 -1 -1
1 -1 1 -1 1 -1 -1 1 1 1 1 1 -1 -1 -1 1 1 1 -1 1 -1 1 -1 1 -1 1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 1 1 1 -1 1 1 -1 -1 1 -1 -1 -1
1 1 -1 -1 1 -1 -1 1 1 -1 1 -1 -1 1 -1 -1 1 1 -1 -1 1 1 1 -1 -1 -1 -1 1 -1 1 -1 1 -1 -1 1 1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 -1
-1 -1 -1 -1 1 1 -1 1 -1 -1 -1 1 -1 -1 1 1 1 1 1 1 1 -1 1 1 -1 1 1 1 -1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 -1 1 1 1 -1 1 1 1 -1 -
1 1 1 -1 1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 -1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 -1 -1 -1 1 1 1 -1 -1 -1 1 -1 1 1 -1 -1 -1 1 1 -
1 1 -1 -1 1 -1 1 -1 -1 1 1 1 1 1 1 -1 -1 1 1 1 1 1 1 1 -1 1 1 1 1 1 -1 1 -1 1 -1 1 1 1 -1 1 -1 1 -1 -1 1 1 -1 1 1 -1 1 1
1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 -1 1 -1 -1 -1 -1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 -1 1 -1 -1 1 -1 -1 -1 1 -1 1 -1 1 1 1 1 -1 1
1 1 1 1 1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 -1 1 -1 1 -1 -1 -1 1 -1 -1 -1 1 -1 1 -1 1 -1 1 1 1 -1 1 -1 -1 -1 1 -1 -1 -1 -1
1 1 1 1 -1 1 -1 1 1 -1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 1 -1 -1 1 1 1 -1 1 1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 -1 -1 1
1 -1 1 -1 -1 -1 -1 1 -1 1 1 1 1 1 -1 1 -1 -1 -1 1 -1 -1 -1 1 -1
Sample Output 6
493
Q21)
Eveyone remember standing for queue in school assembly. One day few students were late in the
morning assembly, so they just went and stood at the end of the queue. But their Principal was strict and
made them stand in ascending order to their height. Given an array of N elements representing the
shortest person with 1 and tallest with N. He thought to arrange queue by following a trick,Trick was
simple: pick a student and send him/her at last or first and to arrange according to height. But he needs
your help to do so. Cost is increased by one if one student is sent at first or last.
Input Format
First line consists of T test cases. First line of test case consists of N. Second line of every test case consists
of N elements.
Constraints
1<=T<=100 1<=N<=10^5
Output Format
Sample Input 0
213
4312
Sample Output 0
Sample Input 1
43428341
Sample Output 1
5
Sample Input 2
4342731
Sample Output 2
Sample Input 3
10
8383838312
Sample Output 3
Q22)
Given n non-negative integers in array representing an elevation map where the width of each bar is 1,
compute how much water it is able to trap after raining. For example: Input: 3 2 0 2 Output: 2 Structure is
like below | | |_| We can trap 2 units of water in the middle gap.
Another example
Input Format
The first line of input contains an integer T denoting the number of test cases. The description of T test
cases follows. Each test case contains an integer N followed by N numbers to be stored in array.
Constraints
Output Format
Sample Input 0
7409
3
699
Sample Output 0
10
Sample Input 1
300204
Sample Output 1
10
Sample Input 2
202
12
010210132121
Sample Output 2
Q23)
Given a string, recursively remove adjacent duplicate characters from string. The output string should not
have any adjacent duplicates
Input Format
The first line contains an integer 'T' denoting the total number of test cases. In each test cases, a string
will be inserted.
Constraints
1<=T<=31 1<=length(string)<=100
Output Format
In each seperate line the modified string should be output. if output string is empty print "Empty"
Sample Input 0
raghuuhga
Sample Output 0
Sample Input 1
engineering
Sample Output 1
enginring
Sample Input 2
caaabbbaacdddd
Sample Output 2
Empty
Sample Input 3
geeksforgeeg
acaaabbbacdddd
azxxzy
Sample Output 3
gksfor
acac
ay
Q24)
All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG".
When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA
molecule. For example,
Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
Input Format
Constraints
--
Output Format
Sample Input 0
AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT
Sample Output 0
[AAAAACCCCC, CCCCCAAAAA]
Sample Input 1
AAAAACCCCCAAAAACCCCCCAAAAAGGGTTTCCCAAAAACCCCCCAAAAAG
Sample Output 1
Sample Input 2
AAAAACCCCCAAAAGGGTTTCCCAAAAACCCCCCAAAAAG
Sample Output 2
[AAAAACCCCC]
Sample Input 3
AAAAACCCCCAAAAGGGTTTCCCAAACCAAAAAG
Sample Output 3
[]
Sample Input 4
AAAAACCCCCAAAAACCCCCCAAAAAGGGTTTAAAAACCCCCAAAAACCCCCCAAAAAGGGTTT
Sample Output 4
Q25)
You are in a party of N people, where only one person is known to everyone. Such a person may be
present in the party, if yes, (s)he doesn’t know anyone in the party. Your task is to find the stranger
(celebrity) in party. You will be given a square matrix M where if an element of row i and column j is set to
1 it means there is an edge from ith person to jth person. An edge represent the relation that i th person
knows j th person. You need to complete the function getId which finds the id of the celebrity if present
else return -1. The function getId takes two arguments the square matrix M and its size n.
Output 1
Explanation For the above test case the matrix will look like 0 1 0 0 0 0 0 1 0 Here the celebrity is the
person with index 1 ie id 1
Input Format
Input: The first line of input contains an element T denoting the No of test cases. Then T test cases follow.
Each test case consist of 2 lines. The first line of each test case contains a number denoting the size of the
matrix M. Then in the next line are space separated values of the matrix M.
Constraints
Output Format
Output: For each test case output will be the id of the celebrity if present (0 based index). Else -1 will be
printed.
Sample Input 0
010
000
010
Sample Output 0
Sample Input 1
1001
0101
0000
1111
Sample Output 1
-1
Sample Input 2
1011
0111
0000
1111
Sample Output 2
Sample Input 3
1111
1111
0000
0000
Sample Output 3
-1
Sample Input 4
1111
1111
0000
0010
Sample Output 4
Sample Input 5
0000
1111
1111
1111
Sample Output 5
Sample Input 6
000
101
010
Sample Output 6
-1
Sample Input 7
00000
10101
00000
11111
11111
Sample Output 7
-1
Sample Input 8
1010
0011
1000
1111
Sample Output 8
-1
Input Format
The first line of input contains N - the size of the array and the second line contains the elements of the
array.
Output Format
Constraints
Example Input
-2 -19 8 15 4
Output
15
2 Number Distribution
Print the count of the occurrences of positive integers, negative integers, and zeroes in the given array.
Input Format
The first line of the input contains an integer N - size of the array, second line of input contains an array
elements of the array.
Output Format
Constraints
10
Output
145
3 Reverse Array
Note:
Try solving this using recursion. Do not use any inbuilt functions / libraries for your main logic.
Input Format
The first line of input contains N - the size of the array and the second line contains the elements of the
array.
Output Format
Constraints
Example Input
2 19 8 15 4
Output
4 15 8 19 2
Given an array of size N. Print the sum of odd and even numbers separated by a space.
Input Format
The first line of input contains N - the size of the array and the second line contains elements of the array.
Output Format
Constraints
Example Input
46925
Output
14 12
Given a sorted array A, containing N integers. Calculate and print their Mean, Median and Mode.
1. For both the Mean and Median, display the values with precision up to two decimal places.
2. Print the first Mode that you encounter from the left hand side.
Input Format
First line of input contains integer N - the size of the array. Second line of input contains N integers -
elements of the array A.
Output Format
Constraints
1 <= N <=104
Example Input
12345566
Output
4.00 4.50 5
Find the missing number in the given list of integers. The list contains 1 to 100 integers but one of the
integer is missing. There are no duplicates in the list.
Input Format
Output Format
Constraints
12 15 9 1 71 77 81 29 70 19 11 83 56 2 57 53 68 99 82 100 22 10 51 40 34 98 80
38 39 89 94 4 26 64 45 8 90 24 93 33 21 7 49 88 5 28 55 67 65 50 32 58 6 37 46
42 20 44 41 3 78 76 73 16 31 85 91 54 60 47 97 43 84 17 35 69 13 30 61 79 72
48 23 66 52 27 62 87 63 18 75 96 14 86 95 74 25 59 36
Output
92
Find a duplicate element in the given array of integers. There will be only a single
Note:
Do not use any inbuilt functions / libraries for your main logic
Input Format
The first line of input contains the size of the array - N and the second line
contains the elements of the array, there will be only a single duplicate element in
the array.
Output Format
Constraints
Example
Input
5 4 10 9 21 10
Output
10
8 First and Last
You are given an array A of size N, containing integers. Your task is to find the first and last occurrences of
a given element X in the array A and print them.
Input Format
The input consists of three lines. The first line contains a single integer N - the size of the array. The
second line contains N integers separated by a space, representing the elements of the array A. The third
line contains a single integer X.
Output Format
Print the indexes of the first and last occurrences separated by a space.
Constraints
X∈A
Example
Input
10
1 3 5 7 9 11 3 13 15 3
Output
19
9 Unique Elements
Print unique elements of the array in the same order as they appear in the input.
Note:
Do not use any inbuilt functions / libraries for your main logic.
Input Format
The first line of input contains the size of the array - N and the second line
contains the elements of the array.
Output Format
Constraints
Example
Input
5 4 10 9 21 4 10
Output
5 9 21
You are given two sorted integer arrays A and B of size N and M respectively. Print the entire data in
sorted order.
Input Format
First line of input contains N - the size of the array. The second line contains N
integers - the elements of the first array. The third line contains M - the size of the
second array. The fourth line contains M integers - the elements of the second
array.
Output Format
For each test case, print the entire data in sorted order with each element
Constraints
Input
1 1 5 8 10 12 15
-1 2 4 5 7
Output
-1 1 1 2 4 5 5 7 8 10 12 15
Given two arrays, A and B, for each index 'i' in array B, print the corresponding
element from array A if B[i] is within the range of A, otherwise print -1.
Input Format
The first line of input contains an integer N - size of array A. The Second line of
input contains elements of array A. The Third line of input contains an integer M
Output Format
Print the values of array A for every index 'i' in B i.e. A[B[i]] if B[i] is in the
Constraints
Example
Input
4 2 0 6 10 0
Output
Explanation
B[3] is 6, size of array A is 5, any index >= 5 is an invalid index, so print -1. B[4] is 10, size of array A is 5,
any index >= 5 is an invalid index, so print -1. B[5] is 0, A[B[5]] => A[0] = 100
12 Gauntlets
gauntlets of the same color. Determine the maximum number of pairs that can be
formed.
Input Format
The first line of input contains an integer N. The second line of input contains an
array of size N.
Output Format
For the given input, print a single line representing the answer.
Constraints
1 ≤ N ≤ 102
1 ≤ Ai ≤ 103
Example
Input
417414
Output
2
Explanation
Choose two gauntlets with the color 1 and pair them. Choose two gauntlets with the color 4 and
pair them.
Then, you will be left with one sock with the color 4 and another with the color 7, so you can no longer do
the operation. There is no way to do the operation three or more times, so you should print 2.
13 Max Altitude
Imagine a pilot starting the flight from the ground and flying over a series of different points at different
heights. You are given an array, where A[i] represents heights.
Currently, if the pilot is at altitude X at ith point, and if he wants to reach (i+1)th point, his altitude will
become X+A[i].
The pilot starts at altitude 0 and wants to find the highest point he can reach during the entire journey.
Your task is to print the highest altitude the pilot reaches.
Input Format
The first line of input contains an integer N. The second line of input contains N space-separated integers.
Output Format
Constraints
Example Input
-5 1 5 0 -7
Output
Given an array of elements containing 0's and 1's. You have to find the length of longest contiguous 1's.
Input Format
First line of input contains N - size of the array. The next line contains the N integers of array A.
Output Format
Constraints
Example Input
10
1001011110
Output
15 Is Bitonic Sequence
valid array if and only if there exists some i with 0 < i < A.length - 1 such that:
A[0] < A[1] < ... < A[i - 1] < A[i] > A[i + 1] > ... > A[A.length - 1].
Input Format
The first line of the input contains N. Second line of input contains an array of
size N.
Output Format
Print true if and only if it is a valid array, otherwise print false.
Constraints
3 ≤ N ≤ 104
0 ≤ Ai ≤ 104
Example
Input
0321
Output
true
Explanation
ar = [0, 3, 2, 1]
idx = 0 1 2 3
So if we take i=1, then we have ar[0] < ar[1] > ar[2] > ar[3]
0<3>2>1
Given an array D of positive integers, your goal is to divide D into two separate arrays, E and F, under the
following conditions:
Each element in array D must belong to either array E or array F Both arrays E and F are non-empty
The objective is to minimize the partition's value, calculated as the absolute difference between
the maximum value of array E (denoted as max(E)) and the minimum value of array F (denoted as min(F))
Print the resulting integer that represents the value of this partition.
Input Format
The first line of input contains N. The second line of input contains an array of size N.
Output Format
2 ≤ N ≤ 104
1 ≤ Di ≤ 109
Example Input
7 1 14 16 30 4
Output
Explanation
We can partition the array D into E = [7, 1, 14, 4] and F = [16, 30].
The maximum element of the array E is equal to 14. The minimum element of the array F is equal to 16.
The value of the partition is |14 - 16| = 2. It can be proven that 2 is the minimum value out of all the
partitions.
Given an array A of size N. Construct an array B, such that B[i] is calculated as follows:
Find leftSum => sum of elements to the left of index i in array A; if none,
use 0.
Find rightSum => sum of elements to the right of index i in array A; if none, use 0.
Input Format
The first line of input contains the N - size of the array. The next line contains N integers - the elements of
array A.
Output Format
Example Input
677
Output
14 1 13
Explanation At index 0:
LeftSum = 0, RightSum = 14
At index 1:
LeftSum = 6, RightSum = 7
At index 2:
18 Alternate Seating
You are given an integer N, denoting the number of people who need to be seated, and a list of M seats,
where 0 represents a vacant seat and 1 represents an already occupied seat. Find whether all N people
can find a seat, provided that no two people can sit next to each other.
Input Format
The first line of the input contains N denoting the number of people. The second line of input contains M
denoting the number of seats. The third line of input contains the seats.
Output Format
Constraints
1 ≤ N ≤ 105
1 ≤ M ≤ 105
Ai ∈ {0, 1}
Example
Input
0010001
Output
YES
Explanation
19 Ternary Array
Given an array A of size N, find the minimum cost to convert it to a ternary array
B. A ternary array can only have 0 or 1 or 2. After conversion, ensure that A[i] !=
Input Format
The first line of input contains a single integer N - the size of the array and the
Output Format
Constraints
1 <= N <= 10000
Example
Input
1 -1 2 0 5
Output
Explanation
Given an array of integers A, print true if we can partition the array into three non-empty subarrays with
equal sums.
Input Format
The first line of the input contains an integer N. Second line of input contains an array of size N.
Output Format
Constraints
3 ≤ N ≤ 104
-104 ≤ Ai ≤ 104
Example Input
10
3 3 6 5 -2 2 5 1 -9 4
Output
true
Explanation
(3 + 3) = (6) = (5 - 2 + 2 + 5 + 1 - 9 + 4) = 6.
21 List Operations
You are tasked with implementing a program that manipulates an empty list based on a series of
commands.
Input Format
The first line of input contains an integer N, indicating the number of commands to follow. The next N
lines contains any of the following commands:
count X: Count the number of occurrences of the integer X in the list. reverse: Reverses the order of
elements in the list.
insert Pos X: Inserts the integer X at the position Pos in the list. sort: Sorts the elements of the list in
ascending order.
index X: Gives the index of the first occurrence of the integer X in the list, or -1 if X is not found.
Output Format
For count, index, and length command, print the result. For the remaining commands, print the updated
list separated by spaces.
Constraints
1 <= N <= 50
10
append 13
append 7
Output
13
13 7
13 6 7
13 6 7 13 6 7
-1
7 6 13 7 6 13
6 6 7 7 13 13
Input Format
The first line of input contains an integer N - the size of an array. The second line contains the elements of
the array.
Output Format
Constraints
1 <= N <= 20
Example Input
5 8 10 15 3 6
Output
5 8 10 3 6 15
5 8 3 6 10 15
5 3 6 8 10 15
3 5 6 8 10 15
3 5 6 8 10 15
Input Format
The first line of input contains an integer N - the size of an array. The second line contains the elements of
the array.
Output Format
Constraints
1 <= N <= 20
5 8 10 15 3 6
Output
3 8 10 15 5 6
3 5 10 15 8 6
3 5 6 15 8 10
3 5 6 8 15 10
3 5 6 8 10 15
Input Format
The first line of input contains an integer N - the size of an array. The second line contains the elements of
the array.
Output Format
Constraints
1 <= N <= 20
Example
Input
87124
Output
78124
17824
12784
12478
Input Format
The first line of input contains an integer N - the size of an array. The second line
Output Format
Constraints
1 <= N <= 20
Example
Input
4 3 12 1 13 9 5 6
Output
4 3 5 1 13 9 12 6
4 1 5 3 12 6 13 9
1 3 4 5 6 9 12 13
Explanation
Initially gap = 4, apply Insertion Sort for elements at distance 4, you will get [4 3
5 1 13 9 12 6]
For gap = 2, again apply Insertion Sort for elements at distance 2, you will get [4 1 5 3 12 6 13 9]
For gap = 1, apply Insertion Sort for elements at distance 1, you will get [1 3 4 5
6 9 12 13]
Input Format
The first line of input contains an integer N - the size of an array. The second line contains the elements of
the array.
Output Format
For each merge call of Merge Sort, print the array elements.
Constraints
1 <= N <= 20
Example Input
5 1 3 15 10 4
Output
1 5 3 15 10 4
1 3 5 15 10 4
1 3 5 10 15 4
1 3 5 4 10 15
1 3 4 5 10 15
Given an array of integers, search a given key in the array using linear search. Note: Do not use any inbuilt
functions / libraries for your main logic.
Input Format
The first line of input contains two integers N and K. N is the size of the array and K is the key. The second
line contains the elements of the array.
Output Format
If the key is found, print the index of the array, otherwise print -1.
Constraints
Example Input
5 15
-2 -19 8 15 4
Output
Input Format
The first line of input contains an integer N - the size of an array and target K.
Output Format
For each iteration of Binary Search, print the values of low, high, and mid. At the
end, if the target K is found in the array, print "True" otherwise, print "False".
Constraints
1 <= N <= 20
1 <= A[i] <= 103
Example
Input 1
9 12
1 4 6 7 10 11 12 20 23
Output 1
084
586
True
Input 2
10 21
3 5 8 11 15 17 19 23 26 30
Output 2
094
597
565
666
False
Note:
Input Format
The first line of input contains N, M - the size of the matrix, followed by N lines each containing M integers
- elements of the matrix.
Output Format
Constraints
Example Input
23
5 -1 3
19 8 -5
Output
22
Input Format
The first line of input contains N, M - the size of the matrix, followed by N lines each containing M integers
- elements of the matrix.
Output Format
Constraints
1 <= N, M <= 100
Example Input
22
5 -1
19 8
Output
24
31 Submatrix Sum
Given a matrix of size N x N and four integers (i, j, k, l), calculate the sum of the sub-matrix from (i, j) to (k,
l).
Input Format
The first line of input contains an integer N. Second line of input contains four integers i, j, k and l. It's
followed by N lines each containing N integers - elements of the matrix.
Output Format
Constraints
1122
123
456
789
Output
28
Explanation
32 Lower Triangle
Given a square matrix of size N × N, find the sum of its lower triangle elements.
Input Format
The first line of input contains N - the size of the matrix. It is followed by N lines each containing N
integers - elements of the matrix.
Output Format
Constraints
Example
Input
5 9 -2
-3 4 1
261
Output
15
Explanation
Given two matrices A and B each of size N x M, print the sum of the matrices (A
+ B).
Note:
Input Format
The first line of input contains N, M - the size of the matrices. It's followed by
2*N lines, each containing M integers - elements of the matrices. The first N lines
are for matrix A and the next N lines are for matrix B.
Output Format
Constraints
Example
Input
23
5 -1 3
19 8 4
4 5 -6
1 -2 12
Output
9 4 -3
20 6 16
34 Interchange Diagonals
Given a matrix A of size NxN, interchange the diagonal elements from top to bottom and print the
resultant matrix.
Input Format
First line of input contains N - the size of the matrix. It is followed by N lines each containing N integers -
elements of the matrix.
Output Format
Constraints
Example Input
5678
13 14 15 16
1234
9 10 11 12
Output
8675
13 15 14 16
1324
12 10 11 9
You are given a matrix and an array. For each row of the given matrix, for each element of that row, check
if it is present in the given array. Print the count of elements present for every row.
Input Format
The first line of input contains N, M - the size of the matrix. It is followed by N lines each containing M
integers - elements of the matrix. The next line of the input contains the A - the size of the array. The next
line of the input contains the
array elements.
Output Format
For each row, print the count of the number of elements present, separated by a new line.
Constraints
Example Input
34
5 9 -2 2
-3 4 1 9
2 -2 1 -2
5 1 -2 2 6
Output
3
Explanation
The first row of the matrix is (5 9 -2 2), out of this, 3 elements (5 -2 2), except 9,
The second row of the matrix is (-3 4 1 9), out of this, only 1 is present in the given array (5 1 -2 2 6)
The third row of the matrix is (2 -2 1 -2), all the 4 elements are present in the given array (5 1 -2 2 6)
Given a matrix of size N x M, print the matrix in zig-zag order. Refer example for more details.
Input Format
The first line of input contains N, M - the size of the matrix. It is followed by N lines each containing M
integers - elements of the matrix.
Output Format
Constraints
Example Input
33
5 9 -2
-3 4 1
261
Output
5 9 -2 1 4 -3 2 6 1
37 Transpose Matrix
Input Format
The first line of input contains N, M - the size of the matrix. It is followed by N lines each containing M
integers - elements of the matrix.
Output Format
Constraints
Example Input
22
5 -1
19 8
Output
5 19
-1 8
38 Sparse Matrix
Given a matrix of size N x M, print whether it is a sparse matrix or not. Please note that if a matrix
contains 0 in more than half of its cells, then it is called a sparse matrix.
Input Format
The first line of input contains N, M - the size of the matrix, followed by N lines each containing M integers
- elements of the matrix.
Output Format
Print "Yes" if the given matrix is a sparse matrix, otherwise print "No".
Constraints
Example
Input
23
500
080
Output
Yes
39 Super One
Given a matrix of 0’s and 1’s, check if there exists a Super One. Please note that
Input Format
The first line of input contains N, M - the size of the matrix. It's followed by N
Output Format
Print "Yes" if the matrix contains Super One, otherwise print "No".
Constraints
Example
Input
44
1000
0001
0100
0000
Output
Yes
Explanation
There's one occurrence of Super One in the matrix at [2,1]. Value 1 at index [0,0]
and Value 1 at index [1,3] are not Super One's because they are not surrounded
by eight 0's.
40 Image Flip
You are given an N x M binary matrix called "image". You need to perform the following operations on the
matrix (in order) and return the resulting image:
Flip the image horizontally: This involves reversing the order of elements in each row of the matrix. For
example, [1,0,1,0,0,0] becomes [0,0,0,1,0,1]
Invert the image: This involves replacing 0s with 1s and 1s with 0s in the entire matrix. For example,
[0,0,0,1,0,1] becomes [1,1,1,0,1,0]
Input Format
Line of input contains N - number of rows and M - number of columns. The next N lines contains M
integers each denoting the elements of the matrix image.
Output Format
1 <= N <=100
1 <= M <=100
Example Input
22
10
01
Output
10
01
Given an integer matrix C with dimensions N × N. Construct a new integer matrix D of size (N - 2) × (N - 2)
such that each element D[i][j] represents the maximum value within a 3 × 3 submatrix of C, where the
center of the submatrix is located at row i + 1 and column j + 1 in matrix C. We aim to identify the highest
value within every continuous 3 × 3 submatrix within C. Print the resulting matrix D.
Input Format
The first line of input contains an integer N. For the next N lines, each line contains N elements separated
by space.
Output Format
Constraints
3 ≤ N ≤ 100
Example
Input
12 9 8 40
5 20 2 6
8 14 6 30
6 2 25 2
Output
20 40
25 30
A[i][j] = 0, set all the elements in the ith row and jth column to 0. Print the
resultant matrix.
Input Format
The first line of input contains N, M - the size of the matrix A. It is followed by N
Output Format
Constraints
A[i][j] ∈ {0,1}
Example
Input
45
01101
11111
11011
11111
Output
00000
01001
00000
01001
43 Check Bit
Input Format
Output Format
Print "true" if the ith bit is set in the given integer N, "false" otherwise.
Constraints
0 <= i <= 30
Example Input
10 1
Output
true
Explanation
The binary form of 10 is `1010`. So, the 1st bit in 10 is set. Note that the LSB bit is referred to as the 0th
bit.
44 Triangle Validator
Given the length of 3 sides of a triangle, check whether the triangle is valid or not.
Input Format
The first and only line of input contains three integers A, B, C - Sides of the triangle.
Output Format
Print "Yes" if you can construct a triangle with the given three sides, "No" otherwise.
Constraints
Example Input
435
Output
Yes
45 Area of Rectangle
Print the area of the rectangle, given its length and breadth.
Input Format
The first and only line of input contains two positive integers L - Length of the rectangle and B - Breadth of
the rectangle.
Output Format
1 <= L, B <=109
Example Input
58
Output
40
46 Arithmetic Operators
Given two integers A and B. Print the sum, difference, product, division, and remainder for the
corresponding values of A and B.
Input Format
Output Format
Print the sum, difference, product, division, and remainder for the corresponding values of A and B. Refer
the given example.
Constraints
Example Input
12 5
Output
Sum: 17
Difference: 7
Product: 60
Division: 2
Remainder: 2
47 Arithmetic Progression
For an Arithmetic Progression series with a given first term (a), common difference (d), and an integer N,
determine the Nth term of the series.
Input Format
Output Format
Constraints
Example Input
215
Output
48 Compute A power B
Note: Do not use any inbuilt functions / libraries for your main logic.
Input Format
The first and only line of input contains two positive integers A and B.
Output Format
Print A power B.
Constraints
0 <= B <= 9
Example Input
23
Output
49 Number Reverse
Input Format
Output Format
Constraints
4431
50 Fibonacci Number
Input Format
Output Format
Constraints
0 <= N <= 20
Example Input
Output
Explanation
0, 1, 1, 2, 3, 5, 8,......
Input Format
The first and only line of input contains a number - N.
Output Format
Print factorial of N.
Constraints
0 <= N <= 10
Example Input
Output
120
52 Catalan Number
Input Format
Output Format
Constraints
0 <= N <= 10
Example Input
3
Output
Explanation
53 NcR Basic
Input Format
Output Format
Constraints
1 <= N <= 10
1 <= R <= 10
Example Input
53
Output
10
54 Applying Modulus
Note:
1. (X × Y) % M = (X % M × Y % M) % M
2. (X - Y) % M = (X % M - Y % M + M) % M
Input Format
The first and only line of input contains six space-separated integers A, B, C, D, E, and F.
Output Format
For the given input, print a single line representing the answer.
Constraints
0 ≤ A, B, C, D, E, F ≤ 1018 A × B × C ≥ D × E × F
Example Input
235124
Output
22
Explanation
55 Factorial Hard
Input Format
Output Format
Print factorial of N. Since the result can be very large, print result % 1000000007
Constraints
0 <= N <= 106
Examples
Input 1
Output 1
Input 2
165
Output 2
994387759
56 Minimum Subtraction
Input Format
Output Format
Constraints
Example
Input
10
Output
Explanation
N = 10
Given a positive integer - N. Print the number of multiples of 3, 5 between [1, N].
Input Format
Output Format
Constraints
Example Input
12
Output
Explanation
58 A B and X
You are given two numbers A and B along with an integer X. In one operation you can do one of the
following:
Set A = A + X and B = B - X
Set A = A - X and B = B + X
Determine if you can make A and B equal after applying the operation any number of times (possibly
zero).
Input Format
The first and only line of input contains three integers A, B, and X separated by a space.
Output Format
For each test case, print YES if you can make A and B equal, otherwise NO.
Constraints
Examples Input 1
681
Output 1
YES
Input 2
15 16 2
Output 2
NO
Explanation
Example 1: The initial values of (A, B) are (6,8). We can perform the following operation.
A = A + X = 6 + 1 = 7 and B = B - X = 8 - 1 = 7
Example 2: It can be proven that we cannot make A equal to B using the given operations.
Input Format
Output Format
Constraints
Example Input
Output
10
60 Armstrong Number
Note that an Armstrong number is a number that is equal to the sum of cubes of its digits.
Input Format
Output Format
Constraints
0 <= N <= 109
Output
Yes
Explanation
13 + 53 + 33 = 153
61 Narcissistic Numbers
Note that a Narcissistic number is a number that is the sum of its own digits each raised to the power of
the number of digits
Input Format
Output Format
Constraints
Output
Yes
Explanation
84 + 24 + 04 + 84 = 8208
62 Harshad Numbers
Note that a Harshad number is an integer, that is divisible by the sum of its digits.
Input
Output
Constraints
Example Input
18
Output
Yes
Explanation
18 / (1 + 8) = 2
63 Compound Interest
interest.
Compound interest is the interest calculated on the initial principal and also on
the accumulated interest of previous periods. Given the principal amount (P), the
annual interest rate (R), the number of times the interest is compounded per year
(N), and the time in years (T), write a program to calculate the final amount (A)
Always consider the floor value of (R/N) while computing Compound Interest.
Input Format
The first and only line of input contains 4 integers P, R, N, T separated by spaces.
Output Format
Constraints
1 <= R <= 10
1 <= N, T <= 5
Example
Input
65 6 1 2
Output
3120
64 Quadratic Equation
Given a quadratic equation in the form ax2 + bx + c, (only the values of a, b and c
Note: Display the values with precision up to two decimal places, and for
Input Format
First and only line of input contains three integers a, b, c separated by spaces.
Output Format
Constraints
Examples
Input 1
1 -2 1
Output 1
1.00 1.00
Input 2
1 7 12
Output 2
-3.00 -4.00
Input 3
111
Output 3
Imaginary Roots
Explanation
Example 3: Roots are imaginary, which are (-0.5 + i0.866025, -0.5 - i0.866025)
restart_alt
settings
save
Score: 0 / 20
00
Minutes
65 Prime or Not
Input Format
Constraints
Example Input
11
Output
Yes
66 Arrange Primes
Given an integer N. Print the count of permutations for the numbers from 1 to N, considering that prime
numbers should be placed at positions with prime indices (1 - based indexing). As the result might be a
large number, print the output % 1e9 + 7.
Input Format
Output Format
Constraints
1 ≤ N ≤ 100
Example Input
8
Output
576
67 Fuel Tank
A truck has two fuel tanks: a main tank and an additional tank. The fuel levels in both tanks are
represented by two integers: mainTank, which represents the fuel in the main tank in litres, and
additionalTank, which represents the fuel in the additional tank in litres.
The truck has a mileage of 10 kilometers per litre. Whenever 5 litres of fuel are consumed from the main
tank, if the additional tank has at least 1 litre of fuel, 1 litre of fuel will be transferred from the additional
tank to the main tank. Print the maximum distance that can be travelled with the given fuel.
Input Format
The first and only line of input contains two integers mainTank and additionalTank.
Output Format
Print the maximum distance that can be travelled with the given fuel.
Constraints
Examples Input 1
5 10
Output 1
60
Input 2
2 2
Output 2
20
Explanation
Example 1:
After spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and the distance travelled is 50km. After
spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.
Total distance travelled is 60km.
Example 2:
After spending 2 litre of fuel, the main tank becomes empty. Total distance travelled is 20km.
68 Min Digit
Tom and Jerry are playing a game with an integer N that doesn't contain any zeros in its decimal
representation. Tom starts first and, on his turn, he can swap any two digits of the integer that are in
different positions. Jerry follows by always removing the last digit of the integer. The game continues in
turns until there's only one digit left. Determine the smallest integer Tom can achieve at the end if he
plays optimally.
Input Format
The first and only line of input consists an integer N consisting of digits 1 - 9.
Output Format
Constraints
Output
1
Explanation
Tom can swap 3 and 1, N becomes 312. After that Jerry deletes the last digit, N becomes 31. Then Tom
swaps 3 and 1, N becomes 13 and Jerry deletes 3, so the answer is 1.
69 Number of Rectangles
Vikram has a collection of N squares with a side length of 1. Print the number of different rectangles that
can be formed using these squares.
Input Format
Print the number of different rectangles that can be formed using these squares.
Output Format
Print the number of different rectangles that can be formed using these squares.
Constraints
1 ≤ N ≤ 100
Example Input
Output
Explanation
We can create different rectangles of sizes 1×1, 1×2, 1×3, 1×4, 1×5, 1×6, 2×2,
2×3.
70 Point Location
There is a line that goes through the points P1 = (x1,y1) and P2 = (x2,y2). There is
also a point P3 = (x3,y3). Print whether P3 is located on the left or right side of the
Input Format
The first and only line of input contains 6 integers x1, y1, x2, y2, x3, y3 separated
by spaces.
Output Format
Constraints
x1 ≠ x2 or y1 ≠ y2
Examples
Input 1
115323
Output 1
LEFT
Input 2
115341
Output 2
RIGHT
Input 3
115332
Output 3
TOUCH
71 Area of Polygon
Print the area of a given polygon. The polygon consists of N vertices (x1, y1), (x2,
y2), …, (xN, yN). The vertices (xi, yi) and (xi+1, yi+1) are adjacent for i = 1, 2, …, N−1, and the
vertices (x1, y1) and (xN, yN) are also adjacent.
Input Format
The first line of input has an integer N: the number of vertices. Next N lines describe the vertices. The ith
such line has two integers xi and yi separated by space. You may assume that the polygon is simple, i.e., it
does not intersect itself.
Output Format
Constraints
3 ≤ N ≤ 1000
Example Input
11
42
35
14
Output
16
72 Filled Rectangle
Input Format
Output Format
Constraints
1 <= N <= 10
1 <= M <= 10
Example
Input
35
Output
*****
*****
*****
73 Hollow Rectangle
Print a hollow rectangle pattern using '*'. See the example for more details.
Input Format
The input contains two integers W - width of the rectangle and L - length of the rectangle.
Output Format
For the given integers W and L, print the hollow rectangle pattern.
Constraints
2 <= W <= 50
2 <= L <= 50
Example Input
54
Output
*****
* *
* *
*****
74 Rectangle Pattern
Print rectangle pattern. See the example for more details.
Input Format
Output Format
For the given integer, print a rectangle pattern as shown in the example.
Constraints
1 <= N <= 50
Example Input
Output
5432*
543*1
54*21
5*321
*4321
75 Triangle Pattern
Given a value N, print a right-angled triangle pattern. See examples for more details.
Input Format
Output Format
Print the right angled triangle pattern.
Constraints
Example Input
Output
**
***
****
*****
76 Floyd Pattern - 1
Print a right-angled triangle pattern using integers. See the example for more details.
Input Format
The first and only line of input contains a single integer N - the size of the triangle.
Output Format
Constraints
1 <= N <= 50
Example Input
6
Output
23
456
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
77 Floyd Pattern - 2
Print a right-angled triangle pattern. See the example for more details.
Input Format
The first and only line of input contains a single integer N - the size of the triangle.
Output Format
Constraints
1 <= N <= 50
Example Input
Output
26
3 7 10
4 8 11 13
5 9 12 14 15
78 Half Diamond
Print half diamond pattern using '*'. See the example for more details.
Input Format
Output Format
Constraints
1 <= N <= 50
Example Input
Output
**
***
****
*****
****
***
**
Given a value N, print a half diamond pattern with numbers. See examples for more details.
Input Format
Output Format
Constraints
Example Input
Output
12
123
1234
12345
1234
123
12
80 Inverted Pyramid
Print a hollow half-inverted pyramid pattern using '*'. See the example for more details.
Input Format
Constraints
1 <= N <= 50
Example Input
Output
*****
* *
* *
**
81 Pyramid Pattern
Print pyramid pattern using '*'. See the example for more details.
Input Format
The first and only line of input contains a single integer N - the size of the pyramid.
Output Format
Constraints
1 <= N <= 50
Example Input
Output
***
*****
*******
*********
82 Palindromic Pattern
Print a palindromic right-angled triangle pattern using characters. See the example for more details.
Input Format
The first and only line of input contains an integer N - the size of the pattern.
Output Format
For the given integer N, print the palindromic right-angled triangle pattern.
Constraints
1 <= N <= 26
Example Input
Output
ABA
ABCBA
ABCDCBA
ABCDEDCBA
83 Multiplication Table
Input Format
Output Format
Constraints
Example Input
Output
9*1=9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
84 Pascal's Triangle
Input Format
Output Format
Constraints
1 ≤ N ≤ 30
Example Input
10
Output
11
121
1331
14641
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
85 Reverse String
Given a string, reverse the given string in place and then print it.
Note:
Do not use any inbuilt functions / libraries for your main logic.
Input Format
Output Format
Constraints
Output
Trams
Given a string, print all the letters present at the odd index, followed by the letters present at the even
index.
Input Format
Output Format
Print letters present at odd index, followed by the letters present at even index.
Constraints
Output
fgtad5g
87 Toggle Case
Given a string, toggle the case of each character in the given string.
Input Format
The first and only input line contains a string S, consisting of lowercase and uppercase characters.
Output Format
Constraints
Output
hEllO
Given a string, print the count of vowels and consonants in the string.
Input Format
Output Format
Print the count of vowels and consonants in the given string, separated by space.
Constraints
Output
47
89 Letter Coverage
Input Format
Output Format
Print "Yes" if the string contains all the letters of the alphabet, and "No" otherwise.
Constraints
Example Input
askhtwsflkqwertYuioPasdfghjklZxcvbnm
Output
Yes
Given a string, you have to check whether it is a square string. A string is said to be square if it is some
string written twice in a row. For example, the strings "cc", "zazazaza", and "papa" are square. But "abc",
and "abaaaabb" are not square.
Input Format
Output Format
Constraints
Example Input
aabaabaabaab
Output
Yes
Explanation
The given string can be formed by adding the string "aabaab" 2 times.
91 Balanced Splitting
A balanced string is one that contains an equal quantity of 'L' and 'R' characters. Given a balanced string S,
your task is to split it into some number of substrings such that each substring is also balanced. Output
the maximum number of balanced strings you can obtain through this splitting process.
Input Format
The first and only line of input contains string S.
Output Format
Print the maximum number of balanced strings you can obtain with the splitting process.
Constraints
2 ≤ len(A) ≤ 1000
Example Input
LRRLLLLRRLRR
Output
Explanation
The string 'LRLLLRRLRR' can be split into three substrings: "LR", "RL" and "LLLRRLRR," each containing the
same number of 'L' and 'R' characters
92 Digit String
Input Format
Output Format
Print "Yes" if the string contains only digits, and "No" otherwise.
Constraints
1 <= len(S) <= 100
Output
Yes
93 Digits Sum
Given a non-negative integer - N, print the sum of digits of the given number.
Input Format
Output Format
Constraints
Output
11
Explanation
1 + 6 + 4 = 11
94 Number of Days
Given 2 unique dates, print the number of days between the 2 given dates.
Input Format
The first and only line of input contains 2 dates separated by space.
Output Format
Constraints
The given dates are valid dates between the years 1971 and 2100.
Example Input
2000-01-16 1999-12-30
Output
17
95 AB and CD
Given a string S of length N. You can apply the following operations any number of times:
1. In one operation you can remove any one occurrence of substring "AB"
from S.
2. In one operation you can remove any one occurrence of substring "CD"
from S.
Print the minimum possible length of the resulting string that you can obtain. Note: The string
concatenates after removing the substring and could produce new "AB" or "CD" substrings.
Input Format
Output Format
Example Input
CCAAABBBDE
Output
Explanation
1st operation: Remove AB from the string, and the string becomes 'CCAABBDE.'
2nd operation: Remove AB from the string, and the string becomes 'CCABDE.' 3rd operation: Remove AB
from the string, and the string becomes 'CCDE.'
4th operation: Remove CD from the string, and the string becomes 'CE.'
Furthermore, we cannot apply any more operations, and the minimum possible length is 2.
96 Strong Password
Find the minimum number of characters to add to a password (P) to ensure that P meets the following
criteria:
Input Format
Constraints
Output
Explanation
The given password P already contains one digit, one lowercase character, one uppercase character and
one special character. However, it should also contain at least 6 characters. So we need to add 1 character
to ensure it meets all the criteria.
97 Anagram Basic
Given two strings A and B consisting of lowercase characters, check if they are anagrams. An anagram is a
rearrangement of the letters of one word to form another word. In other words, some permutations of
string A must be the same as string B.
Input Format
The first line of input contains string A. The second line of input contains string B.
Output Format
Constraints
stop post
Output
TRUE
98 Compress String
Given a string, compress the given string. See the example for more details.
Input Format
Output Format
Constraints
Example Input
aaabbbbhhheaaAsssssss
Output
a3b4h3e1a2A1s7
Explanation
In the given string, a is repeating for 3 times - after compression a3. Similarly,
b is repeating for 4 times - b4 h is repeating for 3 times - h3 e is repeating for 1 time - e1 a is repeating for
2 times - a2 A is repeating for 1 time - A1 s is repeating 7 times - s7
99 Strings Rotation
Given two strings A and B of length N, check if string A is a rotation of string B.
Input Format
The first line of input contains N - the length of the strings. The second line contains A and B separated by
a space.
Output Format
Constraints
Example Input
hello lohel
Output
Yes
Given strings S and T. Print "Yes", if T is both a prefix and a suffix of S, otherwise "No".
Input Format
First and only line of input contains two strings separated by a space.
Output Format
1 <= len(S), len(T) <= 1000 'a' <= S[i], T[i] <= 'z'
Example Input
smartinterviewssmart smart
Output
Yes
Given a string, compute the length of the longest proper prefix which is same as the suffix of the given
string.
Input Format
Output Format
Print the length of the longest proper prefix which is the same as a suffix of the given string.
Constraints
Example Input
smartintsmart
Output
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--
.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
The full table for the 26 letters of the English alphabet is given above. For
example, "abc" can be written as ".--...-.-.", which is the concatenation of ".-", "-
...", and "-.-.". We will call such a concatenation the transformation of a word.
Input Format
First line of input contains the size of the array N. The second line of input
Output Format
Constraints
1 ≤ A.length ≤ 100
1 ≤ A[i].length ≤ 12
Example
Input
Output
Explanation
Observing your friend as they type their name on the keyboard, you notice that occasionally a key might
be held down longer, causing a character to appear multiple times. After examining the sequence of
typed characters, determine whether it's possible that the typed sequence corresponds to your friend's
name.
Input Format
The first and only line of input contains two strings separated by space.
Output Format
Constraints
Example Input
raju rrraaajjjjjjjjjjjjjjuuuu
Output
True
Given two strings, P and Q, your task is to find the largest common divisor string S, such that both P and Q
are divisible by S. In other words, there exists a string 'S' for which P = S + S + ... + S and Q = S + S + ... + S. If
such a string S exists, output the largest possible S, otherwise, print -1.
Note: A string X is divisible by string Y if and only if X can be obtained by concatenating Y with itself one or
more times.
Input Format
The first line of input contains the string P. The Second line of input contains string Q.
Output Format
Constraints
Output
AB
multiplication, division, and modulo operators. Evaluate the expression and print the result.
Note:
Assume that it is a regular Calculator, where the expression will be simply evaluated from left to right,
without following BODMAS Rule.
Assume that the modulo operator (say % M) will give a positive integer value in the range [0, M-1]
Examples:
3 - 8 / 2 = -5 / 2 = -2
3 + 8 / 2 = 11 / 2 = 5
2 - 9 % 5 = -7 % 5 = 3
Input Format
The first line of input contains an integer N. The second line of input is a single line containing a
mathematical expression. The expression will contain N integers, and (N-1) operators, separated by single
spaces.
Output Format
Constraints
2 <= N <= 8
Example Input
8+2*5-3/5%6
Output
Explanation
8+2*5-3/5%6
= 10 * 5 - 3 / 5 % 6
= 50 - 3 / 5 % 6
= 47 / 5 % 6
=9%6
=3
You are tasked with implementing a program that manipulates an empty Dictionary based on a series of
commands.
Input Format
The first line of input contains an integer N, indicating the number of commands
insert K: Insert a key-value pair (K,1) into the Dictionary. If the key (K) already exists, increment the count
associated with that key by 1.
search K: Search for a key (K) in the Dictionary. If the key exists, print True, otherwise print False.
delete K: Completely remove the key (K) from the Dictionary. remove K: If the count associated with the
key (K) is greater than 1,
decrement the count by 1. If the count is 1, completely remove the key from the Dictionary.
get K: Retrieve the count associated with the key from the Dictionary. size: Gives the size of the
Dictionary.
Output Format
For size and search command, print the result. For the remaining commands, print the sorted (K:V) of the
Dictionary separated by spaces (see example for more details). If the Dictionary is empty, skip printing the
Dictionary.
Constraints
1 <= N <= 50
For delete K, remove K and get K commands => K ∈ {Keys in the Dictionary}
Example Input
10
insert 5
insert 10
insert 66
insert 66
remove 66
search 10
delete 10
insert 3
get 3 size
Output
5:1
5:1 10:1
Given two arrays of size N and M, insert them into two sets A and B. Implement the following operations
in the same sequential order:
Union of A and B: Find the union of A and B, print the elements of the resulting set in sorted order.
Intersection of A and B: Find the intersection of A and B, print the elements of the resulting set in sorted
order.
Symmetric Difference of A and B: Find the symmetric difference of A and B, print the elements of the
resulting set in sorted order.
Check if A and B are disjoint sets: If yes, print true, otherwise, print false. Check if A is a subset of B: If yes,
print true, otherwise, print false.
Input Format
The first line of input contains N, the size of array1. The second line of input contains N elements of
array1.
The third line of input contains M, the size of array2. The fourth line of input contains M elements of
array2.
Output Format
For subset, superset, and disjoint operations print True or False. And for remaining all operations, if
resulting set is not empty, print the sorted set separated by spaces, otherwise skip printing the set.
Constraints
1 <= N, M <= 50
Example Input
9687
996
Output
6789
69
78
Your goal is to find the minimum total unhappiness by serving all guests in any order you choose.
Please note that at a given time, only one guest can be served, and each guest takes exactly one unit of
time to be served.
1 <= Ci <= N
Output: 2
Input: 4 1 1 1 1
Output: 6
2 Find the minimum possible absolute difference between the maximum and minimum sum of
elements in 4 non-empty contiguous subsequences of an array A of N elements by making three cuts.
Constraints:
Input:
10
10 71 84 33 6 47 23 25 52 64
Output: 36
3 You are given N people and K days, each day represented by an array of N numbers, indicating the
order of the people who arrived at the theatre. Your task is to find the largest group of people who arrive
in the same order for all K days.
Constraints:
1 <= K <= 10
Sample Input:
N=4, K=3
Day 1: [1, 3, 2, 4]
Day 2: [1, 3, 2, 4]
Day 3: [1, 4, 3, 2]
Sample Output:
4 You are given a string of length n consisting of numbers and question marks (# represents a mine,
and the number represents the sum of the number of mines in the adjacent cells). Your task is to fill the
question marks with either 0 or 1 in such a way that the string represents the correct sum of mines in the
adjacent cells. Return the number of ways to fill the question marks.
Constraints:
Example Input:
??0?1?
Example Output:
Example explanation: Two possible ways to fill the question marks are #1001# and 00001#.
1 Shyam has N various varieties of dishes lined up in a row: A1, A2,..., AN, where Ai signifies the
type of the ith dish. He wants to select as many dishes as possible from the menu, but only if the following
two requirements are satisfied:
• He can select only one sort of dish.
Now the query is that Shyam wants to know which type of dish he should select so that he has the option
of choosing the maximum number of dishes possible.
Example:
As we can see here, For type 1, Shyam has a maximum of four dishes to choose from. Selecting A1, A4, A7,
and A9 is one of the possible ways of selecting four dishes of type 1.
For type 2, Shyam has a maximum of two dishes to choose from. One way is to select A3 and A5. In this
situation, Shyam should go for type 1, which allows him to select comparatively more dishes.
Input Format
T, the number of test cases, appears on the first line. Then there are the test cases following T.
The first line of each test case contains a single integer N. And the N integers A1, A2,..., AN appears on the
second line.
Constraints
Output Format
Print a single line for each test case containing one integer indicating the type of dish Shyam should
select. Print the smallest response if there are multiple answers.
Sample Input:
12212
111111
12223421
Sample Output: 1
2 Sam is handed a rectangular piece of paper with the dimensions h*w, where h denotes height and
w denotes width. Sam wants to fold the paper in the fewest possible moves such that its dimensions are
h1*w1. The paper could only be folded parallel towards its edges, and the dimensions should be integers
after folding. If h=8 and w=4, for example, fold the paper till it's h1, w1 = 6,1. First, fold the long edge 6
units to the side, resulting in a 6*4 paper. And then, Fold the page in three folds along the width 2 units
edge to achieve a 6*1 page.
Input Format
First line contains an integer denotes h Seconds line contains an integer denotes w Third line contains an
integer denotes h1
Constraints
h1 <= h w1 <= w
Output Format
Sample Output: 1
A delivery company is missing one package from a shipment of N packages. Each package has a unique
tracking number from 1 to N, but one is missing.
The company needs to quickly identify the missing package to ensure timely delivery.
Parameters:
Input Format:
Output Format:
• For each test case, print a single integer — the missing tracking number
Example Cases:
Case 1:
Input:
1235
Output:
Explanation:
The complete set is {1, 2, 3, 4, 5}. The number 4 is missing from the input list.
Case 2: Input: 1
23
Output:
1
Explanation:
Case 3:
Input:
12346
Output:
Explanation:
A spy receives a coded message where words are scrambled. The message must be decrypted by
reversing the order of words, while keeping the characters in each word intact.
The spy needs to decode the message before the enemy intercepts it.
Parameters:
• S :: STRING — the coded message (1 ≤ |S| ≤ 10⁵), consisting of words separated by single spaces
Input Format:
Output Format:
• For each test case, print the decoded message with the words in reverse order.
Example Cases:
Case 1:
Input:
There are two words: "hello" and "world". Reversing their order gives: "world hello".
Case 2 :
Input:
Explanation:
The words are: ["spy", "must", "decode", "message"]. After reversing: ["message", "decode", "must",
"spy"].
Case 3:
Input:
A bank uses a checksum validation system to verify account numbers. Given an account number, check if
it follows the correct checksum rule. If the checksum is incorrect, the account number is flagged for
review.
Checksum Rule:
The account number is valid if the sum of its digits is divisible by 10. Parameters:
Input Format:
Output Format:
• For each test case, print "Valid" if the account number passes the checksum, otherwise print
"Invalid".
Example Cases:
Case 1:
Input:
12340
Output:
Valid Explanation:
Case 2:
Input:
987654321
Output:
Invalid
Explanation:
Input:
1111111111
Output:
Valid Explanation:
A librarian needs to sort books by title efficiently to help visitors find books faster. The sorting must be
done in alphabetical order while handling large datasets.
• Titles :: STRING ARRAY — list of book titles (each title is a non-empty string of at most 100
characters)
Input Format:
Output Format:
• For each test case, print the sorted titles — one per line
Example Cases:
Case 1:
Input:
3
Harry Potter
Output:
• A Game of Thrones
• Cinderella
• Harry Potter
Case 2:
Input:
Case 3:
Input:
"A" comes before "T", so "Animal Farm" is listed before "The Great Gatsby".
Given the total bill amount and the number of people, calculate how much each person should pay.
Parameters:
Input Format:
Output Format:
• For each test case, print the amount each person should pay, rounded to 2 decimal places
Example Cases:
Case 1:
Input:
100 4
Output:
25.00
Explanation:
Case 2:
Input:
99 3
Output:
33.00
Explanation:
Case 3:
Input:
250 6
Output:
41.67
Explanation:
A city traffic management system needs to simulate traffic light changes at fixed intervals.
The system must ensure smooth traffic flow by switching between red, yellow, and green lights in
sequence:
Given the durations for each light, simulate the sequence of light changes over a given time period.
Parameters:
• T_total :: INTEGER — total time to simulate the light changes (1 ≤ T_total ≤ 1000)
Input Format:
Output Format:
• For each test case, print a single line with space-separated names of lights (Red, Green, or
Example Cases:
Case 1:
Input:
2115
Output:
Lights sequence:
1-2 → Red
3 → Green
4 → Yellow
5 → Red
Case 2:
Input:
1116
Output:
Each light lasts 1 second → cycle is 3 seconds Repeat cycle twice to get 6 total seconds
Case 3:
Input:
3 2 1 10
Output:
Red Red Red Green Yellow Red Red Red Green Yellow Explanation:
Cycle: Red(3s) → Green(1s) → Yellow(2s) → total cycle = 6 seconds Next cycle continues from second 7 to
10
A cinema hall has multiple available seats, and customers want to book the best seat.
The system should recommend the seat closest to the center for an optimal viewing experience.
Parameters:
Input Format:
Output Format:
• For each test case, print the seat number that is closest to the center position of all available
seats.
• If there are multiple such seats, print the smallest seat number.
Example Cases:
Case 1:
Input:
10 20 30 40 50
Output:
30
Explanation:
Case 2:
Input:
123789
Output:
Explanation:
Center = (1 + 9) / 2 = 5
Case 3:
Input:
4
13 17 20 25
Output:
17
Explanation:
• 17 (distance 2)
• 20 (distance 1) → closer
So, output = 20
Given a set of temperature readings, find the highest and lowest temperatures recorded to help
Parameters:
Input Format:
Output Format:
• For each test case, print two space-separated integers:
Example Cases:
Case 1:
Input:
10 20 -5 30 15
Output:
30 -5
Explanation:
Case 2:
Input:
0000
Output:
00
Explanation:
Case 3:
Input:
-1 -30
Explanation:
A social media platform needs to generate unique usernames for new users.
The username should be based on the user's name and birth year, ensuring uniqueness by combining
them.
Parameters:
Input Format:
Output Format:
Example Cases:
Case 1:
Input:
Alice 1995
Output:
alice95 Explanation:
Case 2:
Input:
Bob 2001
Output:
bob01 Explanation:
Case 3:
Input:
Eve 1987
Output:
eve87 Explanation:
Parameters:
Input Format:
Output Format:
• For each test case, print the final price after applying the discount, rounded to 2 decimal places.
Example Cases:
Case 1:
Input:
10
Output:
540.00
Explanation:
Case 2 :
Input:
150 350
20
Output:
400.00
Input:
50 50 50 50 50
Output: 237.50
Explanation:
Sum = 250
Banks monitor transactions for suspicious activities to prevent fraud. Given a series of financial
transactions, your task is to find the longest sequence of consecutive transactions that add up to a target
suspicious sum K. This will help detect potential fraud patterns.
Parameters:
• N: number of transactions
• K: suspicious sum to detect
Input Format:
Output Format:
Example Cases:
Example Case 1:
Input:
5 12
24281
Output:
Explanation:
The longest sequence with sum 12 is [2, 4, 2, 8], but only the subarray [4, 2, 6] adds exactly to 12;
length is 3.
Example Case 2:
Input:
6 15
123456
Output:
Explanation:
Example Case 3:
Input:
4 10
1234
Output:
Explanation:
Parameters:
• S: input string
Input Format:
A single string S.
Output Format:
Example Cases:
Example Case 1:
Input:
dcba
Output:
abcd
Explanation:
Example Case 2:
Input:
aabbcc
Output:
aabbcc
Explanation:
Example Case 3:
Input:
zyx
Output:
xyz
Explanation:
A warehouse manages thousands of items daily. Some items sell more frequently than others, and your
task is to determine the most frequently sold product. By tracking sales patterns, inventory can be
adjusted to meet customer demand effectively.
Parameters:
Input Format:
Output Format:
Example Cases:
Example Case 1:
Input:
Output:
apple
Explanation:
'apple' sold 3 times, more than any other.
Example Case 2:
Input:
Output:
pen
Explanation:
Example Case 3:
Input:
Output:
chair
Explanation:
An airline wants to provide the shortest flight route between two cities to save fuel and reduce travel
time. Given multiple flight routes, find the shortest path between two specified cities while ensuring
safety and efficiency.
Parameters:
• N: number of cities
Input Format:
First line contains two integers N and M. Next M lines contain three integers A,B,C. Last line contains two
integers X and Y. Output Format:
Example Cases:
Example Case 1:
Input:
44
125
2 3 10
343
1 4 20
14
Output:
18
Explanation:
Example Case 2:
Input:
33
124
236
1 3 15
13
Output:
10
Explanation:
Input:
21
127
21
Output:
No path
Explanation:
In a smart home, appliances consume electricity based on predefined schedules. To optimize energy
consumption, you must determine the best time slots to turn appliances ON/OFF to minimize overall
power usage while meeting household needs.
Parameters:
• N: number of appliances
Input Format:
First line contains two integers N and T. Next N lines contain two integers S and E. Output Format:
Example Cases:
Example Case 1:
Input:
3 24
15
6 10
11 15
Output:
Schedule with minimal overlap
Explanation:
Example Case 2:
Input:
2 12
16
7 12
Output:
Explanation:
Example Case 3:
Input:
4 24
14
38
7 12
11 16
Output:
Explanation:
An online auction platform needs a mechanism to determine the highest bid for an item in real-time. Each
bidder places their bid, and the system must identify the highest valid bid before the auction closes.
Parameters:
• N: number of bids
Input Format:
Output Format:
Example Cases:
Example Case 1:
Input:
1 100
2 150
3 120
Output:
150 2
Explanation:
Example Case 2:
Input:
1 200
2 180
3 210
4 190
5 205
Output:
210 3
Explanation:
Example Case 3:
Input:
1 50
2 50
Output:
50 1
Explanation:
An emergency occurs in a large building, and an evacuation plan needs to be executed efficiently. Given a
building layout with multiple rooms, your task is to find the shortest escape path from a given starting
location to the nearest exit.
Parameters:
• N: number of rooms
• M: number of hallways
• X: starting room
Input Format:
First line contains two integers N and M. Next M lines contain two integers A and B. Last line contains
integer X.
Output Format:
Example Cases:
Example Case 1:
Input:
55
12
23
34
45
15
Output:
Explanation:
Example Case 2:
Input:
43
12
23
34
Output:
Explanation:
Example Case 3:
Input:
32
12
23
3
Output:
Explanation:
A stock analyst wants to identify long-term stock price trends. Given a list of stock prices recorded over N
days, determine the longest consecutive increasing trend. This helps traders make informed investment
decisions.
Parameters:
• N: number of days
Input Format:
Output Format:
Example Cases:
Example Case 1:
Input:
Output:
Explanation:
Example Case 2:
Input:
5
54321
Output:
Explanation:
Example Case 3:
Input:
123456
Output:
Explanation:
A music streaming platform wants to generate the most popular playlist based on listening history. Given
a list of songs played, identify the top K most frequently played songs.
Parameters:
Input Format:
Output Format:
Example Cases:
Example Case 1:
Input:
72
Output:
song1 song2
Explanation:
Example Case 2:
Input:
53
ababc
Output:
abc
Explanation:
Example Case 3:
Input:
41
aabc
Output:
Explanation:
A hospital emergency room must prioritize patients based on severity. Each incoming patient is assigned a
severity score, and the system must always serve the most critical patient first.
Parameters:
• N: number of patients
• P,S: patient ID P with severity score S
Input Format:
Output Format:
Example Cases:
Example Case 1:
Input:
101 5
102 10
103 7
Output:
102
Explanation:
Example Case 2:
Input:
201 8
202 8
203 7
204 6
Output:
201
Explanation:
Tie in severity 8, earliest patient 201 chosen.
Example Case 3:
Input:
301 3
302 4
Output:
302
Explanation:
Sample 1
Today you decided to go to the gym. You currently have E energy. There are N exercises in the gym. Each
of these exercises drains Ai amount of energy from your body.
You feel tired if your energy reaches 0 or below. Calculate the minimum number of exercises you have to
perform such that you become tired. Every unique exercise can only be performed at most 2 times as
others also have to use the machines.
If performing all the exercises does not make you feel tired, return
-1.
Parameters:
E :: INTEGER
The first line contains an integer, E, denoting the Energy. E :: 1 -> 10^5
N :: INTEGER
A :: INTEGER ARRAY
Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing the amount of energy
drained by ith exercise.
Case#: 1
Input:
Output:
E=6
Input:
10
Output:
-1
E = 10
By doing both the exercises 2 times you won’t feel tired. Case#: 3
Input:
Output:
E=2
Sample 2
There is a battle between heroes and villains going on. You have M heroes, all of them have the same
health H. There are N villains, health of the ith villain is Vi.
When a hero, with health H battles a villain with health Vi, one of the three scenarios can happen:
if H > Vi: The villain is defeated and the health of the hero is decreased by Vi
if H < Vi: The villain wins, his health is not affected and the hero is no longer able to fight.
if H = Vi: Both of them are considered defeated and neither can fight.
The heroes start fighting villains one by one in the same order, first villain 1 then villain 2 and so on. It is
might be possible that before defeating all the villains, all the heroes are defeated. Therefore, to ensure
the victory of the heroes, you want to remove some villains from the front.
Your task is to find the minimum number of villains you need to remove from the front such that the
victory of the heroes is guaranteed.
Note: If in the last battle, both the hero and villain are defeated and no more heroes or villains remain, it
would still be considered a victory since all the villains are defeated.
Parameters:
N :: INTEGER
The next line contains an integer, H, denoting the health of each of the heroes
H :: 1 -> 10^9
Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing the health of each of
the villains.
Input:
Output:
[3, 1, 3, 3]. We have 4 heroes will health 3. The heroes 1 will fight villain 1. Both get defeated. The hero 2
fights villain 2. It wins the battle and now his health is 2. He fights the third villain and loses, the villain still
has health 3. The hero 3 fights villain 3 and both get defeated. Hero 4 fights villain 4 and both get
defeated. So no need to remove any villain.
Case#: 2
Input:
3
1
Output:
The fight will take place and hero 1 will defeat villain 1 and 2. Hero 2 will defeat villain 2. Hero 3 will
defeat villain 3 and 4
Case#: 3
Input:
Output:
Only 1 hero is present with health 4. Since you can only remove villain from the front, you will have to
remove the first 3 villains to ensure victory. The hero can fight the last 2 villain of health 1 and 3
respectively and win the battle.
You need to build a road in a rugged terrain. You know the sea level of each segment of the rugged
terrain, i.e. the i-th segment is Li meters from sea level.
You needs to transform the terrain into a strictly downward sloping terrain for the road, i.e, for each i-th
segment where 2 <= i
<= N, resultant Li-1 > Li. In order to do so, you employ a powerful digging team to help you dig and reduce
the sea level of the segments. On day D, the team can reduce the sea level for each segments that you
scheduled that day by 2D-1 meters each.
You are allowed to assign the team to dig on multiple segments and/or dig on the same segments for
multiple days.
Your task is to find the minimum number of days needed to transform the terrain as per your
requirements.
Parameters:
N :: INTEGER
N :: 1 -> 10^5
L :: INTEGER ARRAY
Each line i of the N subsequent lines (where 0 < i ≤ N) contains an integer describing Li, the sea level of the
i-th segment.
Case#: 1
Input:
Output:
We can dig on the 2nd segment, reducing it from 3-meter sea level to 2. Resulting in {3, 2} which is strictly
decreasing.
Case#: 2 Input:
2
-3
Output:
Input:
-1
Output:
-1, -2}
Sample 4
You are given an array of size N. You need to change this array into a mountain. By mountain we mean,
the either ends of the array should have equal elements. Then as we move towards the
middle from both ends, the next element is just one more than the previous one. So it would have a peak
in the middle and decreases if you go towards either end, just like a mountain.
difference is 2. The array [1, 2, 3, 1] is also not a mountain because the elements 2 and 3 are not equal
from both ends.
You need to find the minimum number of elements that should be changed in order to make the array a
mountain. You can make the elements negative or zero as well.
Parameters:
N :: INTEGER
The first line contains an integer, N, denoting the number of elements in array.
N :: 1 -> 10^5
Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing i-th element of array.
Input:
Output:
2
array = [1, 2, 3, 4, 5] . We can change 4 and 5 to make it [1, 2, 3, 2, 1]
Case#: 2
Input:
Output:
3, 2, 1, 0, -1]
Case#: 3
Input:
5
5
Output:
Sample 5
You have an interesting string S of length N. It is interesting because you can rearrange the characters of
this string in any order. You want to cut this string into some contiguous pieces such that after cutting, all
the pieces are equal to one another.
You can’t rearrange the characters in the cut pieces or join the pieces together. You want to make the
number of pieces as large as possible. What is the maximum number of pieces you can get?
Note: You can observe that you may not want to cut the string at all, therefore the number of pieces is 1.
Hence, the answer always exists.
Parameters:
S :: STRING
The first line contains a string, S, denoting the string. len(S) :: 1 -> 2 * 10^5
Case#: 1
Input:
zzzzz
Output:
You can cut it into 5 pieces “z” + “z” + “z” + “z” + “z” Case#: 2
Input:
ababcc
Output:
Rearrange the string as abcabc. you can cut it into “abc” + “abc”, hence the answer is 2
Case#: 3
Input:
abccdcabacda
Output:
2
Sample 6
You are allowed to choose at most one pair of elements such that distance (defined as the difference of
their indices) is at most K and swap them.
Notes:
An array x is lexicographically smaller than an array y if there exists an index i such that xi<yi, and xj=yj for
all 0≤j<i. Less formally, at the first index i in which they differ, xi<yi
Parameters:
N :: INTEGER
N :: 1 -> 10^5
A :: INTEGER ARRAY
Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing A[i].
The next line contains an integer, K, denoting the upper bound on distance of index.
K :: 1 -> N
Case#: 1
Input:
Output:
2
2
Here as all the array values are equal swapping will not change the final result.
Case#: 2
Input:
Output:
Here A=[5,4,3,2,1] K=3, we can swap elements at index 0 and index 3 which makes A=[2,4,3,5,1].
Case#: 3
Input:
1
1
Output:
Here A=[2,1,1,1,1] K=3, we can swap elements at index 0 and index 3 which makes A=[1,1,1,2,1].
Sample 7
Your friend knows that there are exactly N dishes in the restaurant. The type of the dishes is described by
an array Arr. This means that if two elements of Arr have the same value, then they are from the same
type.
Your friend wants to eat as many dishes as possible. However, your friend will never order more than one
serving of a particular dish.
It is given that the restaurant will not let you order the dishes of the same type more than once.
Moreover, if you order A dishes in the restaurant your next order must contain (2*A) dishes. It is also
given that the restaurant does not accept orders containing more than one type of dishes in the same
order.
Your friend can start eating with any number of dishes. Find the maximum number of dishes that your
friend can eat.
Notes:
Your friend is a foodie and can eat any amount of food that is served to him by the restaurant.
Parameters:
N :: INTEGER
The first line contains an integer, N, denoting the number of elements in Arr.
N :: 1 -> 10^5
Each line i of the N subsequent lines (where 0 ≤ i < N) contains an integer describing Arr[i].
Arr[i] :: 1 -> 10^9
Case#: 1
Input:
Output:
N=5
A=[1,2,4,2,3]
For example, start with type 1 or 4, then double the amount by eating two of type 2 dishes.
Case#: 2
Input:
Output:
6
N=7 A=[2,2,1,1,1,1,1]
Start with eating two dishes of type 2, then eat four dishes of type 1.
Note that you can’t start with one dish of type one, then two dishes of type 2, and get back to eat to a
dish of size 1 again, your friend cannot eat the same type of dishes multiple times.
Case#: 3
Input:
Output:
N=4 A=[1,1,1,1]
Problem Statement:
You are given a grid of size n × m where some cells are known to be either light (0) or dark
(1). Your task is to count the number of valid full configurations such that:
• The XOR of colors of all adjacent pairs of cells is even (i.e., total XOR is 0).
o n: Number of rows
o m: Number of columns
o For k lines: xi, yi, ci representing a known cell at (xi, yi) with color ci
Input
335
110
121
220
321
330
224
110
121
211
220
Output
4
0
Given an array, delete the minimum number of elements to make it a "good" array. An array is good if:
Parameters
Input
132213
Output
You are given students' predictions for boarding on days. Vadim wants to ensure that at least one student
sees both of their predictions come true on consecutive days. Determine if it’s guaranteed.
Parameters
• t: Number of test cases
o n: Number of students
Input
123
5555
Output
Yes No
You have n sticks of unique lengths 1 to n. Arrange them to satisfy a string s consisting of '<' and '>'
characters.
Parameters
Input
<><
Output
1423
Given an array of integers, remove any number of elements (without rearranging) to maximize the
number of non-overlapping contiguous subarrays with positive sum.
Parameters
o N: Length of array
o A: Array of integers
Input
1 -2 3 4 -1
4
-1 -2 -3 -4
Output
Given a string S, find the lexicographically largest subsequence possible by removing characters (order
must be maintained).
Parameters
Input
abcbdab edcba
Output
ddb e
reach all other nodes directly or indirectly. Count how many nodes are essential.
Parameters
o M lines of edges u v
Input
44
12
23
34
13
Output
1
Parameters
o M lines of edges u v
Input
33
12
23
31
42
12
34
Output
Yes No
value x, find the maximum XOR between x and any value in u’s subtree.
Parameters
• N: Number of nodes
• A: List of N values
• Q: Number of queries
• Q lines of queries: u x
Input
1 23 45
1 2
1 3
2 4
2 5
1 1
2 6
3 7
Output
4
You are given an array of N integers. Answer Q queries: for each, find the K-th smallest number in
subarray A[L...R].
Parameters
• N: Length of array
• A: The array
• Q: Number of queries
• Q queries: L R K
Input
15263
132
253
154
Output
5
Neo wants to escape from the Matrix. In front of him are n buttons arranged in a row, each with an
integer weight a₁, a₂, …, aₙ. Neo is immobilized but can create and move clones. Each clone:
Whenever a clone stands in front of an unpressed button, it presses it instantly. Buttons can only be
pressed once. To escape, the sequence of button weights pressed must be non- increasing.
Find the minimum number of clones Neo needs to create to press all buttons in such an order.
Parameters
Input
4 3 2 1 5
1 1 1
7 8 1 5 92
10
1 7 9 7 1 10 2 10 10 7
Output
2
Given a binary string s of length n, a grid g of size n x n is constructed such that row i is the result of
flipping the i-th character of s. A good set S of size k consists of unique cell coordinates (x, y) such that:
• Each g[x][y] = 0
• All cells in S are part of a single connected region (adjacent in 4 directions) Determine the
maximum size of such a good set for each test case.
Parameters
Input
000
0010
1011001
4
0001
11
Output
10
1. Compute x+1
3. Sort the resulting string’s digits in non-decreasing order Determine how many distinct strings S(x)
exist for x ∈ [1, n]. Parameters
Input
2
42
1337
Output
42
948
You are given a final binary grid n × m. Balls can be pushed from the left (into rows) or top (into columns).
Rules:
• If they hit another ball, the new ball stops and pushes the existing one.
Parameters
33
001
001
110
33
010
111
010
33
111
111
111
33
000
000
000
33
000
000
001
Output
YES YES YES YES NO
You have two lanes starting with 1 person each. You're given n pairs of gates. Each gate can be:
• + a: Add a people
• x a: Multiply by a
Gained people can be added to either lane. Find the maximum total people after all operations.
Parameters
Input
+ 4 x 2
x 3 x 3
+ 7 + 4
+ 9 x 2
x 2 x 3
+ 9 + 10
x 2 + 1
4
x 2 + 1
+ 9 + 10
x 2 x 3
+ 9 x 2
x 3 x 3
x 2 x 2
+ 21 + 2
x2x3
+ 41 x 3
Output
32
98
144
351
You are given a string s consisting of characters A and B. Your task is to split it into blocks of length 1 and 2
such that:
Parameters
o a, b, ab, ba: Maximum allowed counts for "A", "B", "AB", and "BA" blocks respectively
Input
00 10 10
01 00
ABA
00 11
ABBABAAB
5500
ABABBAABBAAB
1123
ABBBBAB
0320
BAABBA
1320
Output
You have two bags. Initially, the first contains n numbers, the second is empty. You can:
2. Increase a number in the first by 1, if the same number exists in the second.
Parameters
Input
1 1
2 1
4
1 1 4 4
3 4 3 3
2 3 4 4
3 3 4 5 3 3
2 2 2 4 4 4
1 1 1 1 1 1 14
10
9 9 9 10 10 10 10 10 10 10
Output
Parameters
• t: Number of test cases
o n: Array length
Input
3 1 4 -1 -5 -9
-10 -3 -17 1 19 20
Output
23
40
There are n pupils with heights a[i]. The lineup is comfortable if a[i] * 2 ≥ a[i+1] for all valid i.
Each pizza increases any pupil's height by 1. Distribute at most k pizzas to maximize max(a)
o a: Initial heights
Input
21
10 20
10
67
312 456
16
32
64
10 4
10
100
1000
10000
Output
26
7 8 10 12 19 35 67
There are n lilypads, Alice and Bob start on different pads a and b.
On each turn, the frog must jump left or right if not occupied. Alice moves first. If a frog has no valid
move, it loses. Determine if Alice can guarantee a win.
Parameters
o n: Number of lilypads
Input
212
331
423
524
762
Output
Input format:
The input consists of several lines, each representing an item.Each item is represented by two
integers separated by a space: the weight of the item followed by its value.The input terminates with
a line containing a single integer -1. After the items, there is an integer representing the maximum
weight capacity.
Output format:
The output prints "The maximum value of the current list is: ", followed by a double value,
representing the maximum value that can be obtained by selecting fractions of items to fit into the
knapsack, rounded off to two decimal points.
Code constraints:
1 ≤ weight and values ≤ 1000
1 ≤ capacity ≤ 100
Sample test cases:
Input 1:
10 60
20 100
30 120
-1
50
Output 1:
The maximum value of the current list is: 240.00
Explanation:
We have 3 items:
Item 1: weight = 10, value = 60 → value/weight = 6.0
Item 2: weight = 20, value = 100 → value/weight = 5.0
Item 3: weight = 30, value = 120 → value/weight = 4.0
Capacity of knapsack = 50.
Take all of Item 1 (weight 10): Remaining capacity = 40, total value = 60.
Take all of Item 2 (weight 20): Remaining capacity = 20, total value = 160.
Take 20/30 = 2/3 of Item 3:
Value = (2/3) × 120 = 80
Remaining capacity = 0, total value = 240. Thus, the maximum value is 240.00.
61721
Output:
Explanation:
He can remove the second student from the line and now the order will be 6,7,2,1. And now he can
easily achieve the goal. 6+2 = 7+1 = 8. So there is one possible way and the output is 1.
Input format:
The first line of input denotes the size of an array, N.
The next line contains N space-separated integer elements of the array.
Output format:
The output prints the number of possible ways Charlie can remove any student from the line to
achieve his goal.
Code constraints:
Input:
61721
Output:
Input:
22222
Output:
5
You are given the time at which customers enter a barbershop and leave after the service. You need
to find the minimum number of barbers required so that no customer waits for the service but is
served instantly.
Use greedy algorithm to solve the given problem.
Input format:
The first line of input is an integer value representing the total number of customers n.
The second line is space-separated integer values representing the arrival time.
The third line is space-separated integer values representing the leaving time.
Output format:
The output prints the number of barbers required.
Code constraints:
2≤n≤5
1 ≤ arrival time & leaving time ≤ 10
Example:
Input:
5
12345
23467
Output:
2
Explanation:
All men arriving at times 1, 3, and 5 can be served by Barber 1. Here, Barber 2 serves all men who
enter the shop at times 2 and 4, so another barber is needed. Therefore, a total of two people is
required.
5
12345
23467
Output 1:
2
Input 2:
2
13
24
Output 2:
1
Input format:
The first line consists of the document text.
The second line consists of the text to be searched.
Output format:
The output prints the starting indices of all occurrences of the sentence in the document, separated
by spaces.
Code constraints:
The document text can hold up to 1000 characters. The text to be searched can hold up to 100
characters.
The text to be searched is case-sensitive.
Sample test cases:
Input:
The quick brown fox jumps over the lazy dog. The quick brown fox is clever.
quick brown fox
Output:
4 49
Input:
The early bird catches the worm. Persistence pays off in the end.
bird Output: 10
Given a string S that consists of only alphanumeric characters and dashes. The string is separated
into N + 1 groups by N dashes. Also given an integer K. We want to reformat the string S, such
that each group contains exactly K characters, except for the first group, which could be shorter
than K but still must contain at least one character. Furthermore, a dash must be inserted between
two groups, and you should convert all lowercase letters to uppercase. Return the reformatted
string.
Input:
5F3Z-2e-9-w
4
Output:
5F3Z-2E9W
Explanation:
The string S has been split into two parts; each part has 4 characters.
Note: Two extra dashes are not needed and can be removed.
Input:
2-5g-3-J
2
Output:
2-5G-3J
Explanation:
The string s has been split into three parts; each part has 2 characters except the first part as it could
be shorter as mentioned above.
Input format:
The first line contains a string S which represents the original string that needs to be reformatted.
The string can contain alphanumeric characters and dashes (-).
The second line contains an integer K which represents the length of each group after reformatting.
Output format:
The output is a single string that represents the reformatted version of the input string S, grouped
according to the integer K.
Code constraints:
1 ≤ S.length() ≤ 100
S contains only alphanumeric characters and dashes (-).
1 ≤ K ≤ 100
Sample test cases: Input 1:
2-5g-3-J
2
Output:
2-5G-3J
Input:
5F3Z-2e-9-w
4
Output:
5F3Z-2E9W
Q6. Problem Statement
Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute difference
between their sums is minimum.
If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must have n-
m elements and the value of abs(sum(Subset1) – sum(Subset2)) should be minimum.
To achieve this, use dynamic programming to determine the closest possible sum to half of the
total sum of the set.
Input format:
The first line contains an integer n, representing the number of elements in the array.
The second line contains n space-separated integers, representing the elements of the array.
Output format:
The output prints a single integer representing the minimum difference between the sums of two
subsets of the given array.
Code constraints:
1 ≤ n ≤ 10
0 ≤ elements ≤ 100
Example Input
4
1 6 11 5
Output
1
Explanation:
Subset1 = {1, 5, 6}, sum of Subset1 = 12 Subset2 = {11}, sum of Subset2 = 11
6
314221
Output 1:
1
Input 2:
4
1 6 11 5
Output 2:
1
Input format:
The first line consists of a string.
The second line consists of a string for which Hannah wants to find anagrams in the stream.
Output format:
The output prints the starting indices of all segments in the stream where an anagram of the pattern
appears, separated by spaces.
Code constraints:
Both the stream and pattern contain only lowercase English letters.
cbaebabacd abc
Output 1:
Anagram found at index 0 Anagram found at index 6 Input 2:
xyzzyxzyxzyxzyxyz xyz
Output 2:
Anagram found at index 0 Anagram found at index 3 Anagram found at index 4
Anagram found at index 5 Anagram found at index 6 Anagram found at index 7
Anagram found at index 8 Anagram found at index 9 Anagram found at index 10
Anagram found at index 11 Anagram found at index 12 Anagram found at index 14
Input format:
The input consists of an integer N, representing the size of the chessboard (N x N).
Output format:
The output prints the configuration of the chessboard, with queens placed so that no two queens
threaten each other.
Code constraints:
4 ≤ N ≤ 20 Example Input:
4
Output:
0010
1000
0001
0100
Explanation: The output represents a valid arrangement of queens on the 4x4 chessboard, where
1 indicates the position of a queen and 0 indicates an empty cell.
In the first row, a queen is placed in the third column.
In the second row, a queen is placed in the first column.
In the third row, a queen is placed in the fourth column.
In the fourth row, a queen is placed in the second column.
This arrangement of queens on the board ensures that no two queens threaten each other.
4
Output:
0010
1000
0001
0100
Input:
6
Output:
000100
100000
000010
010000
000001
001000
Input format:
The first line consists of a string representing a long DNA sequence consisting of characters 'A',
'C', 'G', 'T'. The second line consists of the specific gene sequence to search for.
Output format:
The output prints the starting indices of all occurrences of the sentence in the document,
separated by spaces.
Code constraints:
The DNA strand string can hold up to 1000 characters.
The gene sequence to be searched can hold up to 100 characters.
The gene sequence to be searched is case-sensitive.
Sample test cases: Input 1:
AGCTTAGCTAGCTGCTAAGCTT AGCT
Output:
0 5 9 17
Input: AGCTCAG CA
Output:
4
Code constraints:
1 ≤ n ≤ 10
0 ≤ elements ≤ 100
Example Input:
5
40 20 30 10 30
Output:
26000
Explanation:
There are 4 matrices of dimensions 40×20, 20×30,
30×10, 10×30.
Let the input 4 matrices be A, B, C, and D.
The minimum number of multiplications is obtained by
putting parenthesis in following way (A(BC))D. The minimum is 20*30*10 + 40*20*10 +
40*10*30 Example 2
Input
5
12343
Output:
30
Explanation:
There are 4 matrices of dimensions 1×2, 2×3, 3×4,
4×3.
Let the input 4 matrices be A, B, C, and D.
The minimum number of multiplications is obtained by
putting parenthesis in following way ((AB)C)D. The minimum number is 1*2*3 + 1*3*4 +
1*4*3 = 30 Input format:
The first line contains an integer n, representing the number of matrices.
The second line contains n integers, where the ith integer represents the dimension of the
matrix. Output format:
The output prints a single integer representing the minimum number of scalar multiplications
needed to multiply the chain of matrices.
Sample test cases: Input 1:
5
40 20 30 10 30
Output 1:
26000
Input 2:
5
12343
Output 2:
30
Q11. Problem Statement
At a cybersecurity agency, around 100 encrypted messages come in for processing. Since the
length of the messages is quite long, manual labor does not help much. Hence, you are
appointed to create a program that helps in decoding the messages, given the following
information:
Messages come in a binary array format, i.e., an array where the elements are 0 and 1.
A meaningful message is formed if all the 1s are grouped together.
The number of swaps must be minimal to get a meaningful message.
For example. If an array is 1 0 0 1 0 1, then the minimum number of swaps is 1 so that all 1s
come together, thereby forming 0 0 0 1 1 1.
Input Format:
The first line has the number of elements in the binary array.
The second line consists of the elements separated by a space.
Output Format:
The output will display the minimum number of swaps required to group all 1s together, in the
following format:
Minimum number of swaps to group all ones together: <number_of_swaps>
Code Constraints:
1 ≤ n ≤ 30
The elements of the array are either 0 or 1.
Sample Input:
6
100101
Sample Output:
Minimum number of swaps to group all ones together: 1
Sample Input:
4
1001
Sample Output:
Minimum number of swaps to group all ones together: 1
Input Format:
The first line of the input consists of the value of n. The next input is the array of elements
separated by a space, which is either '0' or '1'.
Output Format:
The output displays the arranged array so that 0s and 1s are separated.
Code Constraints:
1 ≤ n ≤ 20
0 ≤ each element ≤ 1
Sample Input:
6
100111
Sample Output:
001111
Sample Input:
5
10010
Sample Output:
00011
Sample Input:
18
8
7 12 5 10 13 3 8 9
Sample Output:
5 + 13 = 18
10 + 8 = 18
Sample Input
100
10
20 50 30 80 45 60 75 40 20 60
Sample Output:
20 + 80 = 100
60 + 40 = 100
Note: Print only unique value pairs in the order they first appear in the array. Once a pair of
values has been printed, any other occurrences of the same pair (regardless of position) should
be ignored.
Input Format:
The first line of input consists of an integer sum, representing the target sum to be found.
The second line of input consists of an integer n, representing the number of elements in the
array.
The third line of input consists of n space-separated integers, representing the elements of the
array.
Output Format:
The first line of output consists of all pairs (if any) whose sum is equal to the given value.
Each output line should be in the format:
a + b = sum, where a and b are the numbers from the array that sum up to the given value
Code Constraints:
1 ≤ n ≤ 105
103 ≤ targetSum ≤ 103
-103 ≤ arr[i] ≤ 103
Sample Input:
xAbcyAAbcbAbccz Abc
Sample Output:
xyz
Explanation:
soldiers: xAbcyAAbcbAbccz pattern: Abc
Iteration:
0: xAbcyAAbcbAbccz
1: xyAAbcbAbccz
2: xyAbAbccz
3: xyAbcz
4: xyz
Input Format:
The first line of input represents "a fleet of soldiers" (an alphanumeric string).
The second line of input represents the kill "pattern" (alpha-numeric string).
Output Format:
The first line of output prints the remaining sequence of soldiers as a string, or "Defeat" if all
soldiers
have been killed.
Code Constraints:
1 ≤ length of soldiers ≤ 100 1 ≤ length of pattern ≤ 100
Defeat
Input 3:
AAbAbccc Abc Output 3:
Ac
Sample Input:
abcaaubcc
Sample Output:
aaabbcccu
Explanation
Imagine "abcaaubcc" as a queue, and each alphabet represents a person standing in a queue.
People of the same group are represented using the same alphabet. The first person you will
be checking is "a". You have to allow all the people in group "a". Then the list will be like
this: "aaabcubcc". The next person you will be checking is "b" Now the list will be updated
as "aaabbcucc". After checking c list, it will be "aaabbcccu". Then after checking "u" the
list will be the same as "aaabbcccu"
Sample Input:
zaynzaakony
Sample Output:
zzaaayynnko
Explanation
The output for the given test case will be "zzaaayynnko". It groups the characters 'z', 'z', 'a', 'a',
'a', 'y', 'y', 'n', 'n', 'k', 'o' together, which represent the grouped people standing in the queue.
Note: People of the same group will be represented using the same alphabetic character. Also,
only lowercase letters will be used.
Input format:
The first line of input consists of a string queue, representing the people standing in the queue.
Each character represents a person, and people in the same group are represented by the same
character. Output format:
The output prints the characters in the order they would enter the hall after grouping all people
of the same group together, maintaining their original order of appearance.
Code constraints:
The string contains only lowercase letters (a-z).
1 ≤ length of string ≤ 100.
Sample test cases:
Input 1:
abcaaubcc
Output 1:
aaabbcccu
Input 2:
zaynzaakony
Output 2:
zzaaayynnko
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
Input format:
The input consists of a string.
Output format:
The output prints the length of the longest palindrome that can be built with the given letters.
Code constraints:
The input string can be up to 50 characters long.
Sample test cases:
Input 1:
abccccdd
Output 1:
7
Input 2:
madam
Output 2:
5
Input 3:
abc
Output 3:
1
Input 4:
Aa
Output 4:
1
Q17.Problem Statement
We are given n-platform and two main running railway track for both direction. Trains which
needs to stop at your station must occupy one platform for their stoppage and the trains which
need not to stop at your station will run away through either of main track without stopping.
Now, each train has three value first arrival time, second departure time and third required
platform number.
We are given m such trains you have to tell maximum number of train for which you can
provide stoppage at your station.
Examples:
Input: n = 3, m = 6
Train no.| Arrival Time |Dept. Time | Platform No.
1 | 10:00 | 10:30 | 1
2 | 10:10 | 10:30 | 1
3 | 10:00 | 10:20 | 2
4 | 10:30 | 12:30 | 2
5 | 12:00 | 12:30 | 3
6 | 09:00 | 10:05 | 1
Output: Maximum Stopped Trains = 5 Explanation: If train no. 1 will left to go without stoppage then 2 and 6 can
easily be accommodated on platform 1. And 3 and 4 on platform 2 and 5 on
platform 3.
Input: n = 1, m = 3
Train no.|Arrival Time|Dept. Time | Platform No.
1 | 10:00 | 10:30 | 1
2 | 11:10 | 11:30 | 1
3 | 12:00 | 12:20 | 1
Output: Maximum Stopped Trains = 3 Explanation: All three trains can be easily stopped at platform 1.
Code Constraints:
1 <= N <= 100
1 <= M <= 104
Q18. Problem Statement
A new variety of rice has been brought in supermarket and being available for the first time,
the quantity of this rice is limited. Each customer demands the rice in two different packaging
of size a and size b. The sizes a and b are decided by staff as per the demand. Given the size
of the packets a and b, the total quantity of rice available d and the number of customers n,
find out maximum number of customers that can be satisfied with the given quantity of rice.
Display the total number of customers that can be satisfied and the index of customers that
can be satisfied.
Input: n = 5, d = 5
a = 1, b = 1
20
32
44
10 0
01
Output: 2
51
Input: n = 6, d = 1000000000
a = 9999, b = 10000
10000 9998
10000 10000
10000 10000
70000 70000
10000 10000
10000 10000
Output: 5
12356
Explanation: In first example, the order of customers according to their demand is:
Customer ID Demand
5 1
1 2
2 5
3 8
4 10
From this, it can easily be concluded that only customer 5 and customer 1 can be satisfied for
total demand of 1 + 2 = 3. Rest of the customer cannot purchase the remaining rice, as their
demand is greater than available amount.
Code Constraints:
1 <= n <= 10^5
(Up to 100,000 customers) 1 <= d <= 10^12
(Available rice quantity is very large, up to 1 trillion) 1 <= a, b <= 10^6
(Packet sizes a and b can be up to 1 million grams or units)
0 <= number of bags requested by a customer <= 10^6 Customer indexing is from 1 to n
Sum of rice needed by all customers will not exceed 10^18.
The customer demands are always non-negative integers.
You can serve customers in any order to maximize number of customers.
For example:
If N=3 and X=7 and array elements are [1,2,3].
Way 1 - You can take 4 elements [2, 2, 2, 1] as 2 + 2
+ 2 + 1 = 7.
Way 2 - You can take 3 elements [3, 3, 1] as 3 + 3 +
1 = 7.
Here, you can see in Way 2 we have used 3 coins to reach the target sum of 7.
Hence the output is 3.
Input Format:
The first line of input contains an Integer T denoting the number of test cases.
The first line of each test contains 2 space separated integers, N and X denoting the size of
the array and given target sum.
The second line of each test contains contains N elements space separated denoting the
elements of the array.
Output format:
print a separate line integer output for each test case.
Code Constraints:
1 <= T <= 10
1 <= N <= 15
1 <= nums[i] <= (2^31) - 1
1 <= X <= 10000
Sample Input 2:
2
34
12 1 3
2 11
21
Sample output 2:
2
6
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the
sequence has an edge connecting them. A node can only appear in the sequence at most once.
Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any non-empty path.
Input format: First line: Space-separated list of integers representing node values in level-order traversal. If a node is
absent (null), use "null" in its place.
Output format: single integer — the maximum path sum from any non-empty path.
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.
Code Constraints:
The number of nodes in the tree is in the range [1, 3 * 104].
-1000 <= Node.val <= 1000
Input Format:
First line: An integer n, the size of the array (number of days).
Second line: n space-separated integers representing arr[i], the stock prices on each
day.
Output Format:
A single integer: the maximum profit achievable.
If no profit is possible, print 0
Input: arr = [10, 7, 5, 8, 11, 9]
Output: 6
Explanation: Buy on day 3 (price = 5) and sell on day 5 (price = 11), profit = 11 - 5 = 6.
Output: 0
Explanation: In this case, no transactions are made. Therefore, the maximum profit remains
0.
Code Constraints:
1 <= n<= 105
0 <= arr[i] <= 106
Input Format: First line contains 3 integer inputs representing the size of the stack 1,stack 2
and stack 3 respectively.
Second third and fourth lines represent the space separated integers representing the stack
elements of stack 1 stack 2 and stack 3 respectively.
Output Format:
A single integer: the maximum equal sum achievable after removing some top elements.
Input:
342
423
1123
14
Output:
5
Explanation:
We can pop 1 element from the 1st stack, and 2 elements from the 2nd stack. Now remaining
elements yield the equal sum of the three stacks, that is 5.
Code Constraints:
1 <= n1, n2, n3 <= 104
(where n1, n2, n3 are the number of elements in stacks s1, s2, and s3 respectively)
1 <= element <= 105
(elements are positive integers)
Stacks may have different sizes (n1 ≠ n2 ≠ n3).
You can only remove elements from the top (start of the array). At any time, you can remove
zero or more elements from any stack. The stacks must be non- empty initially (i.e., each has
at least 1 element). Final sum must be equal for all three stacks after removals. You need to
maximize the common sum after removals. If it's not possible to achieve any common sum,
the result must be 0.
Input Format:
First line: Two integers V and E — the number of vertices and edges.
Next E lines: Each line contains three integers u v w, meaning there is an undirected edge
between vertex u and vertex v with weight w.
Output Format:
A single integer: the sum of the weights of all edges in the Minimum Spanning Tree (MST).
Input:
33
015
123
021
Output:
4
Explaination: The Spanning Tree resulting in a weight of 4 is shown below.
Code Constraints:
2 ≤ V ≤ 1000
V-1 ≤ E ≤ (V*(V-1))/2
1 ≤ w ≤ 1000
The graph is connected and doesn't contain self- loops & multiple edges.
Input format:
First line: An integer n, representing the number of trains.
Second line: n integers, representing the arrival times arr[] of the trains.
Third line: n integers, representing the departure times dep[] of the trains.
All times are given in 24-hour format without a colon (e.g., 9:00 AM is 900, 11:30 AM is
1130, etc.).
Output Format:
A single integer: minimum number of platforms needed so that no train waits.
Explanation: There are three trains during the time 9:40 to 12:00. So we need a minimum of
3 platforms. Input: arr[] = [900, 1235, 1100], dep[] = [1000, 1240,
1200]
Output: 1
Explanation: All train times are mutually exclusive. So we need only one platform.
Input
3
1000 935 1100
1200 1240 1130
Output: 3
Input Format:
First line: Single integer n (number of jobs). Second line: n space-separated integers
representing the deadline[] array.
Third line: n space-separated integers representing the profit[] array.
Output Format:
Output two integers separated by a space: First integer: Maximum number of jobs
done. Second integer: Maximum profit earned.
4111
20 10 40 30
Output:
2 60
Explanation: Job1 and Job3 can be done with maximum profit of 60 (20+40).
Input:
21211
100 19 27 25 15
Output:
2 127
Explanation: Job1 and Job3 can be done with maximum profit of 127 (100+27).
Code Constraints:
1 ≤ deadline.size() == profit.size() ≤ 105 1 ≤ deadline[i] ≤ deadline.size()
1 ≤ profit[i] ≤ 500
Output Format:
Print the index of the celebrity if one exists. Otherwise, print -1 if no celebrity exists.
Examples:
Input:
3
110
010
011
Output: 1
Explanation: 0th and 2nd person both know 1st person. Therefore, 1 is the celebrity
person.
Input:
2
11
11
Output: -1
Explanation: Since both the people at the party know each other. Hence none of them is a
celebrity person.
Input:
1
1
Output: 0
Code Constraints:
Input Format:
The first line contains an integer n, the number of nodes in the graph (size of the matrix).
The next n lines contain n integers, where each integer represents the weight of the edge
between nodes. A value of 108 indicates that there is no direct edge between the nodes
(infinity).
Note: Modify the distances for every pair in place.
Output Format:
Print the updated adjacency matrix after applying the Floyd-Warshall algorithm, which gives
the shortest distances between every pair of nodes in the graph.
Constraints:
1 ≤ dist.size() ≤ 100
-1000 ≤ dist[i][j] ≤ 1000
Input Format:
The first line contains two integers n and m, representing the number of children and the
number of cookies.
The second line contains n integers, representing the greed factor of each child (greed[i]).
The third line contains m integers, representing the size of each cookie (cookie[j]).
Output Format:
Example test cases:
Input: 3 2
123
11
Output: 1
Explanation: You can only assign cookie 0 or 1 to child 0.
Input:
23
12
123
Output: 2
Explanation: You can assign cookie 0 to child 0 and cookie 1 to child 1.
Constraints:
1 ≤ greed.size() ≤ 105
1 ≤ cookie.size() ≤ 105
1 ≤ greed[i] , cookie[i] ≤ 109
Input Format:
The first line contains two integers N and K, where N is the number of elements in the array
and K is the number of modifications you must perform.
The second line contains N integers representing the array arr[].
Output Format:
A single integer representing the maximum sum of the array after exactly K modifications.
51
1 2 -3 4 5
Output:
15
Explanation:
We have k=1 so we can change -3 to 3 and sum all the elements to produce 15 as output.
Input:
10 5
5 -2 5 -4 5 -12 5 5 5 20
Output:
68
Explanation:
Here we have k=5 so we turn -2, -4, -12 to 2, 4, and 12 respectively. Since we have
performed 3 operations so k is now 2. To getnmaximum sum of array we can turn positive
turned 2 into negative and then positive again so k is 0. Now sum is
5+5+4+5+12+5+5+5+20+2 = 68
Constraints:
1 ≤ N,K ≤ 105
-109 ≤ Ai ≤ 109
Input Format:
First argument is an integer array A. Second argument is an integer array B. Output
Format:
Return an integer denoting the minimum time when the last mouse gets inside the holes.
-4 2 3
0 -2 4
Output:
2
Explanation:
Assign the mouse at position (-4 to -2), (2 to 0) and
(3 to 4). The number of moves required will be 2, 2 and 1 respectively. So, the time taken
will be 2.
Input:
-2
6
Output:
4
Explanation:
Assign the mouse at position -2 to -6. The number of moves required will be 4. So, the time
taken will be 4.
NOTE:
Each dish is supposed to be eaten by only one person. Sharing is not allowed.
Each friend can take any dish an unlimited number of times.
There always exists a dish with a filling capacity of 1 so that a solution always exists.
Input Format:
Friends: A: List of integers denoting eating capacity of friends separated by space.
Capacity: B: List of integers denoting filling capacity of each type of dish.
Cost: C: List of integers denoting cost of each type of dish.
Output Format:
A single integer representing the minimum cost to satisfy all the friends
Example Input:
46
13
53
Example Output:
14
Explanation: The first friend will take 1st and 2nd dish, the second friend will take 2nd
dish twice. Thus, total cost = (5+3)+(3*2)= 14
Code Constraints:
1 <= Capacity of friend <= 1000 1 <= No. of friends <= 1000
1 <= No. of dishes <= 1000
Input Format:
First and only argument is an integer A. Output Format:
Return an integer denoting the number of ways to fill a 3 x A board with 2 x 1 dominoes with modulo 109 + 7.
Example Test case:
Input:
2
Output:
3
Explanation:
Following are all the 3 possible ways to fill up a 3 x 2 board.
Input:
1
Output:
0
Explanation: Not a even a single way exists to completely fill the grid of size 3 x 1.
Problem 1
In the land of Numerica, the Council of Integers faced a grand challenge issued by the wise
Mathmagician:
"Rearrange yourselves in such a way that, when read side by side, you form the largest number
possible.
Only then will you prove you might and earn the title of the Great Sequence!"
The integers need your help to determine the correct order to maximize their combined value.
Parameters:
T :: INTEGER
T :: 1 → 100
N :: INTEGER
N :: 1 → 1000
A :: INTEGER ARRAY
Case#: 1
Input:
101 21 92 97 203
Output:
97 92 21 203 101
Explanation:
The goal is to arrange the integers so their concatenation forms the largest possible number.
Sorted with custom comparator (xy > yx), we get: 97, 92, 21, 203, 101
Case#: 2
Input:
0000
Output:
0
Explanation:
All elements are zero. Any permutation gives 0000, which simplifies to a single 0.
Case#: 3
Input:
8 90 89 908 898 9
Output:
9 90 908 89 898 8
Explanation:
Problem 2
The Professor has discovered that a vast amount of gold is hidden beneath the Bank of Spain. To
execute a perfect heist, he first needs to calculate the total gold stored inside.
The gold is stored across a grid floor of size N x N, where each cell represents a room. The room
number is defined as the sum of its row and column indices.
The amount of gold in a room is calculated as the absolute difference between the sum of even
digits and the sum of odd digits in the room number.
You must compute the total gold units stored across all rooms in the bank for each test case.
Parameters:
T :: INTEGER
T :: 1 → 10⁵
N :: INTEGER
The size of the grid (N x N).
N :: 1 → 10⁶
Case#: 1
Input:
Output:
Total = 2
Case#: 2
Input:
Output:
12
(1,1) → 2 → |2 - 0| = 2
(1,2) → 3 → |0 - 3| = 3
(2,1) → 3 → |0 - 3| = 3
(2,2) → 4 → |4 - 0| = 4
Sum = 2 + 3 + 3 + 4 = 12
Case#: 3
Input:
1
3
Output:
36
2, 3, 4, 3, 4, 5, 4, 5, 6
Total = 36
Problem 3
You are a cricket analyst preparing a presentation for team owners. You have access to N match
scores of a player.
To highlight the player's performance, you want to display the longest increasing subsequence of
these scores — this means a sequence that is strictly increasing and not necessarily from consecutive
matches.
Find and return the length of this longest increasing subsequence (LIS) for each test case.
Parameters:
T :: INTEGER
T :: 2 → 9
N :: INTEGER
N :: 2 → 999
Input:
10 22 9 33 21 50
Output:
Length = 4
Case#: 2
Input:
54321
Output:
All scores are decreasing. Any single score is a valid LIS of length 1.
So the answer is 1.
Case#: 3
Input:
13254769
Output:
Length = 5
Problem 4
There are N people in a meeting. These N people are sitting in a circle. Each person has already
shaken hands with their two adjacent neighbors (left and right).
Now, every person must shake hands with all the remaining people except the adjacent ones.
Find the number of additional handshakes required so that every pair of non-adjacent people shakes
hands exactly once.
Parameters:
N :: INTEGER
N :: 1 → 10^4
Case#: 1
Input:
Output:
Each person has already shaken hands with their only neighbor.
Case#: 2
Input:
Output:
Remaining handshakes = 6 - 4 = 2
Case#: 3
Input:
Output:
Handshakes already done (one per neighbor per person, divided by 2 to avoid double-counting): 6
Remaining = 15 - 6 = 9
Problem 5
You are required to compute this count for each test case and output it.
Parameters:
T :: INTEGER
T :: 1 → 10
N :: INTEGER
N :: 1 → 10⁵
V :: INTEGER ARRAY
Case#: 1
Input:
1423
Output:
Total = 6
Case#: 2
Input:
Output:
Total = 1
Case#: 3
Input:
22222
Output:
15
Total subarrays = N * (N + 1) / 2 = 5 * 6 / 2 = 15
Problem 6
A string is called an "ab string" if it is composed of characters 'a' and 'b' and follows either of these
patterns:
You are allowed to remove any number of characters (possibly zero) from the string.
Your task is to determine the maximum possible length of a valid ab string that can be obtained after
such removals.
Parameters:
T :: INTEGER
T :: 1 → 100
S :: STRING
Case#: 1
Input:
abaababbbaaaabaaab
Output:
14
aa...aaabbbb...b
Resulting string is of the form "aaaaabbbbb", which is valid and of length 14.
Case#: 2
Input:
1
bab
Output:
Maximum length = 3
Case#: 3
Input:
bbbbababb
Output:
Problem 7
A factory has a set of machines, each assigned a specific task. The tasks are scheduled in the order
they arrive. If a machine is idle, it begins working on the next available task immediately.
Your task is to compute and print the completion time for each machine's task, assuming each
begins execution immediately after the previous one completes.
Parameters:
T :: INTEGER
T :: 1 → 10
N :: INTEGER
Number of tasks in a test case.
N :: 1 → 10⁵
Case#: 1
Input:
457
Output:
4 9 16
Explanation:
Case#: 2
Input:
23146
Output:
2 5 6 10 16
• Task 1: 2
• Task 2: 2+3 = 5
• Task 3: 5+1 = 6
• Task 4: 6+4 = 10
• Task 5: 10+6 = 16
Case#: 3
Input:
1111
Output:
1234
Each task takes 1 unit time and starts right after the previous one.
Problem 8
You are given a string s which contains lowercase and uppercase characters along with the asterisk
(*) character.
In one operation:
You remove the closest non-star character to its left, and also remove the star itself.
You must perform this operation for every star in the string, exactly once per star, and print the final
resulting string after all stars and the respective characters are removed.
It is guaranteed that:
Parameters:
T :: INTEGER
T :: 1 → 100
S :: STRING
Case#: 1
Input:
Dinesh**reddy****
Output:
Diner
Case#: 2
Input:
abcdef**
Output:
abcd
Case#: 3
Input:
ABCDEFG
Output:
ABCDEFG
Problem 9
You are given an array arr of integers indexed from 0. Your task is to find the greatest common
divisor (GCD) of the smallest and largest numbers in the array.
The GCD of two numbers is the largest positive integer that divides both numbers without leaving a
remainder.
Parameters:
n :: INTEGER
n :: 1 → 10⁵
arr[i] :: 1 → 10⁹
Case#: 1
Input:
2 4 6 8 10
Output:
• Minimum: 2
• Maximum: 10
• GCD(2, 10) = 2
Case#: 2
Input:
4
15 25 35 45
Output:
15
• Minimum: 15
• Maximum: 45
• GCD(15, 45) = 15
Case#: 3
Input:
17 34 51 68 85 102
Output:
17
• Minimum: 17
• Maximum: 102
• GCD(17, 102) = 17
Problem 10
Leo and his friend Max are playing a game with two stacks of nuts. Initially, the stacks have A and B
nuts respectively. They take turns, starting with Leo. The rules are as follows:
On a turn, a player:
If the remaining stack has only 1 nut, it cannot be split, and the player loses.
Parameters:
T :: INTEGER
The number of test cases.
T :: 1 → 1000
A, B :: INTEGER
Each test case contains two integers, the count of nuts in the two stacks.
A, B :: 1 → 10⁴
Case#: 1
Input:
11
Output:
Max
Leo starts, but both stacks have only 1 nut. If Leo eats one stack, the other cannot be split. So Leo
loses.
Case#: 2
Input:
12
Output:
Leo
Leo eats stack with 1 nut, splits the 2-nut stack into (1, 1). Now Max has no valid move, so Leo wins.
Case#: 3
Input:
45
Output:
Leo
Leo has many possible valid moves (e.g., eat 4 and split 5 into 2,3). With optimal strategy, Leo forces
Max into a losing position.
Problem 11
Rahul and Sameer are seated next to each other during an exam and want to share answers. There
are p different sets of questions numbered from 0 to p−1, assigned based on each student’s roll
number using the formula (roll number - 1) % p. They can only share answers if assigned the same
set of questions. Given Rahul’s roll number A and Sameer’s roll number B, find how many different
values of p allow them to have the same set of questions.
Parameters:
T :: INTEGER
A :: INTEGER
B :: INTEGER
Case#: 1
Input:
28
Output:
They get the same set if (A−1) % p == (B−1) % p → p divides |(B−A)| = |8−2| = 6.
Case#: 2
Input:
15 1
Output:
Input:
10 5
Output:
Problem 12
Aman loves chocolates and there are N chocolates in a bowl. Aman can only take m chocolates such
that m is a power of 2 and m ≤ N. The goal is to find the maximum number of chocolates Aman can
take.
Parameters:
T :: INTEGER
N :: INTEGER
Case#: 1
Input:
Output:
Case#: 2
Input:
25
Output:
16
Case#: 3
Input:
59
Output:
32
Problem 13
You are given two positive integers A and B. Your task is to find and print the sum of all prime
numbers between A and B (inclusive).
Parameters:
T :: INTEGER
A :: INTEGER
B :: INTEGER
Case#: 1
Input:
18 35
Output:
102
Case#: 2
Input:
1 20
Output:
77
Sum = 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 = 77
Case#: 3
Input:
10 10
Output:
Sum = 0
Problem 14
In a desolate, frozen wasteland, Alice and her family find themselves trapped inside a deserted
outpost with no escape. The only lifeline they have is a stockpile of frozen meals that have
miraculously survived the apocalyptic conditions.
In this icy realm, sustenance comes in the form of frozen meals, and each family member requires a
daily intake of X meals to stave off starvation. However, the twist lies in their ability to endure
beyond the depletion of their food supply.
After the last meal is consumed, the family can endure for an additional D days before succumbing
to the harsh environment.
Given the scarcity of resources, the pressing question is: for how many days can Alice and her family
brave the frozen desert?
Your task is to compute and output, for each test case, the total number of days Alice and her family
can endure in this frozen desert.
Parameters:
T :: INTEGER
N :: INTEGER
X :: INTEGER
D :: INTEGER
[Number of days the family can endure without sustenance after meals run out. 0≤D<200 ≤ D < 20]
Case#: 1
Input:
245 4 9
Output:
70
Daily need = 4
Total = 61 + 9 = 70
Case#: 2
Input:
405 2 0
Output:
202
With 405 meals and a daily need of 2, they survive 405 // 2 = 202 days.
Case#: 3
Input:
188 3 5
Output:
67
Total = 62 + 5 = 67
Problem 15
There are three students: Krishna, Ram, and Vishnu. Each is assigned a positive integer roll number:
a, b, and c. You are given min(a, b), min(b, c), and min(c, a). Determine if there exist positive integers
a, b, and c satisfying these three values.
Your goal is to output "YES" if such three integers exist, and "NO" otherwise.
Parameters:
T :: INTEGER
minAB :: INTEGER
minBC :: INTEGER
minCA :: INTEGER
Case#: 1
Input:
494
Output:
YES
Case#: 2
Input:
345
Output:
NO
Case#: 3
Input:
5 10 5
Output:
YES
Problem 16
San Te is starting the 37th Chamber of Shaolin to teach women self-defence. A woman is eligible for
training if her age is between 10 and 60 (inclusive). Given the ages of women in the village,
determine how many are eligible.
Your goal is to output the number of eligible women for each test case.
Parameters:
T :: INTEGER
N :: INTEGER
Case#: 1
Input:
53 39 4 10 37 32
Output:
Case#: 2
Input:
3 52 1
Output:
Only 52 is eligible.
Case#: 3
Input:
9 10 60 61 30
Output:
Problem 17
You are given a string of lowercase English letters. Construct a new string based on the following
rules:
1. Characters with higher frequency come first.
2. After placing a character once, reduce its count by one and repeat the process.
3. If two characters have the same frequency, choose the lexicographically smaller character first.
Parameters:
t :: INTEGER
len :: INTEGER
string :: STRING
Case#: 1
Input:
13
abcdccbacbcbc
Output:
ccbcbcabcabcd
‘c’ appears most, followed by ‘b’, then ‘a’, and finally ‘d’.
Case#: 2
Input:
47
sjdfvhwebuyuuuuuuuuuuuunndcvshhhhhhhvuiwoqwjeoqpo
Output:
uuuuuuhuhuhuhuhuhouvwdehjnoqsuvwbcdefhijnopqsuvwy
‘u’ appears most, followed by ‘h’, then sorted by frequency and lexicographical order.
Case#: 3
Input:
8
aabbccdd
Output:
abcdabcd
Problem 18
007 is preparing for an ambush mission. Out of N available weapons, each with a certain attack
rating, he can select any number of weapons as long as their total attack rating does not exceed a
specified limit K. His goal is to maximize the number of weapons he can carry without violating the
total attack rating limit.
Your goal is to output the maximum number of weapons 007 can carry within the given constraint.
Parameters:
T :: INTEGER
N :: INTEGER
K :: INTEGER
attack_ratings :: LIST[INTEGER]
Case#: 1
Input:
43
4521
Output:
Case#: 2
Input:
5 15
10 2 3 4 5
Output:
Selected: 2, 3, 4, 5 → total = 14
Case#: 3
Input:
32
345
Output:
Problem 19
Nikola Tesla wants to study N subjects numbered from 1 to N. He is given M prerequisite pairs [a, b],
meaning subject a must be completed before subject b. Determine if it is possible for Tesla to study
all subjects following these prerequisite conditions.
Parameters:
T :: INTEGER
Numberoftestcases(1≤T≤10)Number of test cases (1 ≤ T ≤ 10)
N :: INTEGER
M :: INTEGER
Case#: 1
Input:
21
12
Output:
Yes
Case#: 2
Input:
33
12
23
31
Output:
No
Case#: 3
Input:
1
43
12
23
34
Output:
Yes
Problem 20
A number is unlucky if it contains the substring "13". All other numbers are lucky. Given n, find how
many lucky numbers of length n digits can be formed. Leading zeros are allowed.
Parameters:
T :: INTEGER
N :: INTEGER
Case#: 1
Input:
Output:
10
99
Explanation:
• For n=1, all digits 0-9 are lucky (no "13" possible). So 10 lucky numbers.
• For n=2, total numbers = 100; exclude numbers with "13" as substring → 100 - 1 = 99.
Case#: 2
Input:
Output:
989
Explanation:
Count all 3-digit numbers (with leading zeros) excluding those containing substring "13".
Case#: 3
Input:
Output:
9801
Explanation:
Problem 21
Tribonacci Numbers: We all know about Fibonacci numbers where Fibonacci(n) = Fibonacci(n-1) +
Fibonacci(n-2), where Fibonacci(n) = n where 0 <= n <= 1. Tribonacci numbers are those numbers
whose value is equal to the sum of the previous 3 numbers of the same sequence, whereas in
Fibonacci it's just 2. So, given the N value, you are supposed to print the Nth Tribonacci number.
NOTE :tribonnaci(n) = n where 0 <= n <= 2.The value can be a huge value, So print the answer in mod
10^9+7
Parameters:
T :: INTEGER
Numberoftestcases(1≤T≤10)Number of test cases (1 ≤ T ≤ 10)
N :: INTEGER
Case#: 1
Input:
Output:
• Tribonacci(1) = 1
• Tribonacci(2) = 2
Case#: 2
Input:
Output:
Tribonacci(0) = 0
Case#: 3
Input:
Output:
11
Problem 22
Climb steps:You are on the ground level basically not on any step. In one instance you can either
climb 1 or 2 steps. Suppose you want to reach the Nth step.Print the total number of ways you can
reach your desired location.NOTE:The answer can be a large value, so print it in mod 10^9+7 format.
Print the total number of ways you can reach the Nth step under mod 10^9+7
Parameters:
T :: INTEGER
N :: INTEGER
Case#: 1
Input:
Output:
2
3
Case#: 2
Input:
Output:
Case#: 3
Input:
Output:
Ways to reach step 4 are 5 in total (1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2).
Problem 23
Ganesh Chaturthi is near, given n entries of donations where each entry has a group number (1 to
10) and the amount of money donated by a person, print the total amount collected by each group
from 1 to 10.
Parameters:
n :: INTEGER
money :: INTEGER
Case#: 1
Input:
1 12
24
34
2 56
1 22
Output:
1 34
2 60
34
40
50
60
70
80
90
10 0
Case#: 2
Input:
3
10 100
10 200
1 50
Output:
1 50
20
30
40
50
60
70
80
90
10 300
Case#: 3
Input:
5 75
Output:
10
20
30
40
5 75
60
70
80
90
10 0
Problem 24
Since her childhood Goldy loves playing with toys.On a fine day she went to a toy shopping mall with
her father and brought some set of toys of her choice to her home.Now she wants to arrange them
in such a ways that all the toys with same size should be at one place and while arranging, the count
of toys also matters i.e the size with maximum number of toys will be placed first and then with
second maximum number of toys and so on until all the toys get arranged. If number of toys of two
or more sizes are equal then arrange the toys with smaller size first. As Goldy is very confused about
how to arrange, she asked your help to do so. Output the toys arranged accordingly.
Parameters:
N :: INTEGER
A :: ARRAY[INTEGER]
Case#: 1
Input:
25285688
Output:
88822556
Case#: 2
Input:
112233
Output:
112233
Case#: 3
Input:
4441223
Output:
4442213
Problem 25
Yashwanth was so hungry so he went to KFC to eat, while he was eating his mobile suddenly fell
down from his hand and broke. so, now he cannot pay online. Now he has to pay hand cash. He has
many 2000,500,200,100,50,20,10,5,2,1 coins. He wants to pay the bill with fewer coins. So, he is
asking for your help to find it.
Parameters:
T :: INTEGER
N :: INTEGER
Case#: 1
Input:
547
673
556
9989
2550
Output:
Case#: 2
Input:
1235
4222
489
Output:
Explanation for 1235: 2000(0), 500(2), 200(1), 100(0), 50(0), 20(1), 10(1), 5(1), 2(0), 1(0) = 6 coins
Case#: 3
Input:
45454
87778
Output:
29
52
Problem 26
Given an array A, count the number of inversion pairs (j, k) such that j < k and A[j] > A[k].
Parameters:
n :: INTEGER
A :: ARRAY of INTEGER
ArrayelementsArray elements
Case#: 1
Input:
20
Output:
Case#: 2
Input:
4
3
Output:
All pairs form inversions: (4,3), (4,2), (4,1), (3,2), (3,1), (2,1)
Case#: 3
Input:
Output:
Problem 27
Given an encrypted string where characters are followed by their frequency, find the Nth character
in the decrypted string. If N is larger than the length of the decrypted string, print -1.
Parameters:
s :: STRING
N :: INTEGER
Case#: 1
Input:
a1b1c3d23
Output:
Case#: 2
Input:
a1b1c3
10
Output:
-1
Case#: 3
Input:
x2y10z1
12
Output:
Problem 28
A factory has a set of machines, each assigned a specific task. The tasks are scheduled in the order
they arrive. If a machine is idle, it begins working on the next available task immediately.
Parameters:
T :: INTEGER
T :: 1 → 10
N :: INTEGER
N :: 1 → 10⁵
Case#: 1
Input:
457
Output:
4 9 16
Explanation:
Case#: 2
Input:
23146
Output:
2 5 6 10 16
• Task 1: 2
• Task 2: 2+3 = 5
• Task 3: 5+1 = 6
• Task 4: 6+4 = 10
• Task 5: 10+6 = 16
Case#: 3
Input:
1111
Output:
1234
Each task takes 1 unit time and starts right after the previous one.
Problem 29
MTV is given an integer sequence of N numbers. But he only likes natural numbers. So he removes
some numbers from the given sequence of N numbers so that the formed sequence is contiguous
natural number sequence starting from 1.
Let us say there are K numbers after removing some numbers from initial sequence, MTV will be
satisfied if, for each integer i (1 ≤ i ≤ K) , the i-th of those numbers from the left is equal to i. See
sample test cases for better understanding.
Print the minimum number of numbers that MTV has to remove from the initial sequence(i.e, K
should be maximized). If no sequence can be formed the print -1.
Parameters:
N :: INTEGER
Case#: 1
Input:
212
Output:
Removing the first element gives [1, 2], which forms a natural sequence starting from 1. So minimum
removals = 1.
Case#: 2
Input:
13245
Output:
Case#: 3
Input:
2345
Output:
-1
Problem 30
You are given an integer array A. Your task is to calculate the sum of absolute difference of indices of
first and last occurrence for every integer that is present in array A.
Formally, if element x occurs m times in the array at indices B1, B2, B3, ...,Bm, then the answer for x
will be Bm−B1 if array B is sorted.
You are required to calculate the sum of the answer for every such x that occurs in the array.
Parameters:
T :: INTEGER
N :: INTEGER
A[i] :: INTEGER
Element of the array (1 ≤ A[i] ≤ 1e9). Total N across all test cases ≤ 200000.
Case#: 1
Input:
12332
Output:
• 1 appears once → 0
Total = 0 + 3 + 1 = 4
Case#: 2
Input:
6
555555
Output:
Case#: 3
Input:
10 20 30 40
Output:
All elements are unique, so the first and last index are same → all differences = 0 → 0.
Easy
1. Collecting Baskets
Problem Statement:
There is a long stretch of market stalls. Each stall has a certain number of fruit baskets. You start at
the first stall and can only move forward. At every step, you are allowed to pick up baskets from that
stall—but there’s a twist.
You can only collect baskets in increasing order of quantity (strictly). That means, if the last basket
you collected had X baskets, you can only pick a basket with more than X baskets next.
You want to know the maximum number of baskets you can collect following this rule.
Input Format:
• Second line contains N integers separated by space, where each integer A[i] denotes the
number of baskets at the i-th stall.
Output Format:
• A single integer — the maximum number of baskets you can collect in increasing order.
Sample Input 1:
132546
Sample Output 1:
Explanation:
Sample Input 2:
5
54321
Sample Output 2:
Explanation:
Only one basket can be collected at most, since all are in decreasing order.
Test Cases
Input 1
10
Output 1
Input 2
333
Output 2
Input 3
123456
Output 3
Input 4
5
77777
Output 4
Input 5
10 22 9 33 21 50 41 60
Output 5
Input 6
132435
Output 6
Input 7
10
100 90 80 70 60 50 40 30 20 10
Output 7
Input 8
2 4 6 8 10 12 14
Output 8
7
Code
def max_baskets(arr):
tails = []
if pos == len(tails):
tails.append(basket)
else:
tails[pos] = basket
return len(tails)
# Read input
n = int(input())
# Print output
print(max_baskets(arr))
2. Ticket Counter Time
Problem Statement:
There’s a single ticket counter and a line of people waiting. Each person needs a specific amount of
time to be served, which is represented by an array T.
The counter serves people in order, but here's the rule: the counter works in rounds. In each round,
the person at the front gets served for 1 time unit, then goes to the back of the queue if their
remaining time is more than 0.
You are given the time required for each person, and you are asked to calculate how many time
units it will take before the K-th person (0-indexed) in the original queue completes their service.
Input Format:
• First line contains two integers N (number of people) and K (index of target person).
• Second line contains N space-separated integers, where T[i] is the total time required for the
i-th person.
Output Format:
• A single integer — total time taken until the K-th person completes service.
Sample Input 1:
42
1234
Sample Output 1:
Explanation:
Sample Input 2:
50
51111
Sample Output 2:
Test Cases
Input 1
10
Output 1
Input 2
32
111
Output 2
Input 3
30
333
Output 3
Input 4
54
11115
Output 4
Input 5
62
331333
Output 5
Input 6
52
22222
Output 6
Input 7
52
10 2 3 1 1
Output 7
10
Input 8
43
1115
Output 8
Code
total_time = 0
while queue:
time_left -= 1
total_time += 1
if time_left == 0:
if idx == k:
return total_time
else:
queue.append((idx, time_left))
# Read input
n, k = map(int, input().split())
# Output result
print(ticket_counter_time(n, k, times))
3. Repeating Pairs
Problem Statement:
You are given a string S. Your task is to count how many distinct pairs of characters occur more than
once as consecutive characters in the string.
A "pair" means two characters next to each other. Pairs are considered the same if they have the
same characters in the same order (e.g., ab and ab are the same, ab and ba are different).
Input Format:
• Print a single integer — the number of distinct character pairs that appear more than once
as consecutive characters.
Sample Input 1:
ababcabc
Sample Output 1:
Explanation:
Consecutive pairs:
ab occurs 3 times
bc occurs 2 times
Sample Input 2:
aaaa
Sample Output 2:
Test Cases
Input 1
abcdef
Output 1
Input 2
a
Output 2
Input 3
abababa
Output 3
Input 4
abcabcabc
Output 4
Input 5
aaaaaa
Output 5
Input 6
abcdefg
Output 6
Input 7
abababab
Output 7
2
Input 8
Output 8
Code
def count_repeating_pairs(s):
pair_count = defaultdict(int)
pair_count[pair] += 1
# Read input
s = input().strip()
# Output result
print(count_repeating_pairs(s))
4. Most Frequent Character After Cleanup
Problem Statement:
• Digits (0-9)
If multiple characters have the same maximum frequency, return the one that comes first in
alphabetical order.
Input Format:
Output Format:
• A single lowercase letter — the most frequent alphabetic character (after cleanup).
Sample Input 1:
Sample Output 1:
Explanation:
Cleaned string: helloworld → Frequencies: h:1, e:1, l:3, o:2, w:1, r:1, d:1
Most frequent: l
Sample Input 2:
A@aaBBccC1234#
Sample Output 2:
Test Cases
Input 1
aaBBccC
Output 1
Input 2
aaBBccCaa
Output 2
Input 3
AAAAaaaaAAAaaa!!!@@@
Output 3
Input 4
xxYYzz!!
Output 4
x
Input 5
QWERTYQWERTY
Output 5
Input 6
!!!@@@###bbb%%%^^^
Output 6
Input 7
aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1234567890!@#$
Output 7
Input 8
Output 8
Code
def most_frequent_letter(s):
freq = defaultdict(int)
for char in s:
char = char.lower()
freq[char] += 1
if not freq:
# Find the character with highest frequency, break ties by alphabetical order
max_freq = max(freq.values())
print(result)
# Read input
s = input().strip()
most_frequent_letter(s)
5. Lonely Light
Problem Statement:
In a row of street lights, only one light is faulty — it flickers only when it receives power an odd
number of times.
You are given an array of integers, where each integer represents the ID of a street light that
received power. Every light gets powered an even number of times — except for one faulty light that
was powered an odd number of times.
• Second line contains N space-separated integers representing the light IDs that received
power.
Output Format:
Sample Input 1:
12321
Sample Output 1:
Explanation:
Sample Input 2:
5754794
Sample Output 2:
Test Cases
Input 1
42
Output 1
42
Input 2
4565477
Output 2
Input 3
10 20 10
Output 3
20
Input 4
838632255
Output 4
Input 5
11
9 10 10 12 13 9 13 15 15 12 11
Output 5
11
Input 6
7
11 12 13 11 12 13 14
Output 6
14
Input 7
56765
Output 7
Input 8
Output 8
2000
Code
def find_faulty_light(arr):
result = 0
return result
# Read input
n = int(input())
print(find_faulty_light(arr))
Problem Statement:
You are given an array of integers. Your task is to find all unique pairs of integers in the array whose
sum is equal to a given target value.
Input Format:
• The first line contains an integer n (1 ≤ n ≤ 1000), the number of elements in the array.
• The second line contains n space-separated integers, representing the elements of the array.
• The third line contains an integer target, representing the sum you need to find pairs for.
Output Format:
• Output all unique pairs of integers whose sum equals the given target.
• Each pair should be printed on a new line, with the two integers separated by a space.
Sample Input 1:
142335
Sample Output 1:
15
24
33
Sample Input 2:
5
10 20 30 40 50
100
Sample Output 2:
No pairs found
Test Cases
Input 1
10
Output 1
No pairs found
Input 2
2222
Output 2
22
Input 3
31456279
10
Output 3
19
37
46
Input 4
1234
10
Output 4
No pairs found
Input 5
513724
Output 5
17
35
Input 6
-1 -2 3 4 5
Output 6
-2 5
-1 4
Input 7
6
333333
Output 7
33
Input 8
10
Output 8
No pairs found
Code
if complement in seen:
result.add(tuple(sorted((num, complement))))
seen.add(num)
if result:
else:
# Reading input
find_pairs(arr, target)
Problem Statement:
Given a non-negative integer n, your task is to count the number of set bits (1s) in its binary
representation.
Input Format:
Output Format:
Sample Input 1:
5
Sample Output 1:
Explanation:
Sample Input 2:
15
Sample Output 2:
Explanation:
Test Cases
Input 1
Output 1
Input 2
64
Output 2
Input 3
255
Output 3
8
Input 4
254
Output 4
Input 5
164
Output 5
Input 6
128
Output 6
Input 7
42
Output 7
Input 8
1024
Output 8
1
Code
def count_set_bits(n):
count = 0
while n:
count += 1
print(count)
# Input parsing
n = int(input())
count_set_bits(n)
Problem Statement:
A number is considered digit-power-weighted if the sum of its digits raised to their position from left
to right, multiplied by their position, results in a unique score.
Given a positive integer n, calculate its weighted digit power sum using the formula:
Input Format:
Output Format:
321
Sample Output 1:
14
Explanation:
Digits: 3 2 1
• 3^1 * 1 = 3
• 2^2 * 2 = 4 * 2 = 8
• 1^3 * 3 = 1 * 3 = 3
Total = 3 + 8 + 3 = 14
Sample Input 2:
245
Sample Output 2:
409
Explanation:
• 2^1 × 1 = 2
• 4^2 × 2 = 16 × 2 = 32
Test Cases
Input 1
Output 1
7
Input 2
111
Output 2
Input 3
Output 3
Input 4
222
Output 4
34
Input 5
123
Output 5
90
Input 6
321
Output 6
14
Input 7
406
Output 7
652
Input 8
105
Output 8
376
Code
def weighted_digit_power_sum(n):
s = str(n)
total = 0
for i, ch in enumerate(s):
digit = int(ch)
power = digit ** (i + 1)
total += power * (i + 1)
print(total)
# Read input
n = int(input())
weighted_digit_power_sum(n)
Problem Statement:
Chef Rahul has recently taken a pledge to improve his health. Every morning, he drinks different fruit
smoothies lined up in a long queue at his smoothie bar. Each smoothie has a certain energy value,
which can be positive (if it boosts his energy) or negative (if it's a detox smoothie that lowers it).
Chef wants to figure out which k-day stretch of smoothies gives him the maximum total energy. He
can only pick a consecutive sequence of k smoothies.
You must help Chef find the maximum energy he can gain in any stretch of k consecutive days.
Input Format:
• Second line: n space-separated integers representing the energy values of the smoothies.
Output Format:
A single integer – the maximum total energy Chef can gain from any k consecutive smoothies.
Sample Input 1:
66
123456
Sample Output 1:
21
Sample Input 2:
52
-1 -2 -3 -4 -5
Sample Output 2:
-3
Test Cases
Input 1
11
5
Output 1
Input 2
53
12345
Output 2
12
Input 3
62
-1 -2 -3 -4 -5 -6
Output 3
-3
Input 4
74
3 -1 2 -5 4 6 -2
Output 4
Input 5
83
1 -1 2 -2 3 -3 4 -4
Output 5
4
Input 6
63
10 9 8 -1 -2 -3
Output 6
27
Input 7
62
-1 -2 -3 4 5 6
Output 7
11
Input 8
95
222222222
Output 8
10
Code
window_sum = sum(energy[:k])
max_sum = window_sum
return max_sum
# Read input
n, k = map(int, input().split())
print(max_energy_window(n, k, energy))
Problem Statement:
An ancient locker in a treasure vault opens only when you enter a "Lucky Code". A number is
considered lucky if the sum of its digits is a multiple of 4.
You're given a number N. Your task is to find the smallest integer greater than or equal to N which is
a lucky code.
Input Format:
Output Format:
Sample Input 1:
100
Sample Output 1:
103
Explanation:
101 → 1 + 0 + 1 = 2 → No
102 → 1 + 0 + 2 = 3 → No
103 → 1 + 0 + 3 = 4 → Correct
Sample Input 2:
1234
Sample Output 2:
1236
Test Cases
Input 1
Output 1
Input 2
16
Output 2
17
Input 3
9999
Output 3
9999
Input 4
256
Output 4
259
Input 5
1006
Output 5
1007
Input 6
2017
Output 6
2019
Input 7
10
Output 7
13
Input 8
45
Output 8
48
Code
def is_lucky(n):
def find_lucky_code(n):
return n
# Read input
n = int(input())
print(find_lucky_code(n))
Problem Statement:
In a small village by the river, the villagers are crossing a stream using rocks. The rocks are placed at
varying distances from each other along the riverbank. A young boy wants to cross the river, but he
is only allowed to jump between rocks that are at a specific distance apart. You are tasked with
helping the boy identify all the pairs of rocks where the difference between their positions equals a
given distance.
Input Format:
• The first line contains an integer n (1 ≤ n ≤ 1000), the number of rocks placed along the river.
• The second line contains n integers rocks[0], rocks[1], ..., rocks[n-1] (1 ≤ rocks[i] ≤ 10^6),
representing the positions of the rocks in sorted order.
• The third line contains an integer target_distance (1 ≤ target_distance ≤ 10^6), the distance
between the rocks the boy can jump.
Output Format:
• For each pair of rocks whose difference in positions equals the target_distance, print the
pair on a new line as (rock1, rock2).
Sample Input 1:
6
1 3 5 7 9 11
Sample Output 1:
(1, 3)
(3, 5)
(5, 7)
(7, 9)
(9, 11)
Sample Input 2:
2 4 6 8 10
Sample Output 2:
No pairs found
Test Cases
Input 1
2 4 6 8 10
Output 1
No pairs found
Input 2
1357
4
Output 2
(1, 5)
(3, 7)
Input 3
1 3 5 7 9 11
Output 3
(1, 3)
(3, 5)
(5, 7)
(7, 9)
(9, 11)
Input 4
1234567
Output 4
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
(6, 7)
Input 5
7
5 1 10 8 6 4 3
Output 5
No pairs found
Input 6
10 15 20 25 30
Output 6
(10, 15)
(15, 20)
(20, 25)
(25, 30)
Input 7
123456
Output 7
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
Input 8
1
100
Output 8
No pairs found
Code
left = 0
right = 1
pairs = []
if current_diff == target_distance:
pairs.append((rocks[left], rocks[right]))
left += 1
right = left + 1 # Reset the right pointer to one step ahead of the left
right += 1
else:
left += 1
if left == right:
right += 1
if not pairs:
print("No pairs found")
else:
print(f"({pair[0]}, {pair[1]})")
# Example usage
if __name__ == "__main__":
# Sample Input 1
find_pairs_with_distance(rocks, target_distance)
Problem Statement:
Sara is writing her college essay in a simple text editor that only supports typing lowercase alphabets
and undoing the last letter using the backspace key (represented by #). She types a sequence of
characters, and for every #, the last typed character (if any) gets removed.
Can you help her figure out the final text after all typing and backspaces?
Input Format:
• A single line string s (1 ≤ |s| ≤ 10^5), consisting of lowercase letters and the # character.
Output Format:
• A single line containing the final string after processing all characters.
Sample Input 1:
abc#d##
Sample Output 1:
Sample Input 2:
a#bc##d
Sample Output 2:
Test Cases
Input 1
##abc
Output 1
abc
Input 2
hello
Output 2
hello
Input 3
abc###xyz
Output 3
xyz
Input 4
helloworld
Output 4
helloworld
Input 5
a#b#c#d#e
Output 5
Input 6
abc##de#
Output 6
Ad
Input 7
a#bc#d#efg#h#
Output 7
bef
Input 8
a#b#c#d#e#f#z
Output 8
Code
def process_typing(s):
stack = []
for ch in s:
if ch == '#':
if stack:
stack.pop()
else:
stack.append(ch)
return ''.join(stack)
# Example usage:
if __name__ == "__main__":
s = input().strip()
print(process_typing(s))
Problem Statement:
A warehouse robot is stacking boxes represented by opening [ and closing ] brackets. It follows a
sequence of commands, where:
Your job is to determine whether the robot has stacked and unstacked the boxes correctly. That is,
every opening [ must have a corresponding closing ], and the order must be valid.
Input Format:
Output Format:
Sample Input 1:
[[]]
Sample Output 1:
Balanced
Sample Input 2:
][][
Sample Output 2:
Unbalanced
Test Cases
Input 1
[]
Output 1
Balanced
Input 2
[[[]]]
Output 2
Balanced
Input 3
][
Output 3
Unbalanced
Input 4
[[[]]
Output 4
Unbalanced
Input 5
[]][[]
Output 5
Unbalanced
Input 6
[[[[[]]]]]
Output 6
Balanced
Input 7
[][[[[]]]]
Output 7
Balanced
Input 8
]]]]
Output 8
Unbalanced
Code
def is_balanced_boxes(s):
stack = []
for ch in s:
if ch == '[':
stack.append(ch)
elif ch == ']':
if not stack:
return "Unbalanced"
stack.pop()
# Example usage
if __name__ == "__main__":
s = input().strip()
print(is_balanced_boxes(s))
Medium
Problem Statement:
In the ancient kingdom of Chronosia, there exists a legendary thief named Kael who can steal time
from time crystals. Each time crystal has a time value and a steal time (how long it takes to steal
from it). Kael has T minutes before the royal guards catch him. His goal is to maximize the amount of
time he can steal from the available crystals before he gets caught.
Each crystal can only be stolen once and stealing must be completed fully to obtain the time value.
Kael decides to steal from the most "efficient" crystals first, where efficiency is defined as the
highest time value per unit of steal time. Help Kael make the optimal choice.
Input Format:
• The next N lines each contain two integers vi and ti — value of time (vi) and time to steal (ti)
for each crystal.
Output Format:
• Print a single integer — the maximum total value of time Kael can steal before getting
caught.
Sample Input 1:
10
60 2
100 4
120 6
30 1
Sample Output 1:
190
Sample Input 2:
50 3
70 4
30 2
Sample Output 2:
70
Test Cases
Input 1
100
Output 1
Input 2
100 1
200 2
300 3
Output 2
Input 3
1000000000
10000 10000
10000 10000
10000 10000
Output 3
30000
Input 4
15
50 5
60 4
70 6
80 3
30 2
Output 4
240
Input 5
10
100 5
200 10
150 7
50 2
Output 5
200
Input 6
10 5
100 4
51
Output 6
100
Input 7
100 2
200 3
300 4
Output 7
Input 8
100 2
150 2
120 2
Output 8
370
Code
total_value = 0
remaining_time = t
for value, steal_time in crystals:
total_value += value
remaining_time -= steal_time
else:
continue
return total_value
# Input reading
if __name__ == "__main__":
n = int(input())
t = int(input())
print(max_stolen_time_value(n, t, crystals))
Problem Statement:
There’s a single ticket counter and a line of people waiting. Each person needs a specific amount of
time to be served, which is represented by an array T.
The counter serves people in order, but here's the rule: the counter works in rounds. In each round,
the person at the front gets served for 1 time unit, then goes to the back of the queue if their
remaining time is more than 0.
You are given the time required for each person, and you are asked to calculate how many time
units it will take before the K-th person (0-indexed) in the original queue completes their service.
Input Format:
• First line contains two integers N (number of people) and K (index of target person).
• Second line contains N space-separated integers, where T[i] is the total time required for the
i-th person.
Output Format:
• A single integer — total time taken until the K-th person completes service.
Sample Input 1:
42
1234
Sample Output 1:
Explanation:
Sample Input 2:
50
51111
Sample Output 2:
9
Test Cases
Input 1
10
Output 1
Input 2
32
111
Output 2
Input 3
30
333
Output 3
Input 4
54
11115
Output 4
Input 5
62
331333
Output 5
Input 6
52
22222
Output 6
Input 7
52
10 2 3 1 1
Output 7
10
Input 8
43
1115
Output 8
8
Code
total_value = 0
remaining_time = t
total_value += value
remaining_time -= steal_time
else:
continue
return total_value
# Input reading
if __name__ == "__main__":
n = int(input())
t = int(input())
print(max_stolen_time_value(n, t, crystals))
16. Festival of Lanterns
Problem Statement:
In the kingdom of Lumora, every year a lantern festival is held where participants light floating
lanterns along a river. Each lantern must be lit and launched at a specific time interval, and each one
brings a certain amount of joy to the crowd.
The Grand Organizer can only allow one lantern to be launched at any given second (due to narrow
river constraints). You're given N lanterns, each with:
• A joy value.
Your task is to select the subset of lanterns to maximize total joy, ensuring no two lanterns are
launched at the same time, and each is launched on or before its deadline.
This is a classic Greedy + Priority Queue problem (variant of Job Scheduling with Deadlines).
Input Format:
Output Format:
Sample Input 1:
2 100
1 50
2 200
1 20
3 300
Sample Output 1:
600
Explanation:
• Choose lanterns with highest joy but that can meet their deadline:
Sample Input 2:
1 40
2 50
2 30
1 70
Sample Output 2:
120
Test Cases
Input 1
1 9999
Output 1
9999
Input 2
1 10
1 20
15
1 100
Output 2
100
Input 3
1 100
2 200
3 300
Output 3
600
Input 4
15
2 20
2 30
2 25
3 50
3 90
Output 4
170
Input 5
1 10
2 10
3 10
4 10
Output 5
40
Input 6
5 100
6 200
7 300
Output 6
600
Input 7
2 10
2 20
2 30
2 40
2 50
Output 7
90
Input 8
1 10000
1 9000
1 8000
1 7000
1 6000
Output 8
10000
Code
import heapq
lanterns.sort(key=lambda x: x[0])
min_heap = []
heapq.heappush(min_heap, joy)
# If we have more lanterns than we can schedule by this deadline, remove the least joyful one
heapq.heappop(min_heap)
return sum(min_heap)
# Input Reading
if __name__ == "__main__":
n = int(input())
print(max_total_joy(n, lanterns))
Problem Statement:
A wealthy merchant is heading to the annual Golden Dunes Market, carrying items of different
values and weights. His caravan can only carry a maximum weight W due to desert travel
constraints.
He wants to maximize his profit by selecting the subset of items that can be carried without
exceeding the total weight limit.
He can take fractions of an item if needed — i.e., this is the Fractional Knapsack Problem, solved
greedily by value per unit weight.
Input Format:
o N: number of items
Output Format:
• A single floating-point number — the maximum total value the merchant can carry.
Sample Input 1:
3 50
60 10
100 20
120 30
Sample Output 1:
240.00
Explanation:
Sort by value/weight:
• 60/10 = 6.0
• 100/20 = 5.0
• 120/30 = 4.0
Pick:
• 60 (10)
• 100 (20)
Sample Input 2:
11
100 2
Sample Output 2:
50.00
Test Cases
Input 1
2 30
100 10
120 30
Output 1
220.00
Input 2
3 60
60 10
100 20
120 30
Output 2
280.00
Input 3
3 10
60 10
100 20
120 30
Output 3
60.00
Input 4
25
100 10
120 30
Output 4
50.00
Input 5
4 10
10 1
20 2
30 3
40 4
Output 5
100.00
Input 6
3 50
500 50
400 40
300 30
Output 6
500.00
Input 7
12
100 4
Output 7
50.00
Input 8
5 100
10 10
20 20
30 30
40 40
50 50
Output 8
100.00
Code
total_value = 0.0
if w == 0:
break
if weight <= w:
total_value += value
w -= weight
else:
w=0
return round(total_value, 2)
# Driver code
if __name__ == "__main__":
n, w = map(int, input().split())
print(f"{max_value(n, w, items):.2f}")
A music event organizer wants to schedule bands for a music marathon. Each band has a
performance start time, end time, and a popularity score (which is equal to the number of tickets
they help sell).
Due to logistical constraints, no two bands can perform at overlapping times. The goal is to select a
subset of non-overlapping bands to maximize total popularity.
Input Format:
Output Format:
Sample Input 1:
1 3 50
2 5 60
4 6 70
6 7 30
Sample Output 1:
150
Explanation:
Total = 50 + 70 + 30 = 150
Sample Input 2:
1 3 50
2 5 60
4 6 70
6 7 30
Sample Output 2:
150
Test Cases
Input 1
1 2 20
3 4 40
5 6 60
Output 1
120
Input 2
1 5 10
2 6 30
3 7 20
Output 2
30
Input 3
1 3 50
3 5 50
5 7 50
2 8 200
Output 3
200
Input 4
1 10 100
2 3 20
4 5 30
Output 4
100
Input 5
1 3 20
3 6 30
6 9 40
9 12 50
12 15 60
Output 5
200
Input 6
1 5 100
10 15 150
20 25 200
30 35 250
Output 6
700
Input 7
1 10 100
1 2 30
2 3 30
3 4 30
4 5 30
Output 7
120
Input 8
1 3 50
3 5 60
5 7 70
7 9 80
9 11 90
11 13 100
Output 8
450
Code
import bisect
def max_popularity(bands):
dp = [0] * (len(bands) + 1)
return dp[-1]
# Driver
if __name__ == "__main__":
n = int(input())
print(max_popularity(bands))
You are given N meetings, each with a start time and end time. All meetings must be scheduled in
conference rooms, and no two overlapping meetings can be in the same room.
Your task is to find the minimum number of rooms required to accommodate all meetings without
overlap.
Input Format:
Output Format:
Sample Input 1:
0 30
5 10
15 20
25 35
Sample Output 1:
Sample Input 2:
12
34
56
Sample Output 2:
Test Cases
Input 1
1 10
1 10
1 10
1 10
Output 1
Input 2
14
25
36
67
78
Output 2
Input 3
12
23
34
45
Output 3
Input 4
1 10
2 10
3 10
Output 4
Input 5
1 10
23
34
45
56
Output 5
Input 6
15
26
57
68
79
8 10
Output 6
Input 7
15
25
35
45
Output 7
Input 8
10 20
30 40
50 60
15 25
35 45
55 65
Output 8
2
Code
def min_rooms(meetings):
start_ptr = end_ptr = 0
current_rooms = max_rooms = 0
current_rooms += 1
start_ptr += 1
else:
current_rooms -= 1
end_ptr += 1
return max_rooms
# Driver
if __name__ == "__main__":
n = int(input())
print(min_rooms(meetings))
20. The Coupon Collector
Problem Statement:
You are at a store that offers coupons on N items. For each item, you are given:
But… you only have K coupons, and each coupon can be applied to only one item.
Your task is to minimize the total cost of buying all items by using at most K coupons, where each
coupon gives the full discount on one item.
Input Format:
Output Format:
Sample Input 1:
52
100 20
200 50
150 30
120 60
80 10
Sample Output 1:
540
Explanation:
Use coupons on items with the maximum discount: 60 and 50
Sample Input 2:
30
100 50
200 100
150 75
Sample Output 2:
450
Test Cases
Input 1
33
100 10
100 20
100 30
Output 1
240
Input 2
25
300 100
400 150
Output 2
450
Input 3
42
100 0
200 0
300 0
400 0
Output 3
1000
Input 4
32
100 100
200 200
300 300
Output 4
100
Input 5
10
999 888
Output 5
999
Input 6
128
Output 6
Input 7
63
100 5
100 10
100 15
100 20
100 25
100 30
Output 7
525
Input 8
63
100 5
100 10
100 15
100 20
100 25
100 20
Output 8
535
Code
def min_total_cost(n, k, items):
total_discount = sum(discounts[:k])
# Driver
if __name__ == "__main__":
n, k = map(int, input().split())
print(min_total_cost(n, k, items))
Problem Statement:
• penalty: the penalty incurred if you miss the deadline (if not done at all or submitted late).
Each problem takes exactly 1 unit of time to solve, and you can only solve one problem per unit
time.
Your goal is to maximize the total penalty avoided, i.e., pick problems in such a way that you solve
the highest-penalty problems within their deadlines.
Input Format:
• Next N lines: Two integers deadline and penalty for each problem
Output Format:
Sample Input 1:
2 100
1 19
2 27
1 25
3 15
Sample Output 1:
142
Sample Input 2:
1 50
1 40
1 30
1 20
Sample Output 2:
50
Test Cases
Input 1
1 10
2 20
3 30
Output 1
60
Input 2
1 10
1 20
1 30
1 40
Output 2
40
Input 3
15
2 50
3 15
2 20
3 25
Output 3
95
Input 4
2 10
2 20
2 30
2 40
2 50
2 60
Output 4
110
Input 5
10 100
9 90
8 80
Output 5
270
Input 6
1 100
2 10
1 30
3 20
2 90
3 80
Output 6
270
Input 7
4
1 50
2 50
3 50
2 50
Output 7
150
Input 8
10000 1000000
9000 900000
8000 800000
7000 700000
6000 600000
Output 8
4000000
Code
total = 0
slots[t] = True
total += penalty
break
return total
# Driver
if __name__ == "__main__":
n = int(input())
print(max_penalty_avoided(n, tasks))
Problem Statement:
You are given N events, each with a start time and an end time. Your task is to determine the
minimum number of rooms required to schedule all events without any overlap in a single room.
Each room can hold only one event at a time. Events are considered overlapping if one starts before
another ends (i.e., inclusive).
Input Format:
• Next N lines: Two integers start and end for each event (inclusive)
Output Format:
Sample Input 1:
5
0 30
5 10
15 20
35 45
25 40
Sample Output 1:
Sample Input 2:
05
6 10
11 15
16 20
Sample Output 2:
Test Cases
Input 1
1 10
29
38
47
Output 1
4
Input 2
15
26
59
7 10
10 13
12 15
Output 2
Input 3
1 100
23
45
67
89
Output 3
Input 4
01
Output 4
1
Input 5
01
23
45
67
Output 5
Input 6
11
11
11
Output 6
Input 7
12
23
34
Output 7
Input 8
8
0 10
10 20
20 30
5 15
15 25
25 35
30 40
35 45
Output 8
Code
import heapq
def min_rooms(events):
min_heap = []
heapq.heappop(min_heap)
heapq.heappush(min_heap, end)
return len(min_heap)
# Driver
if __name__ == "__main__":
n = int(input())
print(min_rooms(events))
Problem Statement:
You are given N tasks. Each task takes a certain amount of time to complete and has a deadline. You
can execute the tasks one after another, starting from time 0. Your goal is to complete the maximum
number of tasks such that each task is finished on or before its deadline.
You can only work on one task at a time, and you must choose tasks wisely (greedy!) so you can
finish as many as possible.
Input Format:
• Next N lines: Two integers duration and deadline for each task
Output Format:
• A single integer – maximum number of tasks that can be completed on or before their
deadlines
Sample Input 1:
39
28
19
2 15
5 12
Sample Output 1:
5
Sample Input 2:
25
13
26
Sample Output 2:
Test Cases
Input 1
24
35
46
10 7
Output 1
Input 2
11
23
36
4 10
Output 2
4
Input 3
15
16
17
18
19
Output 3
Input 4
32
43
54
Output 4
Input 5
6 12
13
24
15
36
Output 5
Input 6
3 10
2 10
1 10
4 10
Output 6
Input 7
5 10
38
25
13
6 12
4 11
Output 7
Input 8
10 100
20 100
30 100
40 100
15 100
5 100
25 100
Output 8
Code
import heapq
def max_tasks(tasks):
total_time = 0
durations = []
total_time += duration
heapq.heappush(durations, -duration)
return len(durations)
# Driver
if __name__ == "__main__":
n = int(input())
tasks = [tuple(map(int, input().split())) for _ in range(n)]
print(max_tasks(tasks))
Problem Statement:
You're managing a charging station with K charging ports. There are N electric cars that want to
charge. Each car arrives at a specific time and needs a specific duration to fully charge.
Your goal is to maximize the number of cars that can be charged, assuming:
Use a greedy algorithm to schedule cars so that the maximum number can finish charging.
Input Format:
• Next N lines: Two integers arrival_time and duration for each car
Output Format:
Sample Input 1:
52
14
23
32
10 1
52
Sample Output 1:
Sample Input 2:
31
12
32
52
Sample Output 2:
Test Cases
Input 1
42
12
32
52
72
Output 1
Input 2
41
15
25
35
45
Output 2
Input 3
33
15
15
15
Output 3
Input 4
52
14
23
32
10 1
52
Output 4
Input 5
42
12
22
10 1
11 1
Output 5
4
Input 6
62
13
22
32
42
52
62
Output 6
Input 7
10 2
12
12
12
12
12
32
32
32
52
52
Output 7
6
Input 8
62
11
21
31
41
51
61
Output 8
Code
import heapq
count = 0
heapq.heappop(ports)
if len(ports) < k:
count += 1
return count
# Driver
if __name__ == "__main__":
n, k = map(int, input().split())
print(max_charged_cars(cars, k))
Problem Statement:
You are given an amount N and a list of M coin denominations. Your task is to find the minimum
number of coins needed to make up that amount using the available denominations. You can use
each coin type an unlimited number of times.
Input Format:
Output Format:
Sample Input 1:
49 6
1 2 5 10 20 50
Sample Output 1:
Explanation:
• 5 = 45
• 2 = 47
• 1 + 1 = 49
• Total: 5 coins
Sample Input 2:
49 6
1 2 5 10 20 50
Sample Output 2:
Test Cases
Input 1
100 4
1 5 10 100
Output 1
Input 2
37 5
1 5 10 20 25
Output 2
Input 3
71
Output 3
Input 4
18 3
2 5 10
Output 4
Input 5
18 4
1 2 5 10
Output 5
Input 6
999 6
1 2 5 10 20 100
Output 6
17
Input 7
15 6
1 1 5 5 10 10
Output 7
2
Input 8
72
24
Output 8
Code
coins.sort(reverse=True)
count = 0
n -= coin
count += 1
return count
# Driver
if __name__ == "__main__":
n, m = map(int, input().split())
print(min_coins_to_pay(n, coins))
Problem Statement:
You are given N tasks. Each task has a deadline and a reward. You can only do one task per day, and
each task takes exactly one day. If a task is not completed on or before its deadline, you miss the
reward.
Your goal is to maximize the total reward by selecting and scheduling tasks greedily.
Input Format:
• Next N lines: Two integers D and R per line (deadline and reward)
Output Format:
Sample Input 1:
2 50
1 10
2 20
1 30
3 40
Sample Output 1:
120
Sample Input 2:
1 10
1 20
1 30
1 40
Sample Output 2:
40
Test Cases
Input 1
1 10
2 20
3 30
4 40
Output 1
100
Input 2
2 50
2 60
2 70
2 40
2 30
2 20
Output 2
130
Input 3
3 15
2 10
1 20
Output 3
45
Input 4
1 10
2 10
3 10
2 10
1 10
Output 4
30
Input 5
1 100
2 10
2 10
3 10
3 10
Output 5
120
Input 6
1 1000
Output 6
1000
Input 7
10 100
11 200
12 300
13 400
Output 7
1000
Input 8
1 10
1 20
1 30
1 40
1 50
1 60
Output 8
60
Code
if parent[x] != x:
def max_total_reward(tasks):
total_reward = 0
for d, r in tasks:
available_day = find(parent, d)
if available_day > 0:
total_reward += r
return total_reward
# Driver
if __name__ == "__main__":
n = int(input())
print(max_total_reward(tasks))
Hard
The Infinite Forest is a mystical place represented as a 2D grid. You start at the top-left cell (0, 0) and
want to reach the bottom-right cell (N-1, M-1). Each cell contains a magical cost, which you must pay
to enter that cell.
There are some rare teleport tiles in the grid (identified by a value of -1). From a teleport tile, you
can jump to any other teleport tile for free, without paying the cost of the destination teleport tile
(but you must still have passed into the teleport tile you're jumping from).
Your goal is to find the minimum magical cost to travel from the start to the destination, considering
both normal and teleportation moves.
Input Format:
• The first line contains two integers N and M — the dimensions of the forest.
Output Format:
Print a single integer — the minimum cost to reach (N-1, M-1) from (0, 0).
Sample Input 1:
44
1 3 -1 4
2859
4 -1 3 1
6725
Sample Output 1:
13
Sample Input 2:
33
1 -1 3
2 4 -1
111
Sample Output 2:
Test Cases
Input 1
33
123
456
789
Output 1
21
Input 2
33
1 -1 3
2 100 -1
111
Output 2
2
Input 3
44
1 2 -1 9
8999
-1 9 9 9
9991
Output 3
31
Input 4
33
-1 3 1
2 -1 2
341
Output 4
Input 5
33
123
456
7 8 -1
Output 5
12
Input 6
33
123
4 -1 6
789
Output 6
18
Input 7
44
1 -1 -1 1
1 100 100 1
1 100 100 1
1111
Output 7
Input 8
44
1 99 99 99
-1 99 99 99
99 99 99 -1
99 99 99 1
Output 8
2
Code
import sys
import heapq
INF = float('inf')
teleports = []
for i in range(n):
for j in range(m):
if grid[i][j] == -1:
teleports.append((i, j))
visited_teleport = False
while heap:
cost, x, y = heapq.heappop(heap)
continue
nx, ny = x + dx, y + dy
dp[tx][ty] = cost
return dp[n-1][m-1]
# Reading input
n, m = map(int, input().split())
print(min_magic_cost(grid, n, m))
You are given an array of integers A of length N. A subsequence S of A is called a "Jumpy Alternating
Subsequence" if:
3. The absolute difference between any two consecutive elements must be at least K.
Input Format:
• First line: Two integers N and K — the length of the array and the minimum absolute jump
size.
Output Format:
Sample Input 1:
62
174925
Sample Output 1:
Explanation:
One such longest sequence is [1, 7, 4, 9, 2, 5] with diffs [+6, -3, +5, -7, +3].
Sample Input 2:
53
12345
Sample Output 2:
Test Cases
Input 1
62
174925
Output 1
Input 2
51
33333
Output 2
Input 3
5 10
12345
Output 3
Input 4
70
1 17 5 10 13 15 10
Output 4
Input 5
73
10 20 5 25 1 30 0
Output 5
Input 6
42
1114
Output 6
Input 7
54
10 5 1 -3 -10
Output 7
Input 8
10 1
1324354657
Output 8
10
Code
n = len(arr)
for j in range(i):
if abs(diff) >= k:
if diff > 0:
# Read input
n, k = map(int, input().split())
print(longest_jumpy_alternating_subsequence(arr, k))
29. Minimum Sum Subsequence with Non-Adjacent Elements
Problem Statement:
You're given an array of integers arr of length n. You need to select a subsequence such that:
1. No two adjacent elements in the original array can be picked (i.e., if you pick arr[i], you
cannot pick arr[i+1]).
Write a program to compute the minimum possible sum under these rules.
Input Format:
Output Format:
• A single integer: Minimum number of button presses required to type the message.
Sample Input 1:
3 2 5 10 7
Sample Output 1:
Sample Input 2:
1
Sample Output 2:
Test Cases
Input 1
10 2
Output 1
Input 2
-5 -10 -3 -1 -6 -9
Output 2
-20
Input 3
Output 3
Input 4
45154
Output 4
Input 5
777777
Output 5
Input 6
5 100
6 200
7 300
Output 6
600
Input 7
8 7 -100 6 9
Output 7
-92
Input 8
10 9 8 7 6 5
Output 8
9
Code
def min_non_adjacent_sum(arr):
n = len(arr)
if n == 1:
return arr[0]
dp = [0] * n
dp[0] = arr[0]
return dp[-1]
# Input
n = int(input())
print(min_non_adjacent_sum(arr))
Problem Statement:
You are given n pairs of integers. Each pair represents a directed link (a, b) such that a < b.
You can form a chain by choosing some pairs such that for each consecutive pair (a, b) and (c, d) in
the chain, b < c.
Your task is to select the maximum number of pairs you can chain together following this rule.
Input Format:
Output Format:
Sample Input 1:
5 24
15 25
27 40
50 60
Sample Output 1:
Sample Input 2:
12
23
34
45
56
Sample Output 2:
3
Test Cases
Input 1
12
23
34
45
56
Output 1
Input 2
1 10
23
34
Output 2
Input 3
01
Output 3
Input 4
2
15
26
Output 4
Input 5
12
23
45
67
89
10 11
Output 5
Input 6
5 10
14
7 11
13 20
68
21 25
Output 6
4
Input 7
Output 7
Input 8
-5 -3
-1 1
23
46
68
9 12
13 15
Output 8
Code
def max_chain_length(pairs):
pairs.sort(key=lambda x: x[1])
count = 0
current_end = float('-inf')
for a, b in pairs:
if a > current_end:
count += 1
current_end = b
return count
# Input
n = int(input())
print(max_chain_length(pairs))
Problem Statement:
Your task is to split the array into k non-empty continuous subarrays, such that the maximum sum
among these k subarrays is minimized.
Input Format:
Output Format:
A single integer — the minimum possible value of the largest subarray sum when the array is split
into k parts.
Sample Input 1:
52
7 2 5 10 8
Sample Output 1:
18
Sample Input 2:
42
1234
Sample Output 2:
Test Cases
Input 1
11
100
Output 1
100
Input 2
63
144132
Output 2
Input 3
64
1 4 4 1 3 22 8 200
Output 3
Input 4
10 5
1 1 1 1 1 1 1 1 1 10
Output 4
10
Input 5
1 3 20
3 6 30
6 9 40
9 12 50
12 15 60
Output 5
200
Input 6
73
2312431
Output 6
Input 7
55
12345
Output 7
Input 8
61
123456
Output 8
21
Code
count = 1
current_sum = 0
count += 1
current_sum = num
else:
current_sum += num
low = max(arr)
high = sum(arr)
result = high
while low <= high:
if can_split(arr, k, mid):
result = mid
high = mid - 1
else:
low = mid + 1
return result
# Input
n, k = map(int, input().split())
print(split_array_min_largest_sum(arr, k))
Problem Statement:
You are given a string s. Your task is to partition the string such that every substring of the partition
is a palindrome.
Return the minimum number of cuts needed to make all parts of the string palindromes.
Input Format:
Output Format:
aab
Sample Output 1:
Sample Input 2:
Sample Output 2:
Test Cases
Input 1
abc
Output 1
Input 2
abba
Output 2
Input 3
racecar
Output 3
0
Input 4
noonabbad
Output 4
Input 5
aaaaaa
Output 5
Input 6
abacdc
Output 6
Input 7
Banana
Output 7
Input 8
Civicracecar
Output 8
Code
def min_cut_palindrome(s):
n = len(s)
# Precompute palindromes
for i in range(n):
is_palindrome[i][i] = True
for i in range(n-1):
j = i + length - 1
dp = [0] * n
for i in range(n):
if is_palindrome[0][i]:
dp[i] = 0
else:
dp[i] = float('inf')
for j in range(i):
if is_palindrome[j+1][i]:
return dp[-1]
# Input
s = input().strip()
print(min_cut_palindrome(s))
Problem Statement:
Given an array of integers, you must find the length of the longest subsequence where the
differences between consecutive elements strictly alternate between positive and negative.
A subsequence is not necessarily contiguous. The first difference can be either positive or negative.
Input Format:
Output Format:
Sample Input 1:
174925
Sample Output 1:
Sample Input 2:
14725
Sample Output 2:
4
Test Cases
Input 1
10
Output 1
Input 2
111
Output 2
Input 3
1234
Output 3
Input 4
4321
Output 4
Input 5
7
70 55 13 2 99 2 80
Output 5
Input 6
33333333
Output 6
Input 7
10
10 22 9 33 49 50 31 60 4 70
Output 7
Input 8
13243
Output 8
Code
def longest_zigzag_subsequence(arr):
n = len(arr)
if n == 0:
return 0
up = [1] * n
down = [1] * n
for j in range(i):
# Input
n = int(input())
print(longest_zigzag_subsequence(arr))
Problem Statement:
You're given n intervals, each with a start time, end time, and a value. Your goal is to select a subset
of non-overlapping intervals such that the sum of their values is maximized.
Input Format:
• Next n lines: Each line contains three integers: start end value
Output Format:
Sample Input 1:
1 3 50
3 5 20
6 19 100
2 100 200
Sample Output 1:
200
Sample Input 2:
1 2 10
2 3 20
3 4 30
Sample Output 2:
60
Test Cases
Input 1
1 4 10
2 5 20
3 6 30
Output 1
30
Input 2
1 10 100
2 3 10
3 4 20
4 5 30
5 6 40
Output 2
100
Input 3
1 10 100
11 20 200
Output 3
300
Input 4
1 5 20
6 10 30
5 6 10
Output 4
60
Input 5
1 2 100
2 3 100
3 4 100
Output 5
300
Input 6
1 1000000000 5000
Output 6
5000
Input 7
1 3 10
2 4 20
3 5 30
4 6 40
Output 7
60
Input 8
121
232
343
454
565
Output 8
15
Code
import bisect
def max_value_non_overlapping(intervals):
intervals.sort(key=lambda x: x[1])
n = len(intervals)
dp = [0] * (n + 1)
return dp[n]
# Input
n = int(input())
print(max_value_non_overlapping(intervals))
Problem Statement:
You are given two integers L and R, and a value k. Count how many numbers between L and R
(inclusive) are beautiful.
Input Format:
Output Format:
A single integer — the count of beautiful numbers in the range [L, R].
Sample Input 1:
1 100 10
Sample Output 1:
Sample Input 2:
1 20 5
Sample Output 2:
3
Test Cases
Input 1
10 99 9
Output 1
10
Input 2
1 1000 10
Output 2
99
Input 3
100 200 15
Output 3
Input 4
123456 654321 7
Output 4
75845
Input 5
1 1000000 1
Output 5
1000000
Input 6
1 1000000 99
Output 6
Input 7
111
Output 7
Input 8
9999999999999999 10000000000000000 9
Output 8
Code
@lru_cache(None)
if pos == len(digits):
total = 0
for d in range(0, limit + 1):
total += dp(
pos + 1,
(sum_mod_k + d) % k,
return total
# Input
L, R, k = map(int, input().split())
print(solve(L, R, k))
Problem Statement:
You're given an array of n integers and an integer k. You need to partition the array into k subsets of
equal size. Each subset must contain unique elements only (no duplicates). The incompatibility of a
subset is the difference between its maximum and minimum elements.
Your goal is to minimize the sum of incompatibilities across all subsets. If it's not possible to partition
the array as required, return -1.
Input Format:
Sample Input 1:
84
12143356
Sample Output 1:
Sample Input 2:
63
123456
Sample Output 2:
Test Cases
Input 1
52
12345
Output 1
-1
Input 2
84
12143356
Output 2
5
Input 3
62
111222
Output 3
-1
Input 4
42
5577
Output 4
Input 5
72
1234567
Output 5
-1
Input 6
63
316245
Output 6
Input 7
42
8888
Output 7
-1
Input 8
84
10 20 30 40 50 60 70 80
Output 8
40
Code
import sys
n = len(nums)
size = n // k
if n % k != 0:
return -1
count = defaultdict(int)
return -1
all_masks = []
mask_cost = {}
seen = set()
subset = []
for i in combo:
if nums[i] in seen:
break
seen.add(nums[i])
subset.append(nums[i])
else:
mask = 0
for i in combo:
mask |= 1 << i
all_masks.append(mask)
dp = [sys.maxsize] * (1 << n)
dp[0] = 0
continue
# Input Reading
if __name__ == "__main__":
n, k = map(int, input().split())
print(min_incompatibility(nums, k))
Problem Statement:
You are given a string s of lowercase English letters. You want to partition s into k non-empty, non-
overlapping contiguous substrings such that each substring is a palindrome. You are allowed to
change characters in the string. Changing one character costs 1 unit.
Your goal is to partition the string into exactly k palindromic substrings with the minimum total cost
of character changes required.
Input Format:
• A single integer, the minimum cost to partition the string into exactly k palindromic
substrings.
Sample Input 1:
abc
Sample Output 1:
Sample Input 2:
aabbc
Sample Output 2:
Test Cases
Input 1
Output 1
Input 2
abc
Output 2
1
Input 3
aaaa
Output 3
Input 4
aaaaaa
Output 4
Input 5
abcdef
Output 5
Input 6
racecar
Output 6
Input 7
abcdef
Output 7
2
Input 8
abcdcba
Output 8
Code
cost = 0
while i < j:
if s[i] != s[j]:
cost += 1
i += 1
j -= 1
return cost
n = len(s)
for i in range(n):
cost[i][j] = min_change_to_palindrome(s, i, j)
return dp[n][k]
# Input Reading
if __name__ == "__main__":
s = input().strip()
k = int(input())
print(min_cost_partition(s, k))
Problem Statement:
Given a string s of lowercase English letters, you are allowed to select substrings such that:
• Each selected substring has all the same characters (e.g., "aaa" is valid, "aab" is not).
• For each selected substring, you gain a score equal to the square of its length.
Your task is to select a subset of such substrings (non-overlapping and non-adjacent) to maximize
the total score.
Input Format:
Sample Input 1:
aaabbaaa
Sample Output 1:
18
Sample Input 2:
ababa
Sample Output 2:
Test Cases
Input 1
aaaaa
Output 1
25
Input 2
aabbaabb
Output 2
Input 3
aabbaa
Output 3
8
Input 4
abcde
Output 4
Input 5
aaabbbcccaaaddd
Output 5
27
Input 6
aabaaabaaa
Output 6
22
Input 7
Output 7
Input 8
aaabbaaccdddeeffggghh
Output 8
31
Code
def max_non_adjacent_block_score(s):
n = len(s)
blocks = []
i=0
while i < n:
j=i
j += 1
blocks.append((s[i], j - i))
i=j
m = len(blocks)
dp = [0] * (m + 1)
if i >= 2:
else:
return dp[m]
# Input Reading
if __name__ == "__main__":
s = input().strip()
print(max_non_adjacent_block_score(s))
Problem Statement:
You are given a binary string s (consisting of only '0' and '1') and an integer k.
You are allowed to flip at most k characters in the string (i.e., change '0' to '1' or '1' to '0').
Your task is to determine the length of the longest balanced substring you can obtain after at most k
flips, where a balanced substring is defined as a substring with an equal number of 0s and 1s.
Input Format:
Output Format:
Sample Input 1:
110001
Sample Output 1:
Sample Input 2:
1111
Sample Output 2:
Test Cases
Input 1
1111
Output 1
Input 2
000111
Output 2
Input 3
00000
Output 3
Input 4
101010
Output 4
Input 5
101100110101
2
Output 5
10
Input 6
1 1000
Output 6
1000
Input 7
1000000001
Output 7
Input 8
111000
Output 8
Code
n = len(s)
max_len = 0
count = {0: 0, 1: 0}
left = 0
count[int(s[right])] += 1
count[int(s[left])] -= 1
left += 1
return max_len
# Input
if __name__ == "__main__":
s = input().strip()
k = int(input())
print(longest_balanced_after_k_flips(s, k))
Problem Statement:
You are given an array of integers arr of size n. You can jump from index i to any index j such that:
• j>i
Input Format:
Output Format:
Sample Input 1:
132468
Sample Output 1:
Sample Input 2:
54321
Sample Output 2:
-1
Test Cases
Input 1
1234
Output 1
1
Input 2
10
Output 2
Input 3
Output 3
Input 4
10 20 10 30 10 40 10 50
Output 4
Input 5
11112
Output 5
Input 6
10
5612345678
Output 6
Input 7
13579
Output 7
Input 8
121212
Output 8
Code
def min_jumps_strictly_increasing(arr):
n = len(arr)
if n == 1:
return 0
graph = defaultdict(list)
# Preprocess: Build graph of possible jumps
for i in range(n):
graph[i].append(j)
# BFS
visited = [False] * n
queue = deque()
visited[0] = True
while queue:
if not visited[neighbor]:
if neighbor == n - 1:
return jumps + 1
visited[neighbor] = True
return -1
# Driver Code
if __name__ == "__main__":
n = int(input())
print(min_jumps_strictly_increasing(arr))