This is the second part of the series on online assessments that I witnessed during the season of 2024. The first part can be found here.
- Zomato
- PACE Stock Broking
- HiLabs Technologies
- InMobi
- Dream 11
- Netradyne
- Microsoft
- Plutus Research
Zomato
Other Campuses Questions
-
You are given the edges that form a tree with the root as . A traversal of the tree is generated in the following manner:
- An empty queue is initialized and the node is pushed into it.
- While the queue is not empty, the front element is popped and all its children are pushed into the queue in any arbitary order.
- The popped element is added to the traversal.
You are given multiple traversals of the tree, and you need to find which of the traversals provided can be a valid BFS order traversal of the same.
Solution
We can use the provided traversal to order the nodes of the tree in the particular order. We can then generate the BFS traversal of the tree and compare it with the provided traversal.
Time Complexity:
-
You are given an string . You are also given two strings and which are both initially empty. You can perform either of the two operations in a turn:
- Append the first character of to the end of .
- Append the last character of to the end of .
You need to apply these operations such that all the end all the characters from are shifted to , and the generated string is the lexicographically smallest possible. Return the lexicographically smallest string that can be generated.
Solution
This question can be solved with the help of stack and using a greedy approach. In the stack, we try to maintain all the elements that we can processed till now (it acts like our string ). We greedily process the characters from to , always travelling to their rightmost occurence and trying to add them to the string . Before processing any character, we also check our stack to see it has some smaller character than the current one, and if it does, we pop it out and add it to the string .
Time Complexity: where is the length of the string .
-
You are given a string that has lowercase English characters. You are also given an integer . You need to generate a string of the given length such that:
- All of the distinct characters present in must be present in the string .
- We will then make a string by repeatedly adding the string to it untill the string can be rearranged to have the string as a substring.
- The generated string should be of the minimum possible length.
- If there are multiple possible with the same length, the string should be chosen so that the generated string is the lexicographically smallest possible.
Return the string that would generate the string . Return empty string if no such string exists.
Solution
It is clear that we need to minimse the number of copies of the string that we need to add to the string . We can binary search on this value of copies needed, and then generate the string greedily by adding the minimum number of characters needed to fullfill condition , and pad the rest of the spaces with the character .
Time Complexity: where is the length of the string .
PACE Stock Broking
Other Campus Questions
-
There are employees in a company, out of which there are special employees who have data network and share their mobile hotspots with other employees. There are employee edges connections already made between the employees, where the / connection connects the employees and , such that either of the employees, and can share a mobile hotspot.
Two employees and are connected if there is a path between them. All the employees connected to a special employee will use the mobile hotspot of the special employee .
Up to now, to restrict data usage, any employee was connected to at most one special employee. As data consumption has increased, any employee can be connected to at most number of special employees. Find the maximum number of edges that can be added to the graph such that any employee is connected to at most special employees.
Solution
It can be proven that it is optimal to greedily make a component as large as possible. To do the same, we will perform the following steps:
- Perform a BFS on the graph to find the connected components.
- For each connected component that has no special employee, connect it to the largest connected component that has a special employee.
- Sort all the connected components in decreasing order of their size.
- If the components are , then connect the first components (i.e. ), then the next components (i.e. ), and so on.
Now each component with size contribute to the answer, where is the number of edges present originally in that component. The time complexity of the solution is .
-
A simple variation of Minimum Path Sum
-
A simple variation of the Job Scheduling Problem
-
Find the number of ways to colour a grid using colours such that no row and column has all the colours the same. Print the answer modulo .
Solution
Refer to this blog post.
-
The floor of your house is created by tiles, which are either empty (
.
), dirty (D
) or have food (F
). Your task is to group the food into a single consecuive group while following the following rules:- You can move the food to the left or right by one tile at cost .
- Food can’t be moved to a tile that is dirty.
- The cost to clean a dirty tile is .
Given queries, each all of the form and a string representing the floor, find the minimum cost to group all the food together for each query.
Solution
This is an application of the standard problem trying to group people together, along with the realization of the fact that all the dirty spots between the leftmost food point and the righmost food point must be cleaned. The complexity of the solution is .
-
There are infinite seats in a bus. There are people in a queue waiting to board the bus, and each wants to board and sit as seat . It is givent that the seat desired by each person is between and . The allotment is done in the following manner:
- If the seat desired by the person in the front of the queue is empty, they are allotted that seat and removed from the queue.
- If the seat desired by the person in the front of the queue is occupied, the seat number desired by them is incremented by and they are pushed to the end of the queue.
Find the final seat number allotted to each person in the queue. There are atmost people in the queue.
Solution
We will first store all the people who have not been alloted a seat in a stack to simulate their priority. We can also see that at max seats till index will be occupied. The rest can be seen from the implementation. The time complexity of the solution is .
-
You are running a restaurant and are expecting customers. The customers are represented by a vector of where the customer is represented by . The customer arrives at time and will stay till time . The customer will order dishes. What is the minimum number of chefs you need to hire so that all the customers can be served?
- Assume that any chef can prepare any dish in unit of time.
- A customer takes no time to eat the dishes after they are served, and they order all the dishes at once as soon as they come.
Solution
We will binary search on the number of chefs required. We can then simulate the process of serving the customers and check if the number of chefs required is less than or equal to the number of chefs we have. So simulate the process, we can use the greedy strategy of trying to serve the customer who is leaving the earliest first. Careful implementation is needed to ensure that you do not process the dishes of the customer before they arrive! I have used a priority queue to store the dishes to simulate the same. The time complexity of the solution is where is the maximum number of chefs that can be needed.
-
You are given a string whose length can be more than . You are given an array and a string showing the count of the characters (for example, if and is
ab
, then the string isabb
). Count the number of sequences modulo such that every subsequence contains all the vowels atleast once.Constraints:
Solution
We will make use of DP to solve this problem. We will maintain as the current index in the compressed string that we are processing, and a to represent the vowels that have occured atleast once in the current subsequence upto the index . The time complexity of the solution is . The extra factor of comes from the fact that we are using the binary exponentiation to calculate the powers of , which can be removed with the help of precomputation.
-
You are given three arrays , and of length each. In one operation, you can choose any one element from any one of the arrays and move it to any other array. After you have performed all the operations, we would sort each of the arrays indidually, and then concatenate them. What is the minimum number of operations that you must perform so that the final resulting array formed is also sorted?
Constraints:
Solution
We can use an approach similar to merging sorted arrays in this question. Let us first sort all the three arrays, and now try to form the new array. If we are able to add the element from the first array, then that is analogous to no operation being required for the sorting to be performed. On the other hand, it the current minimum is either from the second or the third array, then atleast one operation would be needed to put the same to it’s correct position. This can be simulated easily with the help of pointers or we can use priority queues for easier implementation. The time complexity of the solution is .
-
You are given an array on length . In one operation you can choose any two distinct indexes and , remove both the elements from the array, and then add their sum back to the array at any position of your choice. What is the minimum number of operations required to make the array sorted in non-decreasing order?
Constraints:
Solution
Let us fix the elements that we would not change in the array, that is the longest non-decreasing subsequence in the array. We can then see that the elements that are not part of the longest non-decreasing subsequence must be removed and added back to the array. When adding back, we can always pair two elements together, and add them in the appropiate position in the sorted array. The time complexity of the solution is .
-
There are bacteria samples which are arranged in a row in a lab, from to . There are number of pairs of bacteria, where bacteria is poisonous to the bacteria . Determine the number of intervals of samples that can coexist.
Constraints:
Solution
-
For some array , the score of the array is defined as . Given an array , find the sum of the scores of all the non-empty subarrays of the array. Return the same modulo .
Solution
For each index , let us calculate the number of subarrays that have the maximum element as that index, and add the contribution of all those arrays to the answer. This can be done with the help of some maths and stacks. Remember to handle the equality of the elements in exactly one the computations of either the previous greater or the next greater and calculate the contribution of the lengths accordingly. The time complexity of the solution is .
Online Assessment Questions
-
Solution
The key realization to solve the problem is that you will never need to increment one number (or fence) by more than times in the optimal solution. Using the same we can write a simple DP solution with the time complexity of .
-
You are given a tree with nodes, and each node has a value . You are given queries, and for each query you need to count the number of nodes with a prime value in the subtree of the query . The tree is rooted at .
Constraints:
-
You are given an even integer . You need to count the number of ways to colour a grid using colours such that no two adjacent cells have the same colour and the cells equidistant from the beginning and the end also do not have the same colour. Print the answer modulo .
Constraints:
- is even
-
You are even a grid of size . Each cell of the grid is either:
- -> Meaning that it is free to move
- -> Meaning that it is blocked
- -> Meaning that it is a has a gold coin
You need to begin at the point and end at the point and need to collect all the gold coins on the way. You can only move within the grid, and can move in any of the directions. Find the minimum number of moves required to collect all the gold coins. You are allowed to visit multiple cells multiple times.
Constraints:
- Count of gold coins
HiLabs Technologies
The company repeated the coding questions across campuses, even if the gap between the OA dates was more than days. MCQs questions were also partially repeated across campuses, both for the SDE and DS roles.
Other Campus Questions
-
You are given a graph with nodes and edges. The graph is undirected and unweighted. A bridge is an edge that, if removed, will increase the number of connected components in the graph. Find the number of pairs of nodes in the graph such that and any path between and contains exactly one bridge.
Constraints:
Solution
You can use Tarjan’s algorithm to find the bridges in the graph. Then, you can condense all the nodes in the graph that have no bridge between them into a single node. This technique is known as the bridge tree. Then the given condition converts to chosing two nodes in the bridge tree such that the path between them contains exactly one edge. The time complexity of the solution is .
-
You are given an array of length . What is the maximum GCD that you can obtain by selecting exactly elements from the array?
Constraints:
Solution
We will try to exclude every element from the array and calculate the GCD of the remaining elements. The maximum GCD that we can obtain is the maximum of all the GCDs that we calculate. This calculation can be done in time by using prefix and suffix GCD arrays. The time complexity of the solution is .
-
A compnay has servers, labelled from to , all of which initally have no workload. requests are sent to the company’s API, where the requests are distributed evenly between the servers. An even distribution ensures that the busiest server has the least possible load. Print which server would handle the request for each API request.
Solution
Use a priority queue to store the servers and their loads. The time complexity of the solution is .
-
You are given an array of length . You need to find the number of ways to divide the array into subarrays such that each subarray has exactly one present in it. The length of the array is up to . The answer can be large, so print the answer modulo .
Solution
We can simply store the indices of all the s in the array and then perform a cut at each of the position between two consecutive s. The time complexity of the solution is .
-
A consisent sequence is a binary string where all the adjacent elements are different. You are given an integer . Find the number of consistent subsequences of a consistent sequence of length starting with the character . Return the number of subsequences modulo .
Solution
The sequence given to us is nothing but and we need to find the alternating sequence of s and s. We can use a simple DP to solve this problem. The time complexity of the solution is .
-
The beauty of an subarray between of array is defined as . Print the maximum value of the beauty across all the possible distinct indexes in the array.
Solution
We maintain the largest value of beauty in the subarray. Then at any index either we can start a new subarray or extend the current subarray by adding the element and one unit of . The time complexity of the solution is .
-
The beauty of an subarray between of array is defined as . Print the maximum value of the beauty across all the possible distinct indexes in the array. The array is indexed.
-
You have coins with values from to . Find the number of ways of choosing exactly coins such that the sum of the coins is divisible by . Return the number of ways modulo .
Constraints:
Solution
We can use a take or not-take approach to solve this problem. The state of the DP can be represented as where is the coin that we are considering right now, is the number of coins taken that we can take in the next moves, and is the sum of the coins that must be taken in the next moves modulo . The time complexity of the solution is as each state can be reached in time.
This might give TLE in a time limit or MLE in strict constraints, so we can space optimise the same and make use of arrays instead of vectors to improve the performance.
Space Optimised Solution
-
You are standing at position . You can move to any position which is the product of any two elements of the array from the current position. Find the maximum distance you can move in one jump.
Constraints:
Solution
You will make the jump to either the most positive position possible or the most negative position possible. The time complexity of the solution is due to the sorting.
-
You are given an array of distinct elements . You elements and can be connected by an edge if . Find the minimum number of connected components possible in from the given array.
Constraints:
Solution
It is obvious that elements greater than when paired with any other element would have a greater than . So we can ignore all the elements greater than . Now let us fix the as . We can push all the elements that are divisible by into an array. Now it is certain that all the elements in this array with have a of atleadt . We can use a two pointer approach to connect all the elements in the array that have . We will use a DSU to connect all the elements in the array. The time complexity of the solution is where is .
-
You are given a tree with nodes with one node intially marked as black, and the rest marked as white. In one operation, you can colour any of the nodes black only if atleast one the neighbours of the node is black. Count the possible number of colourings of the tree. Return the answer modulo .
Solution
We can use simple DFS to solve this problem. Let the function return the number of ways of colouring the subtree of (when the whole tree is rooted at ) and the node is coloured black. Then for every child node, we can either leave it white, resulting in way of colouring, or colour it black which can be calculated recursively by multiplying with the result of the function. All the ways for all the children are multiplied together to get the final result. The complexity of the solution is .
-
When comparing two numbers, you need to first compare the sum of digits of the two numbers, and only if they are the same, then you need to compare the actual values of the numbers themselves. Given an array , for each index, find the index of the closest number to the right that is bigger than the number at the given index according to the comparision scheme specified above. If no such number exists, print .
Constraints:
-
You are given array of size . You can make atmost operations on the same, where in each operation you can increase or decrease an element in array by . Now, the beauty of array is frequency of most frequent element in the array. Output the maximum beauty that can be achieved in operations.
Constraints:
Solution
Let us first sort the array and try to binary search on the answer. It is clear that when we are checking the validity for an answer , we would want some subarray of the sorted array to become all equal to . Thus we can maintain a sliding window, and calculate the required number of operations for each window. It is a well known fact that given a sorted array, the median of the array is the point from where the number of operations required to make the array all equal by increments and decrements is minimum. We can use prefix sums to calculate the number of operations required to make the array all equal to in time for any subarray. Thus the overall complexity of the solution is .
-
You are given a tree with nodes and each node has the value initially. The tree is rooted at . You need to perform queries on the same of the following types:
1 X Y
: Increase the value of all the nodes in the subtree of node by .2 X Y
: Increase the value of all nodes by except the nodes in the subtree of node .
Print the final values of all the nodes in the tree.
Constraints:
Solution
-
This question was asked in the Software Developer role, and a workspace was provided to work on the same. You are required to design a simple HTML page that accepts from the user the number of rows and columns, and then makes a table of the specified dimensions. There is bonus marking for CSS styling.
HTML Code
Online Assessment Questions
-
You are given a string and a dictionary of words as of length . You need to find the word from the dictionary with the minimum edit distance with respect to the provided string . If there are multiple such words, return the lexographically smallest word.
Constraints:
-
You are given a string of length denoting a valid binary expression. The string can have the following characters:
x
: Denotes the primary variableX
: Denotes the negation of the primary variable1
: Denotes the logicaltrue
value0
: Denotes the logicalfalse
value&
: Denotes the logicaland
operation|
: Denotes the logicalor
operation^
: Denotes the logicalxor
operation(
: Denotes the start of a subexpression)
: Denotes the end of a subexpression
You need to determine the minimum number of substituitons required (replace any
x
orX
with0
or1
) to make the expression evaluate to eithertrue
orfalse
. There are multiple testcases, and you need to print the result for each testcase in a new line.Constraints:
- The expression is always valid.
Sample Input:
Sample Output & Explanation:
-
A UI screenshot involving three buttons and a picture was given. Depending upon which button is clicked, the image shown shown be changed. Some amount of Flexbox and CSS was required to position the buttons and the image in the correct manner as shown in the UI. Asthetics was also a part of the marking.
InMobi
Other Campus Questions
-
You are given projects, where the project has a pure profit of and a minimum capital of is required to start the same. Initially you have capital. Whenever you complete a project, you will obtain its pure profit and the same would be added to your capital. Pick a list of at most distinct projects from the given projects to maximise your final capital, and return the final maximised capital.
This question is repeat of IPO on Leetcode.
-
Solution
-
You are given a string of lowercase English letters. You need to select one index from it and remove the letter at that index from such that the frequency of every letter in is equal. Return
true
if it possible to do so in exactly one operation, or else returnfalse
. -
Imagine a vertical line cutting through the root node, thus dividing the left and right sub-trees of it. A mirror element of a node satisfies the following three properties:
- It is on the opposite side of the dividing line.
- It is at the same depth as .
- It’s horizontal distance from the vertical dividing line is the same as that of .
Your task is to write a program logic that first creates a Binary Search Tree, then creates a mirrored tree out of it, and finally prints the preorder (Root, Left, Right) traversal of the mirrored tree. Your program will be provided with the number of nodes in the Binary Search Tree and the data of nodes separated by space in the next line.
Solution
This question can be seen as a conjuction of three standard DSA problems:
- Creating a balanced BST from a sorted array.
- Mirroring a binary tree.
- Preorder traversal of a binary tree.
The implementation is relatively simple. The time complexity of the solution is .
-
Try all the variants of the House Robber problem.
Online Assessment Questions
-
Given an array of size , find the missing and duplicate integer in the array. The array is supposed to all the integers between and exactly once.
-
Find the probability to reach the target node from the root node in an unweighted undirected tree in time . In each second you can visit one of the unvisited nodes from the current node with equal probability, and if there are no unvisited nodes, you can stay at the same node. The tree is given in the form of an adjacency list.
-
Given an integer and character of size containing two characters: for guard and for intruder, you need to count the maximum number of intruders that can be caught. A guard can catch only one thief if it lies in range where is the position of the guard under consideration.
Dream 11
Other Campus Questions
-
Cricket is a team sport comprised of player each team has four types of player: Batsman, Bowler, All-Rounder, and Wicket Keeper. Dream11 is a fantasy cricket platform where users create their own cricket teams. You have decided to participate in Dream11 during the IPL season. The platform rewards prizes based on the maximum total value of your team. Your task is to create a cricket team based on certain constraints to win the reward.
Write a program to do so while adhering to the following constraints:
- Your team must consist of players.
- You have a budget of to spend on selecting players.
- Each player has a price tag and a player value.
- There are four types of player: Batsman, Bowler, All-Rounder, and Wicket Keeper.
- Your team should have at least one Wicket Keeper, one All-Rounder, two Batsmen, two Bowlers.
- Now given list of price and player values to determine the type of players:
- The first 20% of players are considered as Wicket Keepers. Note: Take the ceil of the number obtained.
- Batsmen are selected from odd positions (excluding the first 20%).
- Bowlers are selected from the even positions that are not divisible by 4 (excluding the first 20%).
- All-Rounders are selected from positions divisible by 4 (excluding the first 20%).
- Player index starts from zero. Please factor this in calculation of player types viz. Wicket Keeper, All-Rounder, Batsmen and Bowler.
Print the maximum total value which is the summation of the selected player values, that can be obtained while satisfying all the constraints and is within the budget else print
Insufficient Budget
.Constraints
Solution
We will use dynamic programming to solve this problem. We will maintain a -dimensional DP array where the dimensions are the index of the player, the budget left, the number of Wicket Keepers, the number of All Rounders, the number of Bowlers, the number of Batsmen, and the total number of players. We would also need to space optimise the solution as the number of dimensions is too high. The time complexity of the solution is which approximately equals operations.
-
You are given a rectangular grid with the bottom left corner as and the upper right corner as . Find all the lattice points in the grid that are at a maximum distance of from the given point . The distance between two points is the cartesian distance between them.
Constraints:
Solution
Since the coordinates are upto only, we can loop over any one coordinate and then use binary search on the other coordinate to find it’s maximum and minimum possible value that allows it to be within the described circle. If we iterate over the coordinate , we need to consider the position of the center and thus make three different cases for the same. Refer to the implementation for details. The time complexity of the solution is where and .
Testing Script
If you want to test your own solution, you can use this script to generate random testcases and compare the output of your solution and the brute force solution.
-
You are given an undirected and connected graph with nodes. Intially you are at node , and need to travel to node . There are power boosters at nodes, and every time you arrive at a power booster node, your power is set to , which allows you to walk cross edges. What is the minimum value of such that you can reach node from node ?
Constraints:
Non Optimal Solution
As with such minimization questions, we will use binary search to find the minimum value of . Once we have a value of , we can use a simple Djikstra to find if a valid path exists. The only change we need to make is if we arrive at a power booster node, we need to set the power to instead of further decrementing it.
You might expect the time complexity of the solution to be where is the maximum number of edges in the graph due to Djikstra, but the same turns out to be in the order of instead. This is because having power booster breaks the monotonicity of the distance function that Djikstra expects (Suppose you reach an intermediary power node that is still at a large distance from destination before the other power node that is at a smaller distance. Now you will recharge at that node (farther from destination) and do Djikstra from it which would be of no use as it is suboptimal and may not be able to reach the final destination from there)
Optimal Solution
We will binary seach on the value of . To check for a particular value of , we will construct an new graph with the nodes , , and all the nodes which are at a distance of from any power node. We will then just run a BFS to check if a path exists from to in this new graph. The time complexity of the solution is .
-
Solution
Since it is clear that only each number can be used at most once in a valid subset, we can maintain a map of the frequency of the elements present. We will use a bitmask to show which all prime numbers have been already been used in our product, and keep the other state as the number we are trying to add to the answer. The main trick behind the question is to first ignore all the occurences of , and then add them later to the sets achieved by the other numbers. The time complexity of the solution is where is the count of maximum occurences of , which can be in the worst case.
Online Assessment Questions
- There were 10 MCQs on C++, OS, and DBMS, and 2 coding questions.
- The MCQs were partly repeated from those of other campuses and some were new. There was a particular focus on error handling in C++ and the basics of DBMS.
- The coding questions did not run all the test cases. Only 2-3 sample test cases were visible, and the code would be evaluated later was the general feedback.
-
Same question as Deutsche Bank: Question from the
Other Campus Questions
section. -
You are given upto queries of the type , where in you have to find the beautiful number between and . A number is said to be beautiful if it contains the substring in it’s binary representation.
Netradyne
The test usually involves 2 coding questions and 1 question involving writing a SQL query. The rest are MCQs from topics like:
- Sitting arrangements
- Percentages & Ratio-Proportion
- Graphs & Data Interpretation
- SQL
- Operating System & Deadlock Synchronisation
- DBMS Normalisation
Other Campus Questions
-
The map contains islands named from to . For any two islands and , you can go to from only if divides . Find the number of ways to reach island starting from island . You can’t move from island to . There are test cases, each denoted by a single integer , the island that you have to reach.
Constraints:
Solution
We can use a simple sieve like approach to compute all the divisors of all the numbers upto and then use a simple DP to precompute the number of ways for all the possible . Then answering any query takes just time. The time complexity of the solution is where .
-
You are given an array of elements. In each step, you need to take the sum of the numbers at the odd indexes of the array ( indexed), and remove all the even elements. Do this until only element is left in the array. What is the final sum obtained?
Constraints:
Solution
Writing the pattern for a couple of arrays by hand, we realize only the elements at index such that are added to the answer for every possible value of greater than . Thus we can writing a simple simulation in $O(n \log n) time.
-
You are given an array of length . You need to all the subsequences of the same of length , and then calculate the score of the subsequence as the product of the first and last element of the subsequence. Return the minimum possible score of any subsequence.
Constraints:
Online Assessment Questions
-
You are given an integer as a string . In each iteration, you need to take the sum of the digits of the number with have their index divisible by . Treat the obtained number as the original string and repeat this untill you obtain a simple digit sum. Return the same.
-
You are looking to hire frontend and backend developers. There are candidates, each of which can be hired either as a frontend or backend developer. The cost of hiring the candidate as a frontend developer is and the cost of hiring the candidate as a backend developer is . Find the minimum cost of hiring frontend and backend developers.
Constraints:
-
There was MCQ on aptitude, simple SQL query writing question, and MCQs from OS, C++ and data structures. A couple of the MCQ questions were repeated from the questions from other campuses.
Microsoft
Other Campus Questions
-
You are given square tiles of size and square tiles of size . Your task is to create the largest square possible using the given tiles. The tiles can not overlap, and the resulting square can not have empty spaces in between. Return the side length of the square.
Constraints:
Solution
The key trick to realize is that if try to binary search over the length of the longest side of the square , then the function would be moontonic sepearately for the cases of even and odd side lengths. This is due to the difference in the optimal greedy strategy to construct the squares:
- For odd side lengths, you atleast need tiles of size that can be used to fill two adjacent edges, and then you can fill the even square of side with the remaining tiles.
- For the even sides, use as many as possible tiles of size to fill the square, and then fill the remaining gaps with the tiles of size .
Then we can simply perform two binary searches to find the maximum possible side length of the square. The time complexity of the solution is where is the maximum possible side length of the square.
-
There is string of length consiting only of characters . Whenever there are two identical adjacent letters, they can be merged together to form the next alphabet (for example, can be converted to ). The letter pair can be merged. What is the lexographically maximum string you can obtain by applying the operations optimally?
Constraints:
Solution
-
Strings with long blocks of repeating characters take much less space if kept in a compressed representation. To obtain the compressed representation, we replace each segment of equal characters in the string with the number of characters in the segment followed by the character (for example, we replace segment
CCCC
with4C
). To avoid increasing the size, we leave the one-letter segments unchanged (the compressed representation ofBC
is the same stringBC
).For example, the compressed representation of the string
ABBBCCDDCCC
isA382C2D3C
, and the compressed representation of the stringAAAAAAAAAAABXXAAAAAAAAAA
is11AB2X10A
. In order increase the compression further, we decided to modify our compression algorithm. Now, before compression, we remove exactly consecutive letters from the input string. We would like to know the shortest compressed form that we can generate this way.Constraints:
Solution
-
In this task, you are given two strings of digits that represent (possibly very large) Integers. Your goal is to make those numbers as close to one another as possible. In other words, you want to minimize the absolute value of their difference. You can swap some of the corresponding digits (e.g. the first digit of the first the first digit of the second number, the second digit of the first number with the second digit of the second number, etc.). Swapping the digita is an extremely tiring task, so you want to make as few swaps as possible. Write a function that, given two strings and , both of length , returns the minimum number of swaps needed to minimize the difference between the two numbers represented by the input strings.
Constraints:
Solution
-
There is an array of integers. What is the largest sum of two numbers which do not have any common digits? If it is impossible to choose two such numbers, the function should return .
Constraints:
Solution
Online Assessment Questions
-
You are given strings of length each. You need to form a string of length such that all the strings differ from the same by atmost character. If it is not possible to form such a string, return an empty string.
Constraints:
- The strings consist of lowercase English alphabets only.
-
You are given a grid of size . You need to start from and need to reach the cell . You can only move rightwards and downwards. The cost of this path is the maximum value of the grid that comes in the path. Find the minimum cost of the path.
Constraints:
Other Campus Questions
- You are given an array of length and two number and . You can perform at max operations on the array, where in one operation you can select any subarray of of length at most , and decrement the value of all elements of the subarray by . Determine the minimum value of the maximum element present in the array if the operations are performed optimally.
-
-
-
Solution
It is clear that we can binary search on the answer. Once we have fixed the maximum element of the array, we can simply iterate over the array from left to right, and whenever we see an element that is greater that the currently fixed maximum, we would apply operations to it to bring it to the maximum. We would always greedily apply the operation to the largest possible subarray, that is of length as it would never worsen our answer. The application of range updates would require the difference array concept. The time complexity of the solution is where is the maximum possible value of the maximum element in the array.
-
You are given a graph (not necessarily connected) of nodes numbered from to and edges. Each edge has a cost associated with it. You can break any edge, disconnecting the pair of nodes in one operation, but you must add the same edge between a different pair od nodes. The cost of one such operation is the cost of the edge. Find the minimum cost to make the graph a tree.
- The graph may contain self loops and multiple edges between the same pair of nodes.
Solution
Since the final connected graph must be a tree, we can make minor modifications to the algorithm for the Maximum Spanning Tree. We will iterate over the edges in the decreasing order of their cost, and only change the edges are present between some already connected components. We won’t add these edges to any component just yet, as it would be optimal to hold of them till the end, and then connect the disconnected components with them. We can use the DSU data structure to keep track of the connected components. The time complexity of the solution is .
Online Assessment Questions
-
You are given an array of length . You need to count the number of quadruples such that and .
Constraints:
Solution
-
You are given an array of size and an integer . You want to divide the array into non-empty contiguous subarrays such that each subarray is a good subarray. A good subarray has the absolute difference between any two elements in that array to be greater than or equal to . A singleton array is by default a good subarray.
What is the maximum possible value of such that the division is possible?
Constraints:
Solution
-
Lexographically Smallest Beautiful String
Solution
Plutus Research
Other Campus Questions
-
Given two integers and () and , find the minimum value between and such that sum of digits of all numbers between and is at least . Its given that at least one such exists.
Solution
We will try to binary search on the answer. If the current answer is , we need to check if the count of digits in the range is atleast or not. The same can be calculated by finding a function to give the sum of the digits of the numbers in the range , which will use digit DP to calculate the same. The time complexity of the solution is .
-
Given an array of size , find the number of subarrays whose product of the minimum value and the maximum value is divisuble by the length of subarray.
Solution
Since the maximum value of the array is , the maximum possible product of the minimum and maximum value of the subarray is . We can iterate over all the possible subarrays of length at most and count the number of subarrays that satisfy the condition. We will use deque to maintain the minimum and maximum in the current subarray. The time complexity of the solution is .
-
Given a tree of nodes rooted at and an array of integers , you need to process queries of the form
v x
. For each query you need to tell the maximum length of the matching prefix (from the MSB to LSB) of and any of the values of the nodes that lie on the path from the root to the node (all ancestors of and ). Each number is represented in bits.Solution
We can use a bit trie to store the binary representation of the numbers. We can then use the trie to answer the queries in time while performing a DFS on the tree. The time complexity of the solution is .
-
Given balls of some colors, where the ball’s color is , you need to find the minimum number of arrangements of these balls module where you can perform an operation atmost once, in which you can choose all balls of one color and change their color to some other color.
Solution
You need to use the simple formula for the number of arrangements of balls of colors, which is . It is clear to minimise the value of this expression, we must combine the two largest colour groups into one. The time complexity of the solution is due to sorting and some addtional time is needed for the factorial calculation.
-
Same question as Deutsche Bank: Question & from the
Online Assessment Question
section. -
Same question as Deutsche Bank: Question , & from the
Other Campus Questions
section. -
Same question as HiLabs: Question from the
Other Campus Questions
section. -
You are given a number , which represents time. Starting from the origin, you can move in any of the fourth cardinal directions, but once you make a move, the next move that you make should be perpendicular to the previous move. What is the distinct number of coordinates reachable with this time?
Solution
Due to the small constraint on the value of , we can simply simulate the movement of the person and keep track of the coordinates that are reachable. The time complexity of the solution is if we use a BFS to simulate all the possible moves.
-
You are given a graph of cities and edges between these cities. If two cities are connected, then they belong to the same kingdom. You are also given an array of length where denotes the number of people living in the group . You need to assign each group to exactly unique city so that the sum of number of friendships across all the kingdoms is the maximum possible. A pair of people are said to be friends if they belong to the same kingdom. Output the maximum possible number of friendships.
-
-
-
Solution
We can use a simple greedy approach and calculate the number of cities in each kingdom (connected component). Then we can use sort the groups in the reverse order, and try to assign the largest number of people to the largest possible kingdom. The time complexity of the solution is .
-
You are given a binary string of length . You need to count the number of substrings it has such that it has atleast bits set.
Constraints:
Solution
We can use a simple two pointer approach to count the number of substrings that have atleast bits set. The time complexity of the solution is .
-
You are given two positive integers and without leading zeroes. You can perform an operation on these integers any number of times, in which you can delete a digit of the given number such that resulting number does not have leading zeroes: Let and be two numbers that were formed after performing operations on and respectively. You have to find the number of all the unique pairs of and whose XOR is zero.
Two pairs of numbers and are considered different if and only if and .
Constraints:
- and do not have leading zeroes.
Solution
Two numbers and have XOR equal to only and only if they are equal to each other. Thus the answer is nothing but the number of common subsequences of the two numbers when represented as string. We must be careful to exclude the strings with leading zeros. The complexity of the solution is as we will be using a bitmask to generate the subsequences.
-
You are given a tree of nodes and edges rooted at node with exactly one candy placed at each node. Let’s say the cost of the candy placed on the node is and you have amount of money. Now, you will choose exactly one node (say, ) and will start buying the candies placed on the path from node to the root until you run out of money, that is, first, you will buy the candy placed at node ,then the candy placed at the ancestor of , then it’s ancestor so on till you run out of money or you reach root node. Also, you cannot skip over a node without buying the candy placed on it. Calculate the the maximum number of candies you can buy in a given amount of money by choosing exactly one starting node.
Constraints:
Solution
We will use binary lifting to solve this problem. For each node, we would calculate the ancestor of the node and the money that we would need to spend to reach the ancestor. Then we can simply iterate over all the nodes and calculate the maximum number of candies that we can buy. The time complexity of the solution is .
-
You are given a circular array with elements. In one operation, you can swap any two adjacent elements. What is the minumum number of operations you need to perform to make the first two elements of the array same? Return is the same is never possible.
Constraints:
Solution
We will iterate over all the elements, and count the moves needed to make them the first two elements. We will then take the minimum of all the moves. The time complexity of the solution is .
-
You are given an undirected graph that contains nodes and edges. These nodes are numbered from to . Initially, you start at node . Each node except node has a priority associated with it that is denoted by the array denoted as . You have to follow these commands to visit each noche in the path:
- You have to start at node and move to the next unvisited node which directly connected to node and having the highest priority.
- If the priority is the same for multiple nodes, then you have to select the nodes that have the minimum distance between them.
- After going to the next node, you have to again select a connected node that has the highest priority among the remaining unvisited nodes
- If there are no adjacent unvisited nodes at a point, then you have to traverse back to the previous node from where you came to the present node for the first time
- You cannot traverse the path once you reach the last unvisted node.
If the distance between the node to node is , then the time elapsed to reach from one node to another is units. Determine the time required to reach at each node except node for the first time. The given graph is a connected graph.
Constraints:
-
You are given the two arrays and of length and respectively. Consider the following points on the coordinate plane:
Find the area of the largest rectangle that can be constructed from the given points. If there is no rectangle possible then print .
Constraints:
Solution
It is obvious that it is only possible to form a rectangle if there are atleast points on the same line. We can iterate over all the points and store all the points that are common in and , and then take the minimum and maximum of the points to calculate the area of the rectangle. The time complexity of the solution is .
-
You need to implement the Least Frequently Used (LFU) cache with the capacity . You are also given operations of the following type:
- : Get the value of the from the cache. If the value does not exist in the cache return .
- : Update the value of the if present, or insert the if not already present.
When the cache reaches it’s capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (two or more keys with the same frequency), smallest key should be removed. For each operation of type , print the required value.
Solution
Since we need to remove the key with the smallest value when the cache is full, we can use a set to store the keys in sorted order. We can use a map to store the frequency of the keys and a set to store the keys with the same frequency. The time complexity of the solution is .
-
During your English exam, you are given a question to find whether a sentence is valid according to the defined rules. You need to create a basic sentence checker that takes in strings as input and determines whether they form valid sentences. You can consider a sentence valid if it conforms to the following rules:
- The sentence must start with a capital letter, followed by a lowercase letter, or a space.
- All other characters must be lowercase letters, separators (
.:;
) or terminal marks (.?!
). - There must be a single space between each word, where space is denoted by
$
. - The sentence must end with a terminal mark immediately following a word.
You are given an integer where denotes the length of the string sentence. You are given a string sentence that you need to validate. Print if the string sentence is valid else print .
-
Alice wanted to setup a chain of restaurants in a town. The town is represented as an axis on the number line. The town consists of houses, and the location of each house is known and given by array . She has to deliver food at each house location. She will set up restaurants in the town and appoint as many delivery boys as she wants at each restaurant. All delivery boys leave the restaurants together for food delivery for all the locations. She will choose locations in town to set up restaurants, such that all food packets get delivered in the minimum possible time. Determine the minimum time in which all food packets get delivered to each house in the town.
- It takes one unit of time to travel one unit distance.
- There is no delay in delivering the food packet, once the delivery boy has reached the delivery location.
- There is no limit on food packets that can be delivered by a single delivery boy.
Solution
We will binary search on the minimum of the maximum distance that all the houses can have from any restaurants. The time complexity is .
Probability Questions
-
Patel is having a party for foreign delegates at his farmhouse. Out of the guests, can speak French, can speak German and can speak Dutch. Mr. Patel, as a diplomatic policy, starts giving a thank you note speech for all his guests which has phrases from all the three languages. At least, how many people would understand the full speech given by Mr. Patel?
-
On a lazy Sunday afterrioon, Chandler thinks of challenging Joey for his love of pizzas. He comes up with a game where Chandler throws a dice and the number that appears on the dice would be the number of pizza slices Joey will have to eat, except when appears. In that case, Joey has to eat pizza slices and Chandler gets to throw the dice again. This may continue Indefinitely. What is the expected number of pizza slices Joey will eat?
-
There is an array of size , with numbers from -. A random permutation of these numbers is stored in the array. What is the expected number of local minimas in the array. (A point is called local minima if it is the lowest among its neighbours, with first and last index having only one neighbour)
-
Mama’s Pizza Kitchen has a percent discount every Friday, Rohit has promised his friends for a treat on his new job’s first salary but will get his salary credited on the last business day of the month. What is the probability that Rohit would be able to avail the offer the day he receives his salary and takes his friends out on a treat to Mamma’s Pizza Kitchen?
-
If and , what is the maximum possible value of ?
-
You host a game where a person throws two dice. Person will get money according to dice rolls (, being the numbers on respective dice throws). The payout will be equal to . What is the expected value of the game?
-
You are given a box with balls ( yellow and red). You pick balls from the box one by one without replacements until all the balls are out. A yellow followed by a red or a red followed by a yellow is termed as “Flip”. Calculate the expected number of “Flip” if the balls are being picked at random.
-
What are the two next terms in the sequences:
-
Sum is to be broken down into a set of positive integers such that the product of to is maximised. What is the maximum product possible?
-
You are a trader considering a stock whose next price movement will be up or down with equal probability. Fortunately you have access to a binary signal predictive of the price change (observable ahead of time). The signal is accurate, conditional on the stock going up. There is a probability that the signal says up and probability that it says down. The reverse is true if stock goes down. You have access to many such signals, all with the same accuracy.
Assume they are conditionally independent given the price movement (eg. conditional of the stock going up, there’s a probability that signals one and two both point up). Suppose you observe such signals and out of those of them are pointing up, while of them are pointing down. What is the probability that will go up?
-
A bitwise XOR for all tile numbers in a list is calculated as: if the number of times appears in the bit is odd and if the number of times appears in the list is even. A function is defined as the XOR of all natural numbers between & , both and inclusive. What is the value of ?
-
There are socks Monica has with numbers to on them. Out of those socks are white and are blue. She has numbered white socks from to and blue socks from to . Joey, Chandler, Ross, Rachel and Phoebe come one by one and pick one blue and one white sock randomly. Score of every person is determined by the sum of the pair of socks they wear. What is the probability that the product of scores of those all five friends is divisible by .
-
What is the smallest such that has zeroes?
-
There are doors. Behind one of them is a Mercedes Benz and behind the other the key to the Mercedez. The remaining three doors are empty. Hrithik knows what is behind all the doors. He asks you to choose two doors. After you choose doors, he opens an empty door which is not chosen by you. Now he gives you a chance to either stick to your earller chosen doors or to switch to the other closed doors. You win the car if you choose doors having both a car and a key. Let be the probability of winning the car in the best case. What is ?
-
You are playing a game with your friend, in which you toss a fair coin. You win point from your friend if the head comes, and if talis comes your friend wins point from you (your score is ). The game continues till either one of you reaches a total of points (and the other one has points). At this point the winner gets dollars from the loser.
- What is the expected value of this game?
- Now, assume you have an option to double the payoff (from to ) of the winner at any point of the game. You can use this option only once. What is the expected value of the new game?
-
A country has only denominations: and . What is the highest integral amount that cannot be made using only these denominations?
-
What is the total number of digit numbers such that the product of the digits of that number is divisible by ?
- Case : Consider numbers whose product is 0 to be divisible by 10.
- Case : Consider only non-zero digit numbers.
-
There are people in a group, for any two members and there is a language that speaks but does not and there is a language that speaks but does not. What is the minimum number of distinct languages spoken by this group?
Online Assessment Questions
-
There are string potions and weak potions. You need to prepare a mixture of potions, such that it atleast has strong potions and weak potions. What is the total number of ways to prepare the mixture?
Constraints:
-
You are given a tree with vertices. Figure out the number of unordered pairs of distinct vertices such that the simple path between them has exactly prime node lying on it.
Constraints:
Solution
-
You are given two arrays and of length . You need to select a subset of indices from such that for any pair of indices , atleast one of the following conditions would hold true:
- If , then
- If , then
- If , then
Find the length of maximum possible subset.
Constraints:
-
There are people, numbered from to . You are also given an vector of pairs if two people and have an enemity. You need to fivide these people into two teams of equal size such that two people who are enemies are not on the same team. It is also guraunteed that each person has enemity with atmost other people. Find the largest possible team size that can be made.
Constraints:
-
You are given an array of integers also queries. For each query of the form you need to find the number of elements from the array such that the value is greater than or equal to . Here is bitwise OR and is bitwise XOR.
Constraints: