Morgan Stanley
30+ OneMagnify Interview Questions and Answers
Q1. 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.
Q2. 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
Q3. 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.
Q4. 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
Q5. 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
Q6. 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
Q7. 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.
Q8. 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].
Q9. 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
Q10. 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
Q11. 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.
Q12. 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.
Q13. 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.
Q14. 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.
Q15. 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.
Q16. 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
Q17. 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)
Q18. 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.
Q19. 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.
Q20. 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.
Q21. 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
Q22. 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.
Q23. 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.
Q24. 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
Q25. 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
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
Q27. 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.
Q28. Convert String from Camel case to Snake case
Converts a string from Camel case to Snake case.
Loop through the string and check for uppercase letters
Insert an underscore before each uppercase letter
Convert the string to lowercase
Q29. optimized solutions and core principles applied in OOPS
Optimized solutions and core principles applied in OOPS
Encapsulation, Inheritance, Polymorphism, Abstraction are core principles of OOPS
Optimized solutions can be achieved through efficient algorithms and data structures
Design patterns like Singleton, Factory, Observer can also be used for optimized solutions
Q30. check palindrome , anagram of string with O(n)
To check palindrome and anagram of a string with O(n), use a hash table to store character frequencies.
Create a hash table to store the frequency of each character in the string.
For palindrome, check that no more than one character has an odd frequency.
For anagram, compare the hash tables of the two strings.
If the hash tables are equal, the strings are anagrams.
If the hash tables differ by only one character, the strings are palindrome anagrams.
If the hash tables differ by mo...read more
Q31. Coin Change and optimization through DP
Coin change problem can be solved using dynamic programming to find the minimum number of coins needed to make a certain amount of change.
Use dynamic programming to build up solutions for smaller subproblems
Start by initializing an array to store the minimum number of coins needed for each amount from 0 to the target amount
Iterate through each coin denomination and update the array with the minimum number of coins needed for each amount
Q32. Kth Max Element in a Array
Find the Kth maximum element in an array of strings.
Sort the array in descending order.
Return the element at index K-1.
Q33. HasMap explanation
HashMap is a data structure in Java that stores key-value pairs.
HashMap is part of the Java Collections framework.
It allows for fast retrieval of values based on keys.
Keys in a HashMap must be unique, but values can be duplicated.
Example: HashMap
map = new HashMap<>();
Interview Process at OneMagnify
Top Software Developer Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month