Sitting for placements is a huge rollercoster ride, but having some idea of what to expect can make the ride a bit smoother. Here is a brief of some online assessments (patterns, questions & tips) that I either personally gave or heard about from my peers during the season of 2024.
- GreyOrange
- Squarepoint Capital
- AQR Capital
- Graviton Research Capital
- Samsung Research Institute Noida
- Codenation (Trilogy Innovations)
- Deustche Bank
- 26 Miles Capital
- ThoughtSpot
- Alphonso
In addition to reading about the questions from here, please do search for the companies on Leetcode Discuss or Job Overflow. Sometimes people even post about OA questions in Codeforces blogs, so spending a bit of time searching for such questions (from past years or from different campuses) can help you gain an unexpected edge!
PS. I have tried to add the solutions of the problems from the time that I had solved them to as many problems as possible, but they may not be necessarily correct. Please raise an issue here if you find any mistakes, either in the solutions or in the content of the blog!
GreyOrange
- 45 min test with 60 MCQs and 2 coding questions
- MCQs based on basic C++ and OOPS
Coding Questions
- Print a 2D matrix
- Print the second greatest element of an array
Squarepoint Capital
- The company had came for three roles on our campus:
- Quant Desk Analyst
- Software Developer
- Infrastructure Engineer
Quant Desk Analyst
Two coding questions were asked which were same for all the students were asked.
-
A simple implementation of two pointers was to be done, which was described in the question itself. Brute approach needed. LC Easy level.
-
You are given a matrix of size with values between and . In one operation, you can choose any one element, and delete all the elements with the same value in the row and column of the picked element (along with the element itself). Give the minimum number of operations to delete all the elements.
Spoiler
You can read about question 2 here. The question actually turns out to be NP Complete, and thus the best you can do is brute force and try all orderings. In the OA to pass the questions, you had to use the (incorrect) greedy approach, where you would always choose the element whose deletion would result in the maximum number of deletions. To solve it in actual constraints, you can try this on Codeforces.
-
You are given an array of size . You can change any number in the array to any value, and the cost of changing the same is absolute difference of new number and old number. Find the minimum cost to make the array either non-increasing or non-decreasing.
Example:
Spoiler
You can first try solving this similar question and then try to modify the solution to fit the constraints of the question.
-
You are given two numbers and and an array . You need to calculate the number of contigous subarrays with minimum value as and maximum value as . Length of array is upto was .
This problem was a restatement of a problem on Leetcode.
-
You are given an array . You need to remove elements from the array until array gets empty. You can remove either first or last element from the same, with the objective of maximizing the score. Score is calculated in this way:
- Add the array sum to the score if the operation serial number was odd, and then remove an element from the array.
- Subtract the array sum from the score if the operation serial number was even and then remove the element from the array.
The length of the array was upto .
Solution
We can use a DP to solve this problem. Let denote the maximum score that can be obtained by when the first and the last elements have been removed. We can then define the transition as:
Software Developer
Everyone had different questions, but most of them were LC Easy or Medium. The questions often had vague wording so a lot of hit and trial was required to pass the test cases. Questions from the previous years were repeated. Only 2 programming questions were present for one student.
-
You are given a list of words and a search word. For each prefix in the search word (let’s say ), you need to find at max 3 lexicographically smallest words from the dictionary that have the same prefix X.
- Number of dictionary words
- Length of dictionary word:
- Sum(Length of all dictionary words)
- Length of search word:
You can try it out here.
-
A question involving generating unique usernames for all the users on a platform was asked. Only basic string processing was needed, but having vague test descriptions made it difficult to pass the test cases. I had used the debug console to print out the testcases and then tried to guess the output the testcases were expecting. Nasty tricks like trailing whitespaces and wierd ASCII characters were used to make the testcases fail, so you had to be very careful with the output.
Infrastructure Engineer
The test had two sections, one based on Python and two based on Linux.
Linux Section
Remote machines were provided to us, and we had to write the Bash scripts to perform the following tasks. Having access to the server allowed to experiment with the commands and test the scripts before submitting them. The evaluation would happen after the contest, where the script would be used on a similar but new server, and check if all the objectives were met.
-
You need to run a
nginx
Docker container and bind it’s default port to the server’s port . -
You were given a file with the first names and the last name of some users. You need to do the following:
- Read the file
- Create a new user for each user in the file with the username as
F_LastName
whereF
is the first letter of the first name andLastName
is the last name. - Assign all the users to a group named
users
. - Ensure that the users are asked to change their password on the first login.
Python Section
A mock API endpoint was provided, to which we had to make an API call to fetch the data. The response needed to be manipulated and some basic processing of the data items was needed. The response was paginated, so we had to make multiple requests to get all the data. Only basic working experience with Python, and the requests
library was needed for this section.
AQR Capital
- The test pattern is more or less constant across the years.
- 20 MCQs & 2 coding questions
- MCQs are based on Java, OOPS, DBMS and other core CS concepts.
- There is slightly more preference given to Java questions and OOPS.
The coding questions are relatively easy as compared to other companies, but the MCQs are a bit tricky and time-consuming. I would highly recommend practicing MCQs from GeeksforGeeks and other platforms before giving the test. SQL is one of the most important topics for AQR, so make sure you are well-versed with it.
Also, AQR is known for having wierd (more often that not) atleast one wrong test-case in their OAs, so if you finish early and are stuck on the last test-case, it might be better to skip it! In both my intern as well as placement exams, one test-case was wrong in one of the questions. AQR also does not run the same number of test-cases for everyone, so it’s possible that you might get a different number of test-cases than your friend.
PYQs
-
There is a river from point to . You need to cross the river by stepping on stones. There are stones present in the river at the points . During your journey, if the max jump that you make is , and the number of jumps that you make is , then the cost associated with the journey is equal to where is fixed constant. Calculate the minimum cost to cross the river.
- ,
-
Given a DAG with atmost nodes, print the two largest strongly connected components in the graph. Also print the shortest path between the two components. If there are multiple shortest paths, you need to print the path that with “extreme” vertices for the component. (Proper clarifications on the meaning of the “extreme” vertices was not given)
-
MCQ questions based on the following topics were given:
- Marker & Functional Interfaces in Java
- Type of Relationships:
IS
,HAS
&USES
Online Assessment
-
MCQs (18) and Fill-in-the-blanks (2) were asked. The primary topics of the same were:
- SQL
- Java
- Assertions & Exceptions
- Break & Skip Statements
Stream
&ParallelStream
in Java- Static members and methods
- Design Principles
- Single Responsibility Principle (SRP)
- Open-Closed Principle (OCP)
- Liskov Substitution Principle (LSP)
- Interface Segregation Principle (ISP)
- OOPS
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
-
You are given an an array of scores of students. You need to arrange them such that the highest score is the middle, the second highest score is to the left of the highest score, the third highest score is to the right of the highest score, the fourth highest score is to the left of the second highest score, and so on.
Example:
-
The question revolved around calculating the sum of the nodes of a binary tree which had exactly two children. The tree nodes were given in a non-convental way (as a string of
L
andR
characters denoting the path that you need to take to reach the node from the root).
Graviton Research Capital
Graviton is known for it’s subjective tests. It did not visit our campus, but I had a few friends who gave the test. Each test had 3-4 questions, and partial & step marking was present.
PYQs
Software Developer
-
Modify the code snippet to remove all branches (
if
statements):
Solution
We need to add the numbers in the range to , all of which have their th bit always set. Thus if a number’s th bit is set, we can add it to the result, otherwise we can ignore it. We can use the following code snippet to achieve the same:
-
There are datapoints given, each with coordinates . Each data point can spread upto a max distance of units. What is the minimum value of so that all the datapoints can talk to each other? (Two datapoints can talk to each other if the distance between them is less than or equal to . Datapoints can talk in a chain, i.e. if can talk to and can talk to , then can talk to )
Constraints:
- ,
Solution
We observe the fact that if the datapoints can talk to each other at a distance of , then:
- The graph formed by the datapoints is a single connected component.
- All these datapoints would be able to be communicate with each other for any as well.
Thus using these two facts, we can use binary search to find the minimum value of for which the graph is a single connected component. For each value of , we can use loop over all the pairs of datapoints, connect them if the distance between them is less than or equal to and then check if the graph is a single connected component or not (using DFS, BFS or Union Find).
The overall complexity of the solution would be which is feasible for the given constraints.
-
There are players in a game, each with a certain number of gold chips denoted by . The maximum number of gold chips that a player can have is denoted by . You are the player at index and thus initially have gold chips. You can give your gold chips to other players to improve your rank. If a player has more gold chips than its capacity, then that player disqualifies and your rank improves. Find an algorithm to get your best rank.
Solution
We can use a combination of greedy & brute force approach to solve this problem. Let’s say we have decided that we want to eliminate some people by giivng them our gold chips. It would always be ideal for us to give our coins to the player with the lowest value. This exchange would increase our rank by due to elimination, but also might decrease our rank by due to now more player having more coins than me.
We can efficiently simulate all the possible number of coins that we can spend by maintaing two priority queues:
- One to keep track of the players that I can eliminate, ordered by the difference of their capacity and current coins.
- One to keep track of players who have coins lesser than me.
We can then simulate the process of giving coins to the players and updating the ranks. The overall complexity of the solution would be .
This code still requires some better handling around ties and how to determine ranks if two people have the same number of coins, but the general idea is the same.
-
Build a transaction function that may run parallely on multiple cores with the signature:
Solution
The question is not very clear, but the main idea is to ensure that the transaction function is thread-safe. You can use locks to ensure that only one thread can access the function at a time, and we can assume that these locks are available on the
Entity
class itself. A simple implementation would look like:This article can be helpful to understand the concept of mutexes in C++ if you haven’t seem them before. Scoped locks are a neat C++ 17 feature that can be used to lock multiple mutexes at once without the risk of deadlocks.
-
In a bit machine, we subdivide the virtual address into 4 segments as follows:
We use a level page table, such that the first bit is for the first level and so on. Assuming the size of a page table entry as bytes, answer these questions:
- What is the page size in such a system?
- What is the size of a page table for a process that has of memory starting at address ?
-
You are tasked with architecting the CPU pipeline for a hypothetical high-performance processor that must meet the following specifications:
-
A deeply pipelined architecture consisting of stages.
-
The implementation of dynamic branch prediction (e.g., leveraging a hybrid predictor combining both global and local history).
- Describe how you would structure the pipeline stages, focusing on optimizing and balancing the stages for instruction fetch, decode, execution, memory access, and write-back.
- What challenges do you anticipate in managing a deep pipeline of this nature? Propose techniques and strategies to address these challenges effectively.
- Design a branch prediction mechanism suitable for this architecture, discussing how your design would balance prediction accuracy and the associated performance overhead.
-
-
Given an array of integers, we have to split the array into continuous non-empty subarrays. Let’s say there are subarrays and let the subarray be from — both inclusive. Hence a split of the array will satisfy , for , , , for .
Each subarray has a value assigned to it. For a subarray from to , the value is calculated as follows:
- First calculate:
- Then is:
- , if
- , if
- , if
The value of a split of the array is the sum of values of all the subarrays of the split. You are requested to find the maximum value of a split possible (over all possible splits of the array).
Constraints:
-
You are currently trapped in a maze with rooms, which are connected by bridges. Each bridge connects two rooms and has a maximum weight capacity . It breaks if the load exceeds . Bridges can be used to travel in both directions and any number of times (as long as the bridge can hold your weight).
There is one magic fruit in each room, and to escape the maze, you have to eat all the magic fruits (an exit portal opens in the room where you finish eating the last fruit). Eating the magic fruit in room increases your weight by .
You are currently in room number . You realize that with your current weight it might not be possible to escape the maze. So you wonder what is the maximum starting weight with which it is possible to eat all the magic fruits (without breaking a bridge and getting trapped in the maze) to escape.
You can assume that the maze is designed in such a way that you can escape it with some positive starting weight. It is not mandatory to eat the magic fruit the first time you visit a room, and each room can be visited any number of times.
Constraints:
Quant Analyst
-
There is a city with different chambers. Each chamber has at least light bulbs. The total number of light bulbs is even. There is a switch between any light bulbs (both the light bulbs can be in the same chamber or different chambers). Assume some initial configuration of the light bulbs. Is it possible to have a sequence of changes in the switches such that each chamber has both light bulbs (on and off), irrespective of the initial state?
-
There is a lift in a multi-level building. The probability of the lift going up is , going down is and staying still is . At floor , the probability of going up is and staying is . Assume infinite floors in the building. What is the proportion of time you are going to stay at level ?
-
There is a sequence of cards with some facing down and some facing up. If there are cards facing up, then you will flip the card from the left. You keep doing this until all the cards are facing down. Let the total number of cards be .
- Is it always possible to bring all the cards facing down irrespective of the initial positioning?
- If it is possible to face all cards down, what is the expected length of sequence of moves?
-
There is a uniform distribution in the range . Ram and Shyam get numbers from this range at random. Both only know about the number that they have received. The player having a higher value wins. Ram has a chance to redraw another number at random from the distribution. Assuming that both the players play optimally, how many times will Ram choose to redraw?
-
Google wants to pick a new CEO. Mr. Pichai has a list of candidates he can recommend. He has people on the list, each of which has a probablity of being selected as the CEO. You need to help Mr. Pichai maximize the probablity of exactly one candidate getting selected. You need to provide a solution for any and .
-
You are given a tree containing nodes and edges. Assume that each node of this tree is coloured either black or white independently with a probability of . We define as the smallest connected subgraph of that contains all the black nodes. What is the expected number of white nodes in ? ( is between and )
-
There is tree of vertices, labelled to . For every tree, you can assign it a sequence as follows:
-
Let the sequence be empty intially.
-
Take the smallest numbered leaf , remove it from the tree and append the unique neighbour that was adjacent to to the sequence.
-
Repeat the above step until the tree has only vertices.
- Prove that there is a one to one correspondence between the sequence of length and the labelled tree.
- Find the total number of labelled trees of vertices using this reduction.
- Find the number of labelled trees with vertices whose degree of th vertex is where .
-
-
Let be an diagonal matrix with characteristic polynomial where are distinct. Let be the vector space of all matrices such that . Prove that the dimension of is .
-
There are participants in a game, where each of them plays a match against the other. The winner gets point, while the loser gets . In case of a draw, both the players get . It is observed that for every player half of their points come from playing against the bottom ranked players, including these bottom players. Find the value of .
-
There are boxes. You can do operations on them. In each operation, you can either do a take move or a put move. In a put move, $1 is placed randomly into one of the two boxes with equal probability. In a take move, you gain all the money in one of the randomly chosen boxes. What is the maximum expected payout if you play optimally?
-
There are males and females that you need to seat at a round dining table. In how many ways can you seat them so that every man is sitting beside at least 1 woman?
-
Given , , does the series converge?
-
There is a sequence of coins, that have already been flipped. Alice starts checking each coin from the beginning to the end. Bob first checks the coins at even positions, and then the coins at the odd positions. The first one to find 26 heads wins. Who is more likely to win the game?
Samsung Research Institute Noida
- The test is conducted on their own software, which works only on Windows, lags a lot, and is generally quite a pain to work with. You can use their inbuilt IDE, Eclipse or Visual Studio to write the code.
- 3 - 4 hours are given to solve a single question, and the questions are generally on the easier to medium side.
- The questions are primarily from the
Recursion
,Dynamic Programming
,Bitmasking
andGraph Theory
topics. - The questions are very frequently repeated, so it’s a good idea to go through the previous year questions. You can view the same from this very helpful repository.
- Some of the seniors also mentioned that in some tests, the standard library functions were disabled, so you might need to implement them yourself. Some common topics to brush up upon before the test include:
- Sorting Algorithms
- Heaps and Priority Queues
- Queue and Stack
- Custom Comparator Functions
- Arrays (
vector.h
might not be allowed)
Question
There are fishing spots on a lake, numbered from to . There are fishermen waiting to get in. There are gates, located at positions and having employees at gate . The distance between consecutive spots is , and the distance between the gate and the nearest spot is also . Only gate can be opened at a time and all fishermen of that gate must occupy spots before next gate is open. Each fisherman will occupy the nearest spot to the gate greedily. It can be seen that all the employees at a gate will occupy a fixed position, except the last one who might have spots to choose from. Write a program to return sum of minimum distance that the fishermen need to walk.
Constraints:
- It is guaranteed that the fishermen will be able to occupy atleast one spot.
Codenation (Trilogy Innovations)
- 2 hour test is conducted with 4 questions
- The company is known for asking very diffcult questions. There is partial marking for the test cases.
- Questions are very frequently repeated across the campuses in the same year, and not so much with the previous years.
Other Campus Questions
-
An array is considered valid if there is no subarray longer than where all elements are identical. Additionally, the array can only contain integers from the range . Determine the number of valid arrays of length . Since the result can be very large, return it modulo .
Problem Constraints:
Solution
If the array length was upto , then we could have used a simple DP solution where we can define as the number of valid suffixes starting from index . As a part of the transition at index , we can take the new element to occur times (between and ), and thus add the value for . Further, the number of possible values of this new element would be if the index is , and would be otherwise (as it cannot be equal to the previous element). The overall complexity of this solution would be .
But this solution is not feasible for . We will make use of binary matrix exponentiation to solve this problem.
Let us maintain a matrix of size where at any point denotes how many valid arrays exist with the last element of the array occuring times for the current length . We can then define the transition to the next matrix representing the length as:
- For , we can a new element (with possible values) to each of the elements in the previous array. Thus .
- For , we can only transition using the same element as the previous one. Thus .
We can see that these transitions are independent of the vlaue of !
Using these facts, we can define a transition matrix of size to denote the number of ways to transition from current length to the next length .
Then we can set the state for the initial matrix of length as and for . We can then calculate the matrix for length as .
The overall complexity of this solution would be where is the complexity of matrix multiplication and is the complexity of matrix exponentiation.
-
Given is the pseudocode below to find a target number between and (both inclusive):
You are required to answer queries, where in each query, you will be provided with values and . For each query, determine what is the probability that the above code will fail to print “Found” when any value (where ) is chosen?
Express this probability as an integer where the fraction is and . You should compute modulo , where is the modular inverse of modulo .
Problem Constraints:
Solution
It can be observed that the output of the code only depends on the length of the array that we are searching in, and the actual values of and are irrelevant. Thus we can simplify the problem to finding the probability that the code will fail to print “Found” for an array of length .
Let us calculate the value where denotes the number of values of such that the code will print
Found
for an array of length . It can be seen that in the base case (as the algorithm chooses the wrong endpoint in these cases).For , we can see that the code will always print
Found
for the middle element of the array. After that the problem would be reduced to counting the number of valid values in the left and right subarrays. Thus we can define the following recursive formula:- If is even, then as is the number of elements in the left subarray, and is the number of elements in the right subarray.
- If is odd, then as both the left and right subarrays would have the same number of elements.
Once we have these counts, finding the required probability is trivial.
-
You are given an array consisting of integers. You are also given queries. Each query consists of three integers , , and . For each query find the largest contiguous subarray starting from index , whose th bit is set, and then update each of its elements with where denotes the bitwise XOR operator.
Your task is to print the total number of updates performed after queries. Given a array that represents the queries:
Problem Constraints:
Solution
This question is quite an exercise on segment trees with lazy proportion & binary search. Let us create segment trees, on for each bit in the number of the arrays. This segment tree needs to support the following operations:
- Getting the sum of the elements in a range. This can be done using the standard segment tree.
- Flipping all the values in a range. This can be done using the lazy propagation technique and setting the value of a tree node to where is the length of the range and is the current value of the node (this shows that all the s in the range are flipped to and vice versa).
Now, wherenever we get a query, we can do the following:
- Perform a binary search to find the rightmost index where the th bit is set. When checking for an index starting from , we need to check that where is the sum returned by the segment tree of bit .
- Then for all the bits set in , we can flip the values in the range for the segment tree of bit .
The overall complexity of the solution would be , which requires careful implementation to pass the time limits.
-
You are a book collector aiming to sell your collection of books. The books are arranged in a line with the th book to the left of the th book. The thickness of each book is represented by an array (where is the thickness of the th book) and each book has a unique thickness.
To enhance the appeal of your books, you can apply a special protective covering to some of them. However, this cover is expensive and thus you want tp minimize its use while ensuring the following conditions are met:
- You should apply the cover to at least one book.
- If you apply the cover to the th book, you must also apply the cover all books that are thicker than the th book.
- There must exist at least one subarray (contiguous segment) of books of size at least such that the number of books with the protective cover is greater than the number of books without the cover.
Your task is to determine the smallest number of books on which you should apply the protective cover to satify the above conditions.
Problem Constraints:
Solution
Let us fix the minimum thickness of the book that we must cover as . It can easilu be argued that if there exists a subarray satisfying the third condition for , then the same subarray would also be valid for all . This gives us the idea that we can binary search on the minimum thickess hoping to maximize the same.
To check if there is a subarray that satifies condition 3 for a particular , we can make the following construction: Create a new array where if else it is . Now the third question reduces to finding if there is a subarray of atleast size in such that the sum of the elements in the subarray is greater than .
This is a pretty standard problem which can be solved with the concepts of prefix sums and minimums (Reading about 2 Sum problem on Leetcode and all it’s possible extensions) in time. Thus the overall complexity of the solution would be where is the maximum thickness of the book.
-
The teacher in Bitland writes the numbers from to (inclusive) on Blackboard. Now, he gives the following task:
- Choose some numbers (possibly all or none) from the blackboard.
- The bitwise XOR of the chosen numbers should be equal to (If you pick no elements, bitwise XOR is considered to be ).
- The count of chosen numbers should be maximum.
- If there are multiple possible options which yield maximum count, then choose the one with minimum sum.
- If there are still multiple possible options, choose the one which is lexicographically smallest.
Problem Constraints:
-
You are a librarian, and after a long day, you decide to collect all the books kept on tables. In front of you, there are several stacks of books. denotes the size of the th stack of books. In one move you can pick an existing stack and merge it with another stack of books. The efforts required for this task is the size of stack being added. You have also decided that for any stack you will not add books to it for more than times added to any other stack. What is the minimum effort required to collect all the books in one stack?
Problem Constraints:
Questions
-
A cryptarithm is a mathematical puzzle where the goal is to find the correspondence between letters and digits such that the given arithmetic equation consisting of letters holds true. Given a cryptarithm as an array of strings , count the number of its valid solutions.
The solution is valid if each letter represents a different digit, and the leading digit of a multi-digit number is not zero. The cryptarithm contains only capital letters and does not contain any leading zeros. has the following structure: , which stands for the cryptarithm. Is is guranteed that the length of the cryptarithm is .
Constraints:
-
You are given a string of the form
a/b+c/d
where are integers upto . You need to calculate the value in the simplest form as where and are coprime integers. Return a string of the formp/q
. -
You are given an array called where denotes the balance of the th account. You are also given an array where denotes the th transaction request. Each transaction request is a string of the form
timestamp [withdraw|deposit] amount accountIdx
. You need to process these requests subject to the following conditions:- The timestamps are processed in increasing order & in seconds.
- A transaction may be invalid if the account balance is less than the amount to be withdrawn or the
accountIdx
is invalid. - As soon as you encouter an invalid transaction, you need to stop processing the requests. If the based index of the first invalid transaction is , you need to return a vector with a single element equal to .
- If all the transactions are valid, you need to return the final balance of all the accounts.
- The bank has an additional offer. Whenever amount is withdrawn from an account, the bank automatically credits a cashbacks to the account after hours of the withdrawn.
- Return the balances just after processing the last transaction, and do not wait for the pending cashbacks (if any) to complete.
-
You are given two
ListNode
heads and . Each list represents a huge number, and each list node represents exactly digits of the number. You need to return the sum of the two numbers as a linked list. The numbers may have leading zeros. (For example, if then it actually represents the number )
Deustche Bank
Other Campus Questions
A lot of these questions have been mixed with questions that were asked in the internship season of 2024 for Deustche Bank!
-
You are given a binary string of length . What is the largest prime number whose binary representation can be formed by deleting some digits from the string ? The length of the string is at most .
Solution
Since the length of the string is at most , we can generate all the prime numbers up to and store their binary representations in a trie. Then, we can perform a DFS on the trie to find the largest prime number that can be formed as a subsequence of the given string, by greeding selecting the next bit from the string.
Time Complexity:
On second thought, we have a simpler implementation available since is small. We can directly use bitmasks to generate all the subsequences of the provided string and check if the number formed by the same is prime or not. The complexity of this solution would be where .
-
You are given a string of length containing only the characters and . Find the lexographically smallest subsequence of of length with atleast ‘s. Return an empty string if no such subsequence exits.
Constraints:
Solution
Take the characters from the end of the string as much as possible, and then take the characters from the beginning of the string as much as possible. There is some edge case handling required related to the count of the characters. The time complexity of the solution is .
-
You are given a grid of size containg some free cells (marked as
.
) and some blocked cells (marked as#
). You take minute to travel from one cell to the other. You can only move horizontally or vertically. You are given the coordinates of the starting cell and the ending cell. Find the minimum time required to reach the ending cell from the starting cell.Constraints:
-
A number is called beautiful if it atleast contains one bit as , and atmost bits as in it’s binary representation. Given multiple queries of the form , find the sum of the cubes of all the beautiful numbers in the range . Print the sum modulo .
Constraints:
Solution
We can use a simple brute force to generate all the possible beautiful numbers, and then use prefix sums and binary search to calculate the sum of the cubes of these numbers in any range. The time complexity of the solution is where is the total number of beautiful numbers ().
Extension
If the question revolved around finding the number of beautiful numbers in the range , or just the sum of all the beautiful numbers in the range , then we could have used a simple digit DP based approach to solve the problem (as addition is distributive over modulo operation). The time complexity of the solution would have been .
-
You are given an array and who empty arrays and . The array is a permutation of length . In one operation, you can do one of the following:
- Remove the element from the starting of and add it to the end of .
- Remove the element from the starting of and add it to the end of .
- Remove the element from the starting of and add it to the end of
Determine if it is possible to obtain the sorted permutation in the array .
Constraints:
Solution
We will use a greedy approach, where we will try to find the currently needed element from both and , and if not found, we would move the elements from to in hopes of finding the currently required element. The time complexity is .
-
You are given a tree with nodes rooted at . In one operation, you can break any edge of the tree. Even after breaking the edge, the original parent-child relation between the nodes will hold. Minimize the number of operations needed to be performed so as convert the tree into a valid -nary tree. After minimising the operations, also return the maximum size of the tree possible.
Solution
-
You are given a tree with vertices, and each vertice has a colour as or . For a node, we define the beauty of the vertex as the number of paths in the subtree of the node that have different colours of the ending points. Find the beauty of each node in the tree when the tree is rooted at vertex .
Solution
We can perform a simple DFS to calculate the number of nodes with colour and colour in the subtree of each node. The beauty of a node is then the product of the number of nodes with colour and colour in the subtree of the node. The time complexity of the solution is .
-
Given a sequence of integers , you need to perform the following operation and return the obtained result.
- For a given integer , calculate the value of the expression , where is the rightmost number with the highest number of distinct prime factors in the sequence .
Constraints:
Solution
We can use the Sieve of Eratosthenes to compute the number of distinct prime factors of each number in the sequence. Then, we can use a sliding window of size and a priority queue to find the rightmost number with the highest number of distinct prime factors in the window. The priority queue would store the number of divisors of the element as well as it’s index. The time complexity of the solution is where is the maximum value of .
-
A function is defined as the sum of all the divisors for the number . The function is defined as the sum of for all the divisors of . Given two numbers and , find the sum of for all the numbers in the range modulo .
Constraints:
Solution
We can use a simple sieve like approach to calculate the sum of divisors of all the numbers in the range . Then, we can again apply this sieve like approach to the sum of divisors to calculate the sum of for all the numbers in the range . The time complexity of the solution is .
This approach can easily be extended with precomputation to calculate the sum of for all the numbers in the range in time for multiple queries.
-
Given an array of size containing integers, find the minimum possible sum of that can be formed be adding the elements in the array. You can perform the following operation at most once:
- Select an index. If the sum of all the elements in the array up to the selected index is a multiple of the element present at the index. divide the sum up to the selected index by the element present at the index.
- After dividing, you do not have to add this element to the resultant sum.
- After this operation is performed, you will have to add the remaining elements to the resultant sum.
- Note that the chosen index is excluded from the prefix sum and the suffix sum. If the chosen index is , then it should be included in the prefix sum.
Constraints:
Solution
We can use a prefix sum and a suffix sum to calculate the sum of all the elements in the array. Then, we can iterate over all the elements in the array and calculate the sum of all the elements in the array excluding the current element. The time complexity of the solution is .
-
Given an integer array of integers of length , find the largest possible value such that atleast elements of the array are divisible by the same.
Constraints:
Solution
We can precompute all the divisors of all the numbers upto using the Sieve of Eratosthenes. Then, we can iterate over all the divisors of any number in the array, and check if it a valid divisor satifying the condition. Since a number till can have atmost divisors, this solution would work in time where is for precomputation. We would need careful handling of the case when the numbers are , and a streamlined implementation to avoid TLE in a second time limit.
-
You are given two integer arrays and of length consisiting of non-negative integers. You have to select numbers from , and then take the bitwise OR of all the elements of one at a time with each of the selected elements. The score of this operation is the sum of the bitwise OR operations. Find the minimum value of such that a score of atleast can be achieved.
Constraints:
-
Solution
-
You are given three arrays , and , which represents that the client was making requests to the server per second for the duration . Find the minimum requests per second that this server should be able to handle to serve all the requests.
Solution
We can use a line sweep algorithm to solve this problem. We can iterate over all the requests and add the requests to the server at the start time of the request, and remove the requests from the server at the end time of the request. We can then iterate over all the times and calculate the number of requests that the server should be able to handle at that time. The time complexity of the solution is .
-
You are given the initial positions of Alice and Bob as and . You are also given apples at the positions . Alice and Bob need to collect all of the apples in the order they are given. The distance between the two points is the Manhattan distance. Find the minimum distance that Alice and Bob need to travel to collect all the apples.
Constraints:
Solution
We can use a simple Djikstra to solve this question where the state is represented as , where is the index of the apple that Alice is currently at, and is the index of the apple that Bob is currently at. The time complexity of the solution is .
-
Count the number of periodic subsequences of a string of length .
- A string is periodic if for all valid indexes in the string.
- An empty string is also periodic.
Constraints:
Solution
Since the value of is small, we can just generate all the subsequences and check if it is periodic. The time complexity of the solution is .
-
Given an undirected tree with nodes such that there exists a path between any two nodes. For the node, a positive integer value is associated with it. You also have a special positive integer and you may perform the following operation zero or more times on the given tree: Choose an edge and update the value of the nodes connected with that edge with bitwise XOR of its current value and . Formally, for all connected to the chosen edge. Find the maximum value of if you can perform the above operations any number of times.
Solution
It can be realized that the structure of the tree does not matter, and the only effective constraint that we have is that we can take the XOR of the nodes with in pairs only (you can do so by applying the operation on all the edges in the path between the two chosen nodes). Thus, we can use a simple greedy approach to solve this problem. The time complexity of the solution is due to sorting.
-
You are given an array of elements. For each index , find the length of the smallest subarray starting at the index and having a non-negative sum. If there is no such subarray for an index, set the answer as for that index.
Constraints:
Solution
We will use a stack to solve this problem. We will iterate over the array from left to right and maintain a stack of indices that have not found a valid subarray for them. Whenever we get an element, if it is non-negative we can set it’s answer as directly and try to pop the elements from the stack that be paired with the current index. If we get a negative element, we will push the index to the stack always.
We will maintain prefix sums to do this computation in constant time for each index. The time complexity of the solution is .
-
Solution
In such questions, often the trick is to fix the middle elements. Thus we will brute force over the pairs of and then find the number of elements less than and greater than in the range and respectively. Counting the number of elements less than or a greater than a particular number in a range is typically done with a merge sort tree, but since here the elements are given to be in the range , we can use simple precomputation to solve the problem. The time complexity of the solution is .
-
You are given a directed tree of nodes in the form of an array such that there is an edge from the node to the node for . In one operation you can break any edge of this tree, and thus divide the same into two subtrees. Apply this operation repeatedly so that each of the final subtrees is a directed chain, and the total sum of the squares of length of each directed chain is maximized. Return the maximum possible sum of the squares of the lengths of the directed chains. It is gaurenteed that all the nodes are reachable from the root node .
Constraints:
Solution
It is clear that we should follow a greedy approach where we try to maximise the length of each of the chains. Since the chains are directed, we will intially take the longest paths from the root node to the leaves, and then try to maximise the length of the chains on the other edges. Refer to the following code for the implementation. The time complexity of the solution is .
-
There is an empty container. You want to support 2 types of queries:
1 V X
: Insert an element in the container with value and weight .2 V 0
: Let be the number of bits in the binary representation of . Consider all the elements in the container till now. You need to count the number of elements which when divided by have a remainder of , and also return the sum of the weights of these elements.
Constraints:
- If the query is of type , then
- If the query is of type , then
Solution
Since a number upto can have atmost bits, we can maintain the count of different modulo values and the sum of powers for each possible length of the binary representation of the number. We can use a map to store the count of different modulo values and the sum of weights for each length of the binary representation of the number. The time complexity of the solution is .
-
You are given two binary strings and of length consisting of only and . Consider a non-empty substring of and a non-empty substring of of the same length. Let be the string obtained as the XOR of and .
The score of these two strings is defined as where is the decimal representation of and is the length of the string .
Find the maximum possible score that can be obtained by choosing the strings and .
Constraints:
Solution
The key observation is that since the score is defined as , the numerator of the fraction can be at max . To have a non-zero score, the value of must be less than or equal to , then the value of must be less than or equal to . Thus, we can be sure that the binary representation of will have at most bits (without non-leading zeroes). To compute the number of leading zeroes in the number at every position, we can use a simple precomputation. The time complexity of the solution is .
-
You are given an array of length , where the element represents a chocolate of length . When you merge two chocolate of lengths and , cost of merging is , and the resultant chocolate length becomes and is replaced in the array. You need to apply these operations until there is only one chocolate left in the array. Find the minimum cost of merging. The expected time complexity of the algorithm should be .
-
You are given two arrays and of same length . You need to find a subset of the indexes , such that for any two entries in the subset, say and the following conditions holds:
- If then
- If then
Return the maximum length of the subset possible.
-
You are given a tree of nodes. You are given queries where each query has three arguments: node , node and a number . You need to consider the path from to , and take the XOR of all the nodes in the path and check if it is equal to the given . You can exclude atmost one node from the path so that the XOR becomes equal to . Return
true
if the same is possible elsefalse
for each query.Constraints:
Solution
It is clear that if the XOR of the nodes from to is equal to , then we can simply return
true
. If the same is not true, then we need to check if there is a node in the path from to where is the XOR operation (as we can exclude this node from the path to get the desried result). To support both of these queries effeciently, we will make use of Mo’s algorithm. The time complexity of the solution is .An alternative solution for the problem involves the use of Heavy Light Decomposition, but I personally find Mo’s algorithm to be more intuitive and easier to implement in online assessments.
Online Assessment Questions
-
You are given a string and an of integers, both of length . You can swap indexes and of the string if . Find the lexographically smallest string you can obtain after performing some (possible zero) swaps.
-
There are types of objects, and each has a cost denoted by . In some operations, you can either:
- Choose an index , pay and get object of type .
- Pay cost , and transform all the objects of type to type . The object of type is converted to type . The cost of the objects is only related to their index and not their type.
Find the minimum cost to get object of each type.
Solution
Suppose that you perform the second operation times. Then you would need to add the fixed cost to the total cost. After that, for each object of type , you would be able to buy it in the minimum of the cost in the range to . Thus loop over the number of times you perform the second operation and find the minimum cost using sliding windows for each object of type . If you use a set with the sliding window, the complexity is which passed comfortably.
-
You are given an array of strings . A permuation of the is called valid if for any two strings in the array that have a common prefix, all the strings between them also have atleast that common prefix. For example, the ordering
[a, aa, aab]
and[a, aab, aa]
are both valid, but[hi, ho, hi]
is not. Find the number of valid permutations of the array.-
-
-
Example #1
For the array["a", "aa", "aaa", "aaaa"]
, the answer is . -
Example #2
For the array["ivo", "ja", "jo"]
, the answer is .
Solution
This question can be solved with the help of a trie. Each prefix of a word denotes a split point, where all the next nodes can be arranged in any specific order. We would also need to add an extra dummy character to denote the end of the word. In the OA, when using pointers to allocate the memory for nodes of the trie, a
MLE
verdict was given. Thus, we need to use a vector of nodes to store the trie nodes. The time complexity of the solution is where is the maximum length of the string. -
26 Miles Capital
There were questions in the test, which had to be solved in minutes. Out of the same, were coding questions which were different for each candidate. The rest of the questions were MCQs from the topics of finance, probablity, data interpretation, and logical reasoning. The MCQs were also shuffled between the candidates.
Coding Questions
-
Find all the distinct palindromic substrings of the given string . The length of is upto .
Solution
You can fix the center of the palindrome, and then iterate creating odd and even length palindromes from that center. The time complexity of the solution is . To find the unique palindromes, you can use rolling hash to convert all the substrings to a number in constant time and push them to a set, thus adding an additonal factor to the runtime. As luck would have it, the test cases of the questions were weak, and a solution where I generated the substring between the two indexes and then pushed it to a set passed the test cases.
-
You are given an unidirected tree of nodes, where each node has a value which is rooted at node . In one operation, you can select a node and delete the entire subtree of that node (along with it). The cost of one such operation is . The final score of the tree is the sum of the values in the tree after all the operations minus the total cost of the operations. What is the maximum possible score that can be obtained?
-
You are given a string that contains spaces, commas, brackets, , and logical operators such as
&
,|
and!
. The string given will always represent a valid boolean expression in prefix notation, and would be bracketted appropriately to convey the precedence. Find the value of the boolean expression.- Example:
| [& [! 1] 0 [! [! 0]]] [& 0 0]
would evaluate to0
.
- Example:
ThoughtSpot
Other Campus Questions
-
Count the Number of Palindromic Paths in a Tree
Solution
-
Determine the number of integers in the range such that they have no repeating digits. Each test file has queries.
Constraints:
-
Given two integers , determine the number of integers in the range such that they are a power number. A power number is a number that can be expressed as where are positive integers and and .
Constraints:
Solution
-
Minimum Swaps to Make the String Balanced
Solution
-
The office manager of a healthcare billing company has been charged with eliminating food waste in the office lounge. The lounge has packets of coffee creamer, each with an expiry date. The creamer must be used no later than that day. The manager also has the option to order additional coffee creamer from a grocery store, each with varying expiry dates. Given a fixed daily demand for creamer, find the maximum amount of additional creamer the manager can order without waste.
Example:
Constraints:
Solution
-
There are in processes to be executed, and the process has a size of . Also, there are processors of different size capacity. The capacity of the processor is . A processor can process a task of size less than or equal to it’s capacity in second, but it can not execute processes whose size is greater than it’s capacity. A processor can execute multiple processes one after the other, but needs to pause for second after completing it’s current one. Multiple processors can work on different processes simultaneously. Find the minimum time to execute all the processes or return if there is no way to execute all the processes.
Constraints:
Solution
-
Two strings are given, and . Some of the characters in word are a question mark (
?
). Find the lexicographically smallest string that can be obtained by replacing?
characters such that appears at least once. If it is not possible to do so, return “-1”.Constraints:
- and contain only lowercase English letters and
?
Solution
Additional Follow Up: Can you solve this problem in the same constraints if the same was asked for the pattern to appear as a subsequence in the string?
-
You are given a tree with nodes. Each node has a value denoted by . Consider all the simple paths in the tree, and return the maximum possible sum of the values of the nodes lying on any path on the tree.
Constraints:
Solution
-
There is a tree with nodes. The tree is rooted at node with number . As usually in computer science, the tree grows upside down comparing to trees existing in nature. Apples grow on nodes of this tree. Some of these apples are underhydrated, some are overhydrated, and others are neither. You know that for each overhydrated apple you’ll get cents penalty and for every underhydrated you’ll get cents penalty. Now, you want to pour water on exactly one node of the tree. When you pour water on node all apples that are in node’s subtree, i.e., itself and all descendants of the node will be hydrated and in consequence, each hydrated apple that was almost overhydrated becomes overhydrated. Moreover, every apple in the whole tree that was almost underhydrated and no water was poured on it gets underhydrated. Calculate the minimum total penalty you can get from pouring water on exactly one node of the tree.
You are given:
- An integer array, of size where denotes the parent of the node.
- An integer array, of size where , denotes the level of the water in the apple on node. It’s either , or , where stands for almost underhydrated, stands for neither and stands for almost overhydrated.
- Integers and denoting the penalty for overhydrated and underhydrated apples respectively.
Constraints:
Solution
-
You are given items, each characterized by three values , where is the type number of the item, is the weight of the item and is the value of the item. You can carry atmost a weight of . Determine the maximum value of the items you can carry subject to the condition that you can not take two items of the same type together.
Constraints:
Solution
Online Assessment Questions
-
Solution
-
You are given a weighted undirected tree of nodes. A pair of nodes can communicate via a third node if and only if the distance of and and the the distance of to are both divisible the by the given constant . For each node, calculate the number of pairs of nodes that can communicate via it.
Constraints:
-
You need to implement a text editor. Intially the string on the screen is empty, and the cursor is at the position. Next the following type of queries would be made to the same:
insert s
: Insert the string at the current cursor position. The cursor moves to the end of the inserted string.print x
: If the cursor is at the position, print the characters in the range .left x
: Move the cursor positions to the left.right x
: Move the cursor positions to the right.backscape x
: Delete the last characters from the screen with respect to the cursor position.delete x
: Delete the next characters from the screen with respect to the cursor position.
All the cursor positions may go out of bounds. You must handle them as any regular text editor would. It is given that the number of queries would be at most and the length of the intermediate text on the screen would never exceed characters.
Alphonso
Other Campus Questions
-
You are given a tree with nodes and a number . The tree is rooted at . You need to assign each node a value in the range to . The so formed tree is called beautiful if the GCD of the values on the path from the root to atleast one leaf node is greater than . Find the number of beautiful trees. Output the same modulo .
Solution
Online Assessment Questions
-
You are given a binary tree with nodes. You need to answer on the same. Each query involves remvoing the subtree of the node and then finding the maximum value present in the tree. Output the same for each query. All the queries are independent of each other, and thus the tree restores to the original state after each query.
Constraints:
-
You are given an array of integers. You want to change the array so that all the elements in the array are unique, and when the array is sorted, the element are consequtive integers. In one operation, you can change any one element of the array to any value that you want. Output the minimum number of operations required to make the array unique and sorted.
Constraints:
-
You are given boxes of the form where is the size of the box, and is the type of the box. You are also given items, each of the form . You are pack an item in a box only if the sizes of the box and item are equal. The packing is called optimal if the type of the box and the item are equal as well. You need to find the maximum number of items that can be packed, and how many of these items can be packed optimally.
Constraints: