Morgan Stanley
200+ Magnate Architectural Auxiliary Services Interview Questions and Answers
Q1. What was the journal entry for prepaid rent which has paid at beginning of the month for the whole year and entry at the end of month ?? Which is entry affects the networth??
Journal entry for prepaid rent paid at beginning and end of month affecting net worth.
Debit prepaid rent account for the full amount paid at the beginning of the month
Credit cash account for the same amount
At the end of the month, debit rent expense account for the portion of rent used during the month
Credit prepaid rent account for the same amount
The entry at the end of the month affects the net worth as it reduces the prepaid rent asset and increases the rent expense
Example...read more
Q2. What is the entry for share purchased today which will be credited into demat on T+2?
The entry for share purchased today credited into demat on T+2 is a debit to the cash account and a credit to the demat account.
Debit cash account
Credit demat account
Occurs on T+2
Reflects purchase of shares
Q3. Sort Big List Dates Problem Statement
Mary is an enthusiastic party-goer who struggles with remembering event dates. Help Mary by sorting a given list of event dates in an ascending order.
Example:
Input:
dates...read more
Sort a list of event dates in ascending order based on year, month, and day.
Sort the list of dates based on year, then month, and finally day.
Use a sorting algorithm to rearrange the dates in ascending order.
Ensure the constraints are met for each date in the list.
Q4. What impact do share price have on issue of dividend ? And what was the reason behind it?
The share price has an impact on the issue of dividends as it affects the dividend yield and the amount of cash paid out to shareholders.
Share price affects the dividend yield, which is calculated by dividing the annual dividend per share by the share price.
A higher share price reduces the dividend yield, making the stock less attractive to income-seeking investors.
Share price also affects the amount of cash paid out as dividends. A higher share price may result in a lower di...read more
Q5. Max Element After Update Operations
Given an array A
of size N
, initialized with all zeros, and another array ARR
of M
pairs of integers representing operations. Each operation consists of a range where each el...read more
Find the maximum element in an array after performing a series of increment operations on specified ranges.
Initialize an array of size N with all zeros
Iterate through the operations and increment elements within specified ranges
Return the maximum element in the array after all operations
Q6. Given a web portal that is running slow, how would you debug the solution for that? Answer stepwise.
Debugging steps for a slow web portal
Check server load and resource usage
Analyze network traffic and latency
Review code for inefficiencies and optimize
Use profiling tools to identify bottlenecks
Consider caching and content delivery networks
Test and monitor performance after changes
Q7. Counting Distinct Elements in Every K-Sized Window
Given an array ARR
of size N
and an integer K
, determine the number of distinct elements in every K-sized window of the array. A 'K' sized window is defined as...read more
Count the number of distinct elements in every K-sized window of an array.
Use a sliding window approach to keep track of distinct elements in each window
Use a hashmap to store the frequency of elements in the current window
Update the hashmap as you slide the window to the right and maintain the count of distinct elements
Return the count of distinct elements for each window
Q8. Sort 0 and 1 Problem Statement
Given an integer array ARR
of size N
containing only integers 0 and 1, implement a function to sort this array. The solution should scan the array only once without using any addi...read more
Implement a function to sort an array of 0s and 1s in linear time complexity without using additional arrays.
Iterate through the array and maintain two pointers, one for 0s and one for 1s.
Swap elements at the two pointers to sort the array in place.
Time complexity should be O(N) where N is the size of the array.
Q9. Find Shortest Path in a Tree
Given a tree with 'N' nodes and 'N - 1' distinct edges, along with two nodes 'N1' and 'N2', find and print the shortest path between 'N1' and 'N2'.
Explanation:
A tree is a nonlinea...read more
Find the shortest path between two nodes in a tree.
Use BFS to traverse the tree and find the shortest path between the two nodes.
Maintain a parent array to backtrack from the target node to the source node.
Output the path by backtracking from the target node to the source node using the parent array.
Q10. Pair Sum Problem Statement
You are given an integer array 'ARR' of size 'N' and an integer 'S'. Your task is to find and return a list of all pairs of elements where each sum of a pair equals 'S'.
Note:
Each pa...read more
Given an array and a target sum, find all pairs of elements that add up to the target sum.
Iterate through the array and for each element, check if the complement (target sum - current element) exists in a hash set.
If the complement exists, add the pair to the result list.
Sort the pairs based on the first element and then the second element.
Handle edge cases like duplicate elements and pairs with the same values.
Example: For input N=5, S=7, ARR=[3, 1, 2, 4, 5], the output shou...read more
Q11. Maximum Sum Problem Statement
Given an integer N
, your task is to recursively break it into three integer parts: N / 2
, N / 3
, and N / 4
. You need to compute the maximum sum possible by dividing the number furt...read more
Given an integer N, recursively break it into three parts and find the maximum sum possible.
Recursively divide N into N/2, N/3, and N/4 to find the maximum sum
Compare the sum obtained by dividing N with the sum of N itself
Return the maximum sum for each test case
Q12. Weight Capacity for Shipment in D Days
You are tasked with managing a shipment company that utilizes conveyor belts to transport packages from one port to another. These packages must be shipped within ‘D’ days...read more
Calculate minimum weight capacity needed to deliver all packages within 'D' days.
Iterate through the array of weights to find the maximum weight
Use binary search to find the minimum weight capacity needed
Check if the total weight loaded each day does not exceed the ship's maximum weight capacity
Q13. Can you explain dcf to me? Can dcf be applied to equity?
DCF is a valuation method used to estimate the value of an investment based on its future cash flows.
DCF involves projecting future cash flows and discounting them back to their present value.
It can be applied to equity by estimating the future cash flows of a company and discounting them back to their present value to determine the company's intrinsic value.
DCF is commonly used in investment banking and finance to value companies and assets.
It is important to use realistic a...read more
Q14. Minimum Number of Vertices to Reach All Nodes Problem Statement
In a directed acyclic graph with 'N' nodes, given a matrix 'edges' of size M x 2 representing 'M' edges where each edge is directed from node edge...read more
The problem involves finding the smallest set of vertices from which all nodes in a directed acyclic graph are reachable.
Create a directed graph using the given edges.
Perform a topological sort to find the vertices that can reach all other nodes.
Output the smallest set of vertices in sorted order.
Q15. Given an array with length n , find highest value which occurs same number of times within the array. [3,8,3,2,1,3,2] 3 occurs 3 times output=3. [4,6,7,6,7,5,4,2,4,9,4,1,9] 4 occurs 3 times output=4
Find the highest value that occurs the same number of times within an array.
Iterate through the array and count the occurrences of each value.
Store the counts in a dictionary or hash map.
Find the maximum count and check which value(s) have that count.
Return the highest value among those with the maximum count.
Q16. What is the technical term we use for the bond interest
The technical term for bond interest is coupon rate.
Coupon rate is the fixed annual interest rate paid on a bond.
It is expressed as a percentage of the bond's face value.
For example, a bond with a face value of $1000 and a coupon rate of 5% will pay $50 in interest annually.
Coupon payments are usually made semi-annually or quarterly.
Q17. Candies Distribution Problem Statement
Prateek is a kindergarten teacher with a mission to distribute candies to students based on their performance. Each student must get at least one candy, and if two student...read more
Determine the minimum number of candies needed to distribute to students based on their performance and ratings.
Iterate through the array of student ratings and assign 1 candy to each student initially.
Then iterate from left to right and check if the current student's rating is higher than the previous student, if so, assign candies accordingly.
Similarly, iterate from right to left to handle cases where the current student's rating is higher than the next student.
Keep track o...read more
Q18. Bubble Sort Problem Statement
Sort an unsorted array of non-negative integers using the Bubble Sort algorithm, which swaps adjacent elements if they are not in the correct order to sort the array in non-decreas...read more
Bubble Sort is used to sort an array of non-negative integers in non-decreasing order by swapping adjacent elements if they are not in the correct order.
Iterate through the array and compare adjacent elements, swapping them if they are in the wrong order.
Repeat this process until the array is sorted in non-decreasing order.
Time complexity of Bubble Sort is O(n^2) in worst case.
Example: For input [6, 2, 8, 4, 10], the output should be [2, 4, 6, 8, 10].
Q19. Topological Sort Problem Statement
You are given a directed acyclic graph (DAG). Your task is to perform topological sorting of the graph and return any valid ordering.
Explanation:
A directed acyclic graph is ...read more
Implement a function to perform topological sorting on a directed acyclic graph (DAG) and return any valid ordering.
Create a graph data structure to represent the DAG
Use depth-first search (DFS) to perform topological sorting
Maintain a visited array to keep track of visited nodes
Return the ordering of nodes after DFS traversal
Q20. Next Greater Number Problem Statement
Given a string S
which represents a number, determine the smallest number strictly greater than the original number composed of the same digits. Each digit's frequency from...read more
Given a number represented as a string, find the smallest number greater than the original with the same digits.
Iterate from right to left to find the first digit that can be swapped with a smaller digit on its right.
Swap this digit with the smallest digit on its right that is greater than it.
Sort the digits to the right of the swapped digit in ascending order to get the smallest number.
If no such number exists, return -1.
Example: For S = '56789', the output should be '56798'...read more
Q21. Trapping Rainwater Problem Statement
You are given an array ARR
of long type, which represents an elevation map where ARR[i]
denotes the elevation of the ith
bar. Calculate the total amount of rainwater that ca...read more
Calculate the total amount of rainwater that can be trapped within given elevation map.
Iterate through the array to find the maximum height on the left and right of each bar.
Calculate the amount of water that can be trapped above each bar by taking the minimum of the maximum heights on the left and right.
Sum up the trapped water above each bar to get the total trapped water for the elevation map.
Q22. Find the Duplicate Number Problem Statement
Given an integer array 'ARR' of size 'N' containing numbers from 0 to (N - 2). Each number appears at least once, and there is one number that appears twice. Your tas...read more
Find the duplicate number in an integer array containing numbers from 0 to (N - 2).
Iterate through the array and keep track of the frequency of each number using a hashmap.
Return the number that appears twice in the array.
The duplicate number is always present in the given array.
Q23. Unweighted Graph Shortest Path Problem
You are tasked with finding the shortest path between two houses in the city of Ninjaland, represented as an unweighted graph. The city has N
houses numbered from 1 to N
a...read more
Find the shortest path between two houses in a city represented as an unweighted graph.
Use breadth-first search (BFS) algorithm to find the shortest path in an unweighted graph.
Start BFS from the source house and keep track of the shortest path to each house.
Once the destination house is reached, backtrack to find the shortest path.
Consider using a queue data structure to implement BFS efficiently.
Q24. Two Sum in a BST Problem Statement
Given a Binary Search Tree (BST) and a target value, determine if there exists a pair of node values in the BST whose sum equals the target value.
Example:
Input:
4 2 6 1 3 5 ...read more
Given a BST and a target value, find if there exists a pair of node values in the BST whose sum equals the target value.
Traverse the BST in-order and store the node values in a set while checking for the target value difference.
Use two pointers approach to find the pair of values that sum up to the target value.
Consider edge cases like negative values and handling duplicates in the BST.
Q25. Duplicate Integer in Array
Given an array ARR
of size N
, containing each number between 1 and N-1
at least once, identify the single integer that appears twice.
Input:
The first line contains an integer, 'T', r...read more
Identify the duplicate integer in an array containing numbers between 1 and N-1.
Iterate through the array and keep track of the frequency of each element using a hashmap.
Return the element with a frequency greater than 1 as the duplicate integer.
Ensure the constraints are met and a duplicate number is guaranteed to be present.
Q26. How would you find whether a number is even or odd without using any conditions?
Using bitwise operator to check the last bit of the number.
Use bitwise AND operator with 1 to check the last bit of the number.
If the result is 0, the number is even. If the result is 1, the number is odd.
Example: 6 & 1 = 0 (even), 7 & 1 = 1 (odd)
Q27. In how many ways can i permute n numbers 1 2 3...n so that all the no.s between u and i+1 are less than i (for all i in the permutation)?
Counting permutations where numbers between u and i+1 are less than i for all i in the permutation.
The first number in the permutation must be 1.
For each i in the permutation, all numbers between u and i+1 must be less than i.
Use dynamic programming to count the number of valid permutations.
The answer is (n-1)th Catalan number.
Example: for n=4, the answer is 5.
Q28. Longest Substring with At Most K Distinct Characters
Given a string S
of length N
and an integer K
, find the length of the longest substring that contains at most K
distinct characters.
Input:
The first line co...read more
Find the length of the longest substring with at most K distinct characters in a given string.
Use a sliding window approach to keep track of the characters and their counts within the window.
Maintain a hashmap to store the characters and their frequencies.
Update the window size and characters count as you iterate through the string.
Return the maximum window size encountered for each test case.
Q29. Split the String Problem Statement
You are given a string str
consisting of N
lowercase alphabets. Your task is to determine if it is possible to divide the string into three non-empty substrings such that one ...read more
Given a string, determine if it can be split into three non-empty substrings where one is a substring of the other two.
Check if any substring of the string is a substring of the other two substrings.
Iterate through all possible splits of the string and check for the condition.
Use two pointers to find all possible substrings efficiently.
Q30. In a unit circle, p is chosen uniformly on the circle and q inside the circle, what is the prob. that the rectangle is inside the circle?
Probability of a rectangle being inside a unit circle with p chosen uniformly on the circle and q inside the circle.
The probability can be found by calculating the ratio of the area of the rectangle to the area of the circle.
The area of the circle is pi and the area of the rectangle can be found using the distance between p and q.
The probability is 1/4.
Example: If the distance between p and q is 0.5, then the area of the rectangle is 0.25 and the probability is 0.25/pi.
Q31. Given a class @Data class Account{String name; String acctBalance;}. Write logic to get Map using Stream API which shows the balance of each person i,e, key will be the name of the account holder and value will...
read moreLogic to get Map using Stream API to show balance of each person
Use Stream API to group accounts by name
Use map() to get the sum of balances for each group
Collect the results into a Map
Q32. Flatten a Multilevel Sorted Linked List
You are given a linked list with 'N' nodes, where each node contains two pointers: one is 'NEXT' pointing to the next node in the list, and the other is 'CHILD', pointing...read more
Flatten a multilevel sorted linked list while maintaining sorted order.
Iterate through the linked list nodes and maintain a stack to keep track of child nodes.
Merge the child nodes with the parent node in sorted order.
Update the pointers to create a single level flattened linked list.
Q33. Minimum Number of Platforms Problem
Your task is to determine the minimum number of platforms required at a railway station so that no train has to wait.
Explanation:
Given two arrays:
AT
- representing the ar...read more
Determine the minimum number of platforms needed at a railway station so that no train has to wait.
Sort the arrival and departure times arrays in ascending order.
Use two pointers to iterate through the arrays and keep track of the number of platforms needed.
Increment the number of platforms needed when a train arrives and decrement when a train departs.
Return the maximum number of platforms needed at any point.
Example: For AT = [900, 940, 950] and DT = [910, 1200, 1120], the ...read more
Q34. Why RBI increase Repo rate to control inflation ?
RBI increases Repo rate to control inflation by reducing money supply and increasing cost of borrowing.
Repo rate is the rate at which RBI lends money to commercial banks.
When RBI increases Repo rate, it becomes expensive for banks to borrow money from RBI.
Banks then increase their lending rates to customers, which reduces borrowing and spending.
This reduces money supply in the economy, which helps in controlling inflation.
For example, if inflation is high, RBI may increase Re...read more
Q35. What was difference between options and future?
Options give the right but not the obligation to buy or sell an asset at a predetermined price, while futures require the buyer or seller to fulfill the contract at a specific date and price.
Options provide flexibility to the buyer as they can choose whether or not to exercise the option, while futures require the buyer or seller to fulfill the contract.
Options have a premium that the buyer pays to the seller for the right to buy or sell the asset, while futures do not have a...read more
Q36. x, y are random variables with probability distribution ke^(-kx) and ue^(-ux). What is the dist. for min(x,y)
Finding the probability distribution for the minimum of two random variables with given distributions.
Use the formula P(min(x,y)>z) = P(x>z)P(y>z)
Integrate over the range of z to get the distribution of min(x,y)
Final distribution is 2ke^(-kx)ue^(-ux)exp(-uz)
Q37. Sum Root to Leaf Numbers
You are given an arbitrary binary tree consisting of N nodes, each associated with an integer value from 1 to 9. Each root-to-leaf path can be considered a number formed by concatenatin...read more
Calculate the total sum of all root to leaf paths in a binary tree formed by concatenating node values.
Traverse the binary tree from root to leaf nodes, keeping track of the current path sum
Add the current node value to the path sum and multiply by 10 for each level
When reaching a leaf node, add the final path sum to the total sum
Return the total sum modulo (10^9 + 7)
Q38. LCA of Binary Tree Problem Statement
You are given a binary tree consisting of distinct integers and two nodes, X
and Y
. Your task is to find and return the Lowest Common Ancestor (LCA) of these two nodes.
The ...read more
Find the Lowest Common Ancestor (LCA) of two nodes in a binary tree.
Traverse the binary tree to find the paths from the root to nodes X and Y.
Compare the paths to find the last common node, which is the LCA.
Handle cases where one node is an ancestor of the other.
Consider edge cases like when X or Y is the root node.
Implement a recursive or iterative solution to find the LCA efficiently.
Q39. Rotated Array Minimum Finder
You are provided with a sorted array that has undergone 'K' rotations (the exact value of 'K' is unknown). A rotation involves shifting each element of the array to the right, and t...read more
Implement a function to find the minimum number in a rotated sorted array efficiently.
Use binary search to find the minimum element in the rotated array.
Compare the mid element with the start and end elements to determine which half of the array to search next.
Continue the binary search until the minimum element is found.
Q40. Maximum Binary Tree Construction Problem
Given an array TREE
of 'N' unique integers, construct a maximum binary tree using the following rules:
- The root of this tree is the maximum number in
TREE
. - The left sub...read more
Construct a maximum binary tree from an array of unique integers following specific rules.
Find the maximum number in the array to set as the root of the tree.
Recursively construct the left subtree with elements before the maximum number.
Recursively construct the right subtree with elements after the maximum number.
Q41. Sorted Linked List to Balanced BST Problem Statement
Given a singly linked list where nodes contain values in increasing order, your task is to convert it into a Balanced Binary Search Tree (BST) using the same...read more
Convert a sorted singly linked list into a Balanced Binary Search Tree (BST) using the same data values.
Create a function to convert the linked list to a BST by finding the middle element as the root and recursively building the left and right subtrees.
Maintain a pointer to the head of the linked list and update it as nodes are processed.
Use level order traversal to output the values of the BST nodes, representing NULL nodes with -1.
Ensure the height difference of the subtree...read more
Q42. Minimize the cost of the pen, what innovations can you do with it?
Innovations to minimize cost of pen
Use recycled materials for pen body and ink
Simplify design to reduce production costs
Implement refillable ink cartridges to reduce waste and cost
Partner with companies for bulk purchasing of materials
Automate production process to reduce labor costs
Q43. Box Stacking Problem Statement
Consider you are provided with 'n' different types of rectangular 3D boxes. For each type of box, you have three separate arrays: height
, width
, and length
that define the dimensi...read more
The task is to stack different types of rectangular 3D boxes to achieve the maximum possible height by following certain constraints.
Sort the boxes based on their base dimensions in non-increasing order.
Use dynamic programming to find the maximum height achievable by stacking the boxes.
Consider all possible rotations of each box to maximize the height.
Ensure that the base dimensions of the boxes below are strictly larger than the ones above.
Handle multiple copies of the same ...read more
Q44. Boundary Traversal of a Binary Tree
Given a binary tree of integers, your task is to return the boundary nodes of the tree in Anti-Clockwise direction starting from the root node.
Input:
The first line contains...read more
Return the boundary nodes of a binary tree in Anti-Clockwise direction starting from the root node.
Traverse the left boundary nodes from root to leaf nodes in a top-down manner
Traverse the leaf nodes from left to right
Traverse the right boundary nodes from leaf nodes to root in a bottom-up manner
Include only unique values in the boundary nodes
Q45. An organism dies out with prob. p and spawns into 2 with prob (1-p). what is the prob. that starting from 1,the organism will die out?
Given prob. p of dying out and prob. (1-p) of spawning into 2, find prob. of dying out starting from 1 organism.
Use probability tree to visualize outcomes
Probability of dying out starting from 1 is p + (1-p) * (probability of dying out starting from 2)^2
Solve recursively to get final answer
Q46. Validate BST Problem Statement
Given a binary tree with N
nodes, determine whether the tree is a Binary Search Tree (BST). If it is a BST, return true
; otherwise, return false
.
A binary search tree (BST) is a b...read more
Validate if a binary tree is a Binary Search Tree (BST) or not.
Check if the left subtree of a node contains only nodes with data less than the node's data.
Check if the right subtree of a node contains only nodes with data greater than the node's data.
Ensure both the left and right subtrees are also binary search trees.
Traverse the tree in an inorder manner and check if the elements are in sorted order.
Recursively validate each node's value against its parent's value range.
Q47. Ninja and Binary String Problem Statement
Ninja has a binary string S
of size N
given by his friend. The task is to determine if it's possible to sort the binary string S
in decreasing order by removing any num...read more
Determine if a binary string can be sorted in decreasing order by removing non-adjacent characters.
Iterate through the binary string and check if it can be sorted in decreasing order by removing non-adjacent characters.
Keep track of the count of '1's and '0's in the string to determine if it can be sorted in decreasing order.
If the count of '1's is greater than the count of '0's, the string can be sorted in decreasing order.
Q48. Ways To Make Coin Change
Given an infinite supply of coins of varying denominations, determine the total number of ways to make change for a specified value using these coins. If it's not possible to make the c...read more
Implement a function to determine the total number of ways to make change for a specified value using given denominations.
Use dynamic programming to keep track of the number of ways to make change for each value up to the target value.
Iterate through each denomination and update the number of ways to make change for each value based on the current denomination.
Return the total number of ways to make change for the target value.
Example: For N=3, D=[1, 2, 3], V=4, the output sh...read more
Q49. Cycle Detection in a Singly Linked List
Determine if a given singly linked list of integers forms a cycle or not.
A cycle in a linked list occurs when a node's next
points back to a previous node in the list. T...read more
Detect if a singly linked list forms a cycle by checking if a node's next pointer points back to a previous node.
Use Floyd's Cycle Detection Algorithm to determine if there is a cycle in the linked list.
Maintain two pointers, one moving at twice the speed of the other.
If the two pointers meet at any point, there is a cycle in the linked list.
Q50. What is market cap and how would you explain in Lehman terms?
Market cap is the total value of a company's outstanding shares. It's calculated by multiplying the current stock price by the number of shares outstanding.
Market cap is short for market capitalization.
It's a measure of a company's size and value.
It's calculated by multiplying the current stock price by the number of shares outstanding.
For example, if a company has 1 million shares outstanding and the current stock price is $50, the market cap would be $50 million.
Market cap ...read more
Q51. Sum of Digits Problem Statement
Given an integer 'N', continue summing its digits until the result is a single-digit number. Your task is to determine the final value of 'N' after applying this operation iterat...read more
Given an integer, sum its digits until a single-digit number is obtained. Determine the final single-digit integer.
Iteratively sum the digits of the integer until a single-digit number is obtained
Output the final single-digit integer for each test case
Handle multiple test cases efficiently
Ensure the final value is less than 10
Q52. What is weak reference? garbage collection in case of such references?
Weak reference is a reference that does not prevent the object from being garbage collected.
Weak references are used to refer to objects that can be garbage collected if there are no strong references to them.
They are typically used in scenarios where you want to hold a reference to an object, but don't want to prevent it from being collected.
Weak references are implemented using weak reference queues, which allow you to perform actions when weakly referenced objects are abou...read more
Q53. A is a matrix vi's are n linear vectors s.t. Avi= Vj a<=j<=n, what are the possible values of |A|?
Possible values of determinant of matrix A given Avi=Vj for n linear vectors
The possible values of |A| are non-zero as the given vectors are linearly independent
The value of |A| can be calculated using the formula |A| = (-1)^n * det(A)
If the given vectors are orthogonal, then |A| is the product of the magnitudes of the vectors
Q54. Find number of occurrences of a character in string. Provide multiple approaches for the solution and choose the best why? For "string aabcadd output=a3b1c1d2
Count occurrences of a character in a string and output in a specific format.
Use a hash table to store the count of each character.
Loop through the string and update the count in the hash table.
Create the output string using the hash table.
Q55. Puzzle: There are 5 switches in a room and there are 5 bulbs (not in that room but on different floors). Find the minimum number of trips you will make to find which switch is associated to which bulb
Q56. Implementing a Priority Queue Using Heap
Ninja has been tasked with implementing a priority queue using a heap data structure. However, he is currently busy preparing for a tournament and has requested your ass...read more
Implement a priority queue using a heap data structure by completing the provided class functions.
Implement push(), pop(), getMaxElement(), and isEmpty() functions in the given class structure.
Use a heap data structure to maintain the priority queue.
Handle different types of queries (push, pop, getMaxElement, isEmpty) as per the given instructions.
Ensure the functions return the correct values based on the type of query.
Test the implementation with sample input and output pro...read more
Q57. A and B play a game with unfair count with P[Heads]= p. they count # of heads and tails .if # of heads > #tails +1 at any point, A wins.Find the prob. that A wins
A and B play a game with unfair coin. A wins if # of heads > #tails +1 at any point. Find prob. of A winning.
The game is played with an unfair coin with P[Heads]=p
A wins if # of heads > #tails +1 at any point
Find the probability of A winning
Q58. First Missing Positive Problem Statement
You are provided with an integer array ARR
of length 'N'. Your objective is to determine the first missing positive integer using linear time and constant space. This me...read more
Find the smallest missing positive integer in an array efficiently.
Iterate through the array and mark positive integers as visited using index as value
Iterate through the marked array to find the first missing positive integer
Handle negative numbers by ignoring them during marking process
Use two threads to print even and odd numbers in increasing order.
Create two threads, one for printing even numbers and one for printing odd numbers.
Use a shared variable to keep track of the current number to be printed.
Synchronize access to the shared variable to ensure correct ordering of numbers.
Use a loop in each thread to print the next number and update the shared variable.
Q60. Find the Second Largest Element
Given an array or list of integers 'ARR', identify the second largest element in 'ARR'.
If a second largest element does not exist, return -1.
Example:
Input:
ARR = [2, 4, 5, 6, ...read more
Find the second largest element in an array of integers. Return -1 if second largest does not exist.
Iterate through the array to find the largest and second largest elements.
Handle cases where all elements are identical by returning -1.
Consider edge cases like empty array or array with less than 2 elements.
Q61. If the price of a security is showing an upward trend, who would gain - a put option holder or a call option holder?
Call option holder would gain.
A call option gives the holder the right to buy the security at a predetermined price, known as the strike price.
If the price of the security is showing an upward trend, the call option holder can exercise their option and buy the security at the lower strike price, then sell it at the higher market price for a profit.
On the other hand, a put option gives the holder the right to sell the security at a predetermined price.
If the price of the secur...read more
Q62. Internal implementation of HashSet? Which scenario will generate same hashcode for a HashMap?
HashSet is implemented using a HashMap internally. Same hashcode is generated when two objects have the same value for hashCode() and equals() methods.
HashSet internally uses a HashMap to store its elements.
The hashcode of an object is generated using the hashCode() method.
If two objects have the same value for hashCode() and equals() methods, they will generate the same hashcode.
For example, if two String objects have the same content, they will generate the same hashcode.
Q63. What is the prob. that element at 20th position lands up at 31st position after the first iteration?
The probability of element at 20th position landing up at 31st position after the first iteration.
The probability depends on the size of the dataset and the algorithm used for iteration.
If the algorithm involves swapping adjacent elements, the probability is higher.
If the dataset is sorted in a way that the element at 20th position is adjacent to the element at 31st position, the probability is 1.
The probability can be calculated using combinatorics and probability theory.
Q64. Implementation of singleton pattern and ways of breaking it? singleton pattern implementation in a multithreaded environment?
Singleton pattern ensures a class has only one instance, while allowing global access to it.
Implement a private constructor to prevent direct instantiation.
Create a static method to provide a single point of access to the instance.
Use lazy initialization to create the instance only when needed.
Ensure thread safety in a multithreaded environment using synchronization or double-checked locking.
Breaking the singleton pattern can be done by using reflection, serialization, or clo...read more
HashMap in Java is a data structure that stores key-value pairs and uses hashing to efficiently retrieve values based on keys.
HashMap internally uses an array of linked lists to store key-value pairs.
When a key-value pair is added, the key is hashed to find the index in the array where it will be stored.
If multiple keys hash to the same index, a linked list is used to handle collisions.
Retrieving a value involves hashing the key to find the index and then traversing the linke...read more
Q66. Find f(n) : pdt F(x) cdf. the value of k> 0 a constant -inf S +inf f(x)*F(kx) dx x follows normal standard distribution?
Finding f(n) for a normal standard distribution with a given constant k.
Calculate the product of probability density function and cumulative distribution function.
Integrate the product of f(x) and F(kx) from -inf to +inf.
The value of k is a constant greater than 0.
Overriding equals and hashCode methods in Java is important for proper object comparison and hashing.
Equals method is used to compare two objects for equality, while hashCode method is used to generate a unique integer value for an object.
By overriding equals and hashCode methods, we can ensure that objects are compared based on their actual content rather than memory address.
This is crucial for collections like HashMap and HashSet, where proper implementation of equals and h...read more
Q68. What is enterprise value and how is it calculated?
Enterprise value is the total value of a company, including debt and equity.
Enterprise value is calculated by adding market capitalization, debt, and minority interest, and then subtracting cash and cash equivalents.
It represents the total value of a company that an acquirer would have to pay to take over the company.
Enterprise value is a more accurate representation of a company's value than market capitalization alone.
For example, if a company has a market capitalization of...read more
Synchronized Collection is thread-safe but may have performance issues, while Concurrent Collection is optimized for concurrent access.
Synchronized Collection uses synchronized keyword to achieve thread-safety, while Concurrent Collection uses non-blocking algorithms like CAS (Compare and Swap).
Synchronized Collection locks the entire collection during modification, leading to potential performance bottlenecks, while Concurrent Collection allows multiple threads to access and...read more
Q70. Given a binary tree and a number n, find the root to leaf branch whose sum equals to n. Now find maximum length branch whose sum equals to n (that means of course now there are more than 1 branch whose sum equa...
read moreFind root to leaf branches in a binary tree with sum equal to n, then find maximum length branches with sum equal to n.
Traverse the binary tree using depth-first search (DFS) and keep track of the current path and its sum
If a leaf node is reached, check if the sum equals n and store the path if it does
For finding maximum length branches, store all paths with sum equal to n and then find the longest ones
Example: Given binary tree with values [1, 2, 3, 4, 5], find branches with...read more
Q71. What is SQL Cursor? Index? Aggregate Functions examples?
SQL Cursor is a database object used to manipulate data row by row.
Cursor is used to fetch and process data row by row
Index is a database object used to speed up data retrieval
Aggregate functions are used to perform calculations on a set of values
Examples of aggregate functions are SUM, AVG, COUNT, MAX, MIN
Q72. Find a local minima of an array in o(log n)? In a functional program
Find local minima of an array in o(log n) in functional programming.
Use binary search to find the local minima.
Check if the mid element is a local minima, if not, move towards the lower side.
If the mid element is greater than its left element, move towards the left side, else move towards the right side.
Repeat until a local minima is found.
Example: [5, 3, 2, 4, 6, 8, 9] -> local minima is 2.
Design a system for users to subscribe to topics and receive notifications for new messages.
Create a user profile where they can select topics of interest to subscribe to.
Implement a messaging system that sends notifications to users when new messages are posted related to their subscribed topics.
Allow users to manage their subscriptions and preferences easily.
Utilize a database to store user subscriptions and messages for efficient retrieval.
Consider implementing push notifi...read more
Q74. Given a sorted array find two element (i,j) s.t. i+j =x in O(n) time?
Find two elements in a sorted array that add up to a given sum in linear time.
Use two pointers, one at the beginning and one at the end of the array.
If the sum of the two pointers is greater than the target, move the right pointer to the left.
If the sum of the two pointers is less than the target, move the left pointer to the right.
Repeat until the sum is found or the pointers meet.
Example: Given [1, 2, 3, 4, 5] and target 7, return (2, 5).
Q75. When would a put option holder exercise the option?
A put option holder would exercise the option when the underlying asset's price is below the strike price.
Put option holders exercise when the market price of the underlying asset is lower than the strike price.
They exercise to sell the asset at a higher price than the market price.
Put options are often exercised before the expiration date if the market conditions are favorable.
Exercising a put option allows the holder to profit from a decline in the price of the underlying a...read more
Q76. What is the difference between package and package-lock.json?
package.json lists dependencies and package-lock.json ensures consistent installs.
package.json lists all the dependencies required for the project
package-lock.json ensures that the same versions of dependencies are installed across all environments
package.json is manually edited while package-lock.json is generated automatically
package-lock.json is used for reproducible builds
CopyOnWriteArrayList creates a new copy of the underlying array whenever an element is added, modified, or removed.
CopyOnWriteArrayList is thread-safe and suitable for scenarios where reads are more frequent than writes.
Adding, modifying, or removing elements in CopyOnWriteArrayList creates a new copy of the underlying array, ensuring thread safety.
Iterators on CopyOnWriteArrayList operate on the original array and do not throw ConcurrentModificationException.
Q78. Types of valuation and reason for using each one of them
Valuation methods include market, income, and asset-based approaches, each used for different purposes.
Market approach: based on comparable sales of similar assets in the market
Income approach: based on the present value of expected future income generated by the asset
Asset-based approach: based on the value of the asset's tangible and intangible assets
Market approach is commonly used for real estate, income approach for businesses, and asset-based approach for liquidation or...read more
Q79. Implement a dynamic 2D excel sheet using DS (underwent various levels of improvisations)
Implement a dynamic 2D excel sheet using DS
Use a 2D array to store the data
Implement functions to add, delete, and modify data
Use data structures like linked lists or hash tables for efficient searching and sorting
Implement dynamic resizing to handle large amounts of data
Use GUI libraries like Tkinter or PyQt for user interface
Q80. What between Tower and Morgan Stanley?
Tower and Morgan Stanley are both financial services companies.
Tower is a global investment management firm with over $1 trillion in assets under management.
Morgan Stanley is a multinational investment bank and financial services company.
Both companies offer a range of financial services including wealth management, investment banking, and asset management.
Tower is known for its focus on sustainable investing, while Morgan Stanley has a strong presence in mergers and acquisit...read more
Q81. Tell me about Yourself. What excel functions are you aware of?
I am a detail-oriented analyst with knowledge of various Excel functions.
I am proficient in basic functions such as SUM, AVERAGE, MAX, MIN, COUNT, etc.
I am also familiar with more advanced functions such as VLOOKUP, HLOOKUP, INDEX, MATCH, IF, AND, OR, etc.
I have experience using PivotTables, PivotCharts, and creating macros to automate tasks.
I am constantly learning and exploring new functions to improve my skills.
Q82. A build up that resulted in the concept of using joins in DBMS
Joining tables in DBMS evolved as a solution to handle complex data relationships.
Joins allow combining data from multiple tables based on a common column.
The concept of joins originated from the need to handle complex data relationships.
Joins can be inner, outer, left, right, or cross depending on the type of data required.
Joins can improve query performance by reducing the number of queries needed to retrieve data.
Joins can also help in data normalization by reducing data r...read more
Q83. Build a system where people subscribe to a particular topic . And if any message is posted regarding the particular topic then the people who have subscribed to that system must get the message...
read moreBuild a system where people can subscribe to a topic and receive messages related to that topic.
Create a subscription system where users can choose topics of interest
Implement a messaging system to post messages related to topics
Store user subscriptions and messages in a database
Send notifications to subscribed users when a message is posted for their subscribed topic
Q84. Design the database for an online shopping website like flipkart. Now how will you modify your database if you want to give some discount on those product which are going to expire after 6 months
Q85. Find an even length palindrome in a string in o(n)?
To find an even length palindrome in a string in O(n), we can use the two-pointer approach.
Initialize two pointers at the center of the string.
Expand the pointers outwards while checking if the characters at both pointers are equal.
If they are not equal, return the previous substring as the even length palindrome.
If the pointers reach the end of the string, return the entire string as the even length palindrome.
Q86. A puzzle: two dice are given. each has six face. Change the numbering on one dice only so that the probability of occurrence of sum (of the numbers appearing in a throw of two dice) from 1 to 12, are all equal....
read moreQ87. What data structure will you use to find the unique words and the number of times the word appear in a novel
Use a HashMap data structure to store unique words and their frequencies.
Use a HashMap<String, Integer> to store unique words as keys and their frequencies as values.
Iterate through each word in the novel, updating the frequency count in the HashMap.
At the end, the HashMap will contain unique words and their frequencies.
I want to work at Morgan Stanley because of its reputation for excellence in finance, global presence, and opportunities for growth.
Morgan Stanley is a renowned financial institution known for its excellence in finance
I am attracted to the global presence of Morgan Stanley and the opportunity to work on international projects
I believe working at Morgan Stanley will provide me with opportunities for professional growth and development
Q89. Write a code to sort a list without pipes?
Code to sort a list without pipes
Use a sorting algorithm like bubble sort, insertion sort, or selection sort
Implement the algorithm in the programming language of your choice
Test the code with different input sizes and types
Q90. What is the difference between hash map and hash set . Explain time complexity in each ??
A hash map is a data structure that stores key-value pairs, while a hash set is a data structure that stores unique elements.
Hash map allows for efficient retrieval of values based on keys.
Hash set only stores unique elements and does not allow duplicates.
Time complexity for hash map and hash set operations is generally O(1) on average, but can be O(n) in worst case scenarios.
Examples of hash map operations include inserting a key-value pair, retrieving a value based on a key...read more
Q91. What are Hedge Funds? Components of Financial Statements
Hedge funds are alternative investment vehicles that use pooled funds to employ various strategies to generate high returns.
Hedge funds are privately owned and managed investment funds
They use a variety of investment strategies such as long-short equity, global macro, and event-driven
They are typically only available to accredited investors due to their high-risk nature
Components of financial statements include balance sheet, income statement, and cash flow statement
Q92. How can we make sure that package versions are taken from package-lock.json and not package.json
To ensure package versions are taken from package-lock.json, use npm ci instead of npm install.
npm ci installs packages based on package-lock.json
npm install may update package versions in package.json
Always commit package-lock.json to version control
Q93. Prove that for N>= a, N> N^.5 + N^(1/3)+N^(1/4)
Prove N>=N^.5+N^(1/3)+N^(1/4) for N>=a
Use AM-GM inequality
Substitute N with a and prove the inequality holds
Use calculus to find the minimum value of the expression
Abstract class can have both abstract and non-abstract methods, while interface can only have abstract methods.
Abstract class can have constructors, fields, and methods, while interface cannot have any implementation.
A class can only extend one abstract class, but can implement multiple interfaces.
Abstract classes are used to define common characteristics of subclasses, while interfaces are used to define a contract for classes to implement.
Example: Abstract class 'Shape' wit...read more
Q95. Process is throwing Out of Memory Error , describe the steps you will take to debug and then interviewer went down in Memory Management concepts and garbage collection algo's of JVM in great detail.
To debug Out of Memory Error, analyze memory usage and garbage collection algorithm of JVM.
Analyze heap dump to identify memory leaks
Check if JVM is running out of heap space
Analyze garbage collection logs to identify any issues
Tune JVM parameters to optimize memory usage
Consider using a profiler to identify memory-intensive code
Check for any large objects or arrays that may be causing the issue
Q96. Write your own implementation for shared pointer. How it will handle if it get assigned by another one. How will you use it in main method. How will you overload -> operator and dereferencing operator in that c...
read moreImplementation of shared and unique pointers in C++ with operator overloading.
Implement a class for shared pointer with reference counting.
Handle assignment by incrementing reference count and decrementing old pointer's count.
Overload -> and * operators to access underlying object.
Use shared pointer in main method by creating instances and passing them around.
For unique pointer, implement a class that transfers ownership upon assignment.
Q97. Annotations : @Component vs @service, @Controller vs @RESTController, @Configuration, @Transactional
Annotations used in Spring Framework for defining components and services.
Annotations like @Component, @Service, and @Controller are used for defining components in Spring Framework.
@RestController is used for defining RESTful web services.
@Configuration is used for defining configuration classes.
@Transactional is used for defining transactional methods.
All these annotations help in defining and managing dependencies in Spring Framework.
Q98. Number of inversions in an array in O(nlogn) time?
Number of inversions in an array in O(nlogn) time.
Use merge sort algorithm to count inversions
Divide the array into two halves and recursively count inversions
Merge the two halves and count split inversions
Time complexity is O(nlogn)
Q99. What are hedge funds, and what are their products and structures?
Hedge funds are investment funds that pool capital from accredited individuals or institutional investors and use various strategies to generate high returns.
Hedge funds typically have high minimum investment requirements and are only available to accredited investors.
They often use leverage and derivatives to amplify returns.
Hedge funds can invest in a wide range of assets, including stocks, bonds, commodities, and real estate.
Common hedge fund strategies include long/short ...read more
Q100. What are bonds and what are the different types of bonds?
Bonds are debt securities issued by companies or governments to raise capital. Different types include corporate bonds, municipal bonds, and treasury bonds.
Bonds are essentially loans that investors give to companies or governments in exchange for periodic interest payments and the return of the bond's face value at maturity.
Corporate bonds are issued by corporations to raise capital for various purposes, such as expansion or acquisitions.
Municipal bonds are issued by state a...read more
Top HR Questions asked in Magnate Architectural Auxiliary Services
Interview Process at Magnate Architectural Auxiliary Services
Top Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month