Goldman Sachs
100+ Codingal Interview Questions and Answers
Q1. Good old standard problem: Playing number game with your friend to select any of the number between 1 to 3. Whoever reaches 20 first, wins. You have to tell the strategy to win the game. Basically, you start wi...
read moreThe strategy is to always subtract the number chosen by the friend from 4 to ensure reaching 16 first.
Start with 20 and subtract the number chosen by the friend from 4.
Continue this strategy until reaching 16 before the friend reaches 17-19.
Ensure the friend ends up at any number between 17 to 19 before reaching 16.
Q2. Given a tank with liquid, and there are flows in and out, inflow is U and outflow is Kx, where x is current height of liquid in tank, all needed quantities given, what are the conditions for overflow and steady...
read moreConditions for overflow and steady state in a tank with inflow and outflow
Overflow occurs when the inflow rate is greater than the outflow rate
Steady state is achieved when the inflow rate equals the outflow rate
Overflow can be prevented by adjusting the inflow rate or increasing the outflow rate
Steady state can be maintained by balancing the inflow and outflow rates
Q3. Given we have a (un)biased die, with given probabilities, and we toss it till we get a sum of 100 or more (basically if the sum crosses 100), and we stop. What is the most probable number you will get on the la...
read moreThe most probable number on the last toss is 6.
The probability of getting a sum of 100 or more is highest when the sum is 99.
The last toss will be made to reach the sum of 100, so the most probable number is the one that will take the sum closest to 100.
The sum of 94 can be achieved by rolling a 6 on the last toss, which is the most probable number.
Q4. Suppose a man starts at 0, and has to go to 20 on the number line. He can either move in steps of 1 or 2. How many number of ways can he do this? Extending this, if we know the number of ways for going from 0 t...
read moreCount number of ways to reach 20 on number line starting from 0 in steps of 1 or 2. Derive recursive formula for n+1.
Use dynamic programming to count number of ways for each step.
For each step, number of ways is sum of number of ways for previous 1 or 2 steps.
Recursive formula: ways[n+1] = ways[n] + ways[n-1]
Q5. Maximum Subarray Sum Problem Statement
Given an array ARR
consisting of N
integers, your goal is to determine the maximum possible sum of a non-empty contiguous subarray within this array.
Example of Subarrays:...read more
The goal is to find the maximum sum of a non-empty contiguous subarray within an array of integers.
Iterate through the array and keep track of the maximum sum of subarrays encountered so far.
Use Kadane's algorithm to efficiently find the maximum subarray sum.
Consider edge cases like all negative numbers in the array.
Example: For input [1, -3, 4, -2, -1, 6], the maximum subarray sum is 7 (subarray [4, -2, -1, 6]).
Q6. There is an urn with n red balls and 1 black ball in it. You and your friend play a game where you take turns drawing from the urn. The player who draws the black ball first wins. Should you go first or second?
Go second. The probability of winning is higher when going second.
The probability of winning when going first is (1/n+1), while the probability of winning when going second is (n/n+1)
This is because the first player has a chance of drawing the black ball on their turn, while the second player has a chance of drawing the black ball on their turn or the first player's turn
For example, if there are 10 red balls and 1 black ball, the probability of winning when going first is 1/1...read more
Q7. LRU Cache Design Question
Design a data structure for a Least Recently Used (LRU) cache that supports the following operations:
1. get(key)
- Return the value of the key if it exists in the cache; otherwise, re...read more
Design a Least Recently Used (LRU) cache data structure that supports get and put operations with capacity constraint.
Implement a doubly linked list to keep track of the order of keys based on their recent usage.
Use a hashmap to store key-value pairs for quick access.
When capacity is reached, evict the least recently used item before inserting a new item.
Update the order of keys in the linked list whenever a key is accessed or inserted.
Q8. Shortest Path in a Binary Matrix Problem Statement
Given a binary matrix of size N * M
where each element is either 0 or 1, find the shortest path from a source cell to a destination cell, consisting only of 1s...read more
Find the shortest path in a binary matrix from a source cell to a destination cell consisting only of 1s.
Use Breadth First Search (BFS) algorithm to find the shortest path.
Keep track of visited cells to avoid revisiting them.
Calculate the path length by counting the number of 1s in the path.
Return -1 if no valid path exists.
Q9. Suppose there are N chocolates, and I pick a random one, and eat that chocolate and also everything to the right of it. I then continue this process with the remaining. How many ways are there to do this?
There are (N-1)! ways to eat chocolates from left to right.
The first chocolate can be chosen in N ways, the second in (N-1) ways, and so on.
However, since the order of chocolates eaten matters, we need to divide by the number of ways to order N chocolates, which is N!.
Therefore, the total number of ways to eat chocolates is (N-1)!
For example, if N=4, there are 3! = 6 ways to eat the chocolates.
Q10. Given 3 functions, f which gives the first day of the current month, g gives the next working day and h gives the previous working day, conpute the 3rd working day? Compute the 2nd working day of the previous m...
read moreCompute working days using given functions f, g, and h.
To compute the 3rd working day, apply function g three times to function f.
To compute the 2nd working day of the previous month, apply function h to function f, then apply function g twice.
To compute the 4th working day of the next month, apply function g four times to function f.
Q11. Suppose you and I are playing a dice game. The one who get the lesser number looses the games. The dice has n sides. If I start the game, what is the probablity of you winning?
Probability of winning a dice game where the one with lesser number wins.
The probability of winning depends on the number of sides on the dice.
If the dice has an odd number of sides, the probability of winning is higher for the second player.
If the dice has an even number of sides, the probability of winning is equal for both players.
Q12. There is a 2D plane with infinite parallel, vertical lines with a spacing of 1 unit between them. You drop a rod of length L randomly on the plane, with random position and orientation. What is the probability...
read moreProbability of a randomly dropped rod of length L intersecting a line on a 2D plane with infinite parallel, vertical lines.
The probability depends on the length of the rod L.
The probability can be calculated using geometric probability.
The probability is 1 - (2L - 1) / infinity.
For example, if L = 1, the probability is 0.5.
If L = 2, the probability is 0.75.
Q13. Given a biased coin, how do you create an unbiased toss?
Flip the coin twice and consider the outcome as follows.
Flip the coin twice and consider the outcome as follows:
- If both flips are heads or both are tails, discard and flip again.
- If the first flip is heads and the second is tails, consider it as heads.
- If the first flip is tails and the second is heads, consider it as tails.
This method ensures a 50-50 chance of getting either heads or tails.
Alternatively, use a physical method to balance the weight distribution of the coi...read more
Q14. Given a number line, and we have a rod of length L. We drop the rod on the line, what is the probability that it covers an integer?
Probability of a rod of length L covering an integer on a number line.
The probability depends on the length of the rod and the distance between adjacent integers on the number line.
If the length of the rod is less than the distance between adjacent integers, the probability is zero.
If the length of the rod is greater than or equal to the distance between adjacent integers, the probability is (L - d)/d, where d is the distance between adjacent integers.
The probability can be c...read more
Q15. Supposed there is a party, with 9 people, each person wants to give gifts to 3 people and also wants a gift from them. Is this scenario possible? If not, when is this possible? Give me a general case
No, it is not possible for each person to give gifts to 3 people and receive a gift from them in a party of 9 people.
In this scenario, each person would need to receive 3 gifts, which is not possible if there are only 9 people.
This scenario would be possible if there were at least 10 people at the party.
In general, for a party of n people, each person can give gifts to n-1 people and receive gifts from n-1 people.
Q16. You have an n x n matrix in which all the rows and all the columns are sorted. Given an input number, describe an algorithm to search for the number in the matrix
Algorithm to search for a number in an n x n matrix with sorted rows and columns.
Start from the top-right corner of the matrix
If the current element is greater than the target, move left
If the current element is less than the target, move down
Repeat until the target is found or the bottom-left corner is reached
Q17. Is the price of a barrier option more or less than a normal option?
The price of a barrier option is generally less than a normal option.
Barrier options have a condition that must be met for the option to be activated, which reduces the likelihood of the option being exercised.
This reduced likelihood of exercise means that barrier options are generally cheaper than normal options.
However, the price of a barrier option can vary depending on the specific conditions and terms of the option.
For example, a knock-in barrier option may be more expen...read more
Q18. You roll a die until the sum of all die rolls becomes at least 100. What is the most likely value of the last roll?
What is the most likely value of the last roll in a game where a die is rolled until the sum of all rolls is at least 100?
The last roll must be at least 4 to reach a sum of 100
The probability of rolling a 4, 5, or 6 is 1/2
The most likely value of the last roll is 4 or 5
Q19. Given coordinates of some points, find a figure that encompasses all of the points. The figure should have the least possible area and be formed by joining points using straight lines. Convex Hull.
The Convex Hull is the smallest convex polygon that encloses all given points.
Sort the points based on their x-coordinate.
Find the upper hull by starting from the leftmost point and moving clockwise.
Find the lower hull by starting from the rightmost point and moving counterclockwise.
Combine the upper and lower hulls to form the convex hull.
Q20. If I have to buy fuel from you, what option would I buy?
You can buy fuel from us through our fuel card program.
We offer a fuel card program that allows you to purchase fuel from our network of stations.
Our fuel card program offers discounts and rewards for frequent users.
You can easily track your fuel expenses and usage through our online portal.
We also offer customized fuel solutions for businesses and fleets.
Our fuel is high-quality and meets all industry standards.
Q21. If we increase the volatility of the stock, how does the price of a call option change?
Increasing stock volatility increases the price of a call option.
Higher volatility means higher potential for the stock to move in the option holder's favor, increasing the option's value
The option's delta and gamma will also increase with higher volatility
Example: If a call option on a stock with a strike price of $50 has a premium of $2 when the stock has a volatility of 20%, increasing the volatility to 30% may increase the premium to $2.50 or higher
Q22. Find the magic number in an sorted array. magic number is the one whose value and index position is same
Find the magic number in a sorted array where value and index are same.
Iterate through the array and check if the value and index are same
If found, return the value
If not found, return -1
Q23. Clarification about what CPI stands(Is it the same as Grade Point Average?)
CPI stands for Consumer Price Index, not the same as Grade Point Average (GPA).
CPI is a measure of the average change over time in the prices paid by urban consumers for a market basket of consumer goods and services.
It is used to track inflation and price changes in the economy.
GPA, on the other hand, is a measure of academic performance and represents a student's average grade point across courses.
CPI and GPA are completely different concepts and have no relation to each ot...read more
Q24. What is the expected number of tosses of a fair coin to get 3 consecutive heads?
Expected number of tosses of a fair coin to get 3 consecutive heads.
The probability of getting 3 consecutive heads is 1/8
The expected number of tosses to get 3 consecutive heads is 14
This can be calculated using the formula E(X) = 2^k + 2^(k-1) + 2^(k-2) + ... + 2^2 + 2^1 + 2^0, where k is the number of consecutive heads required
Q25. What is a call option? Why are call options bought?
A call option is a financial contract that gives the buyer the right, but not the obligation, to buy an underlying asset at a predetermined price within a specified time period.
Call options are bought by investors who believe that the price of the underlying asset will rise in the future.
The buyer of a call option pays a premium to the seller for the right to buy the asset at a predetermined price, known as the strike price.
If the price of the asset rises above the strike pri...read more
Q26. How do you calculate the price of a call option?
The price of a call option is calculated using the Black-Scholes model which takes into account the underlying asset price, strike price, time to expiration, risk-free interest rate, and volatility.
Determine the current price of the underlying asset
Determine the strike price of the option
Determine the time to expiration of the option
Determine the risk-free interest rate
Determine the volatility of the underlying asset
Plug these values into the Black-Scholes model to calculate ...read more
Q27. Given two arrays of size n each, describe an algorithm to find the largest common subarray of the two arrays
Algorithm to find largest common subarray of two arrays of size n
Create a 2D array to store the lengths of common subarrays
Traverse both arrays and fill the 2D array with lengths of common subarrays
Find the maximum length and its corresponding ending index in the 2D array
Use the ending index to retrieve the largest common subarray from either of the arrays
Q28. Row sorted and column sorted matrix problem of finding an element.
The problem involves finding an element in a matrix that is sorted both row-wise and column-wise.
Start from the top-right corner of the matrix
Compare the target element with the current element
If the target is smaller, move left; if larger, move down
Repeat until the target is found or the matrix boundaries are crossed
Q29. Different efficient ways to implement product and summation of n numbers. And limitations
Efficient ways to implement product and summation of n numbers with limitations.
For summation, use a loop or built-in functions like sum() or reduce().
For product, use a loop or built-in functions like prod() or reduce().
Limitations include overflow errors for large numbers and memory constraints for very large arrays.
Using parallel processing or vectorization can improve efficiency.
Consider using data structures like binary trees or prefix sums for faster calculations.
Q30. If You have an infinite array then how many ways to sort it and also tell the complexities
There are infinite ways to sort an infinite array with varying complexities.
Sorting algorithms like QuickSort, MergeSort, HeapSort, etc. can be used to sort the array.
The time complexity of sorting algorithms varies from O(n log n) to O(n^2).
The space complexity also varies depending on the algorithm used.
Sorting an infinite array is not practical, so it is usually done in chunks or using parallel processing.
The sorting order can be ascending or descending based on the requir...read more
Q31. What do you know about options?
Options are financial contracts that give the buyer the right, but not the obligation, to buy or sell an underlying asset at a predetermined price.
Options can be used for hedging or speculation
There are two types of options: call options and put options
Call options give the buyer the right to buy the underlying asset at a predetermined price, while put options give the buyer the right to sell the underlying asset at a predetermined price
Options have expiration dates and strik...read more
Q32. A person can climb 1 or 2 stairs. Find the number of ways to jump n stairs
Number of ways to jump n stairs if a person can climb 1 or 2 stairs.
Use dynamic programming to solve the problem.
The number of ways to jump n stairs is equal to the sum of ways to jump n-1 stairs and ways to jump n-2 stairs.
Base cases: if n=0, return 1 and if n=1, return 1.
Q33. Given a 2d matrix sorted row and column wise, search an element
Searching an element in a sorted 2D matrix
Start from the top-right corner or bottom-left corner
Compare the target element with the current element
Move left or down if the target is smaller or move right or up if the target is larger
Q34. Efficient algorithms on calculating Fibonacci’s Sequence
Efficient algorithms for calculating Fibonacci's sequence
Use dynamic programming to avoid redundant calculations
Implement matrix exponentiation to reduce time complexity to O(log n)
Use memoization to store previously calculated values
Iterative approach using constant space complexity
Binet's formula for direct calculation of nth Fibonacci number
Q35. Replace Node With Depth Problem Statement
For a given Binary Tree of integers, replace each of its data with the depth of the tree. The root is at depth 0, hence the root data is updated with 0. Replicate the s...read more
Replace each node in a binary tree with its depth starting from root as 0.
Traverse the binary tree in inorder fashion and update each node's data with its depth.
Start with depth 0 for the root node and increment the depth as you go down the tree.
Handle cases where nodes do not have left or right child by taking -1 in their place.
Print the inorder traversal of the tree with updated node data representing the depth.
Q36. How will you mane a LRU Cache
An LRU cache can be made using a doubly linked list and a hash map.
Create a doubly linked list to store the cache items.
Create a hash map to store the key-value pairs.
When a new item is added, check if the cache is full. If it is, remove the least recently used item from the linked list and hash map.
When an item is accessed, move it to the front of the linked list.
When an item is removed, remove it from both the linked list and hash map.
Q37. Delete a Node from a Linked List
You are provided with a linked list of integers. Your task is to implement a function that deletes a node located at a specified position 'POS'.
Input:
The first line contains a...read more
Implement a function to delete a node from a linked list at a specified position.
Traverse the linked list to find the node at the specified position.
Update the pointers of the previous and next nodes to skip the node to be deleted.
Handle edge cases such as deleting the head or tail of the linked list.
Ensure to free the memory of the deleted node to avoid memory leaks.
Q38. Find integer solutions of x^y=y^x.
Find integer solutions of x^y=y^x.
If x=y, then x^y=y^x=1
If x
If x>y, then x^y>y^x
Only solution is (2,4) and (4,2)
Use logarithms to prove
Q39. difference between hedge funds and private equity
Hedge funds are actively managed investment funds that use various strategies to generate high returns, while private equity firms invest in private companies and aim to increase their value.
Hedge funds are open to a wider range of investors than private equity funds
Hedge funds use leverage to increase returns, while private equity firms use debt to finance acquisitions
Hedge funds have a shorter investment horizon than private equity firms
Private equity firms typically take a...read more
Q40. Find the Longest Palindromic Substring
Given a string ‘S’ composed of lowercase English letters, your task is to identify the longest palindromic substring within ‘S’.
If there are multiple longest palindromic ...read more
Find the longest palindromic substring in a given string, returning the rightmost one if multiple substrings are of the same length.
Use dynamic programming to check for palindromes within the string.
Start by checking for palindromes of length 1 and 2, then expand to longer substrings.
Keep track of the longest palindromic substring found so far and return the rightmost one if multiple substrings are of the same length.
Q41. Connecting Ropes with Minimum Cost
You are given 'N' ropes, each of varying lengths. The task is to connect all ropes into one single rope. The cost of connecting two ropes is the sum of their lengths. Your obj...read more
The problem is to connect N ropes of different lengths into one rope with minimum cost.
Sort the array of rope lengths in ascending order.
Initialize a variable to keep track of the total cost.
While there are more than one rope remaining, take the two shortest ropes and connect them.
Add the cost of connecting the two ropes to the total cost.
Replace the two shortest ropes with the connected rope.
Repeat the above steps until only one rope remains.
Return the total cost.
Q42. Zero Matrix Problem Statement
You are given a matrix MATRIX
of dimension N x M
. Your task is to make all the elements of row i
and column j
equal to 0
if any element in the ith
row or jth
column of the matrix i...read more
The task is to modify a given matrix such that if any element in a row or column is 0, then make all elements in that row and column 0.
Iterate through the matrix and keep track of rows and columns that contain 0s
After the first iteration, iterate through the tracked rows and columns and set all elements to 0
Handle the case where the first row or column contains 0 separately
To solve with O(1) space complexity, use the first row and first column of the matrix to track the rows ...read more
Q43. Design a newspaper subscription system
Design a newspaper subscription system
Create a user registration system
Allow users to select subscription plan and payment method
Provide options for delivery frequency and start/end dates
Send reminders for subscription renewal
Allow users to modify or cancel subscription
Track subscription history and payment records
Q44. Serialization and Deserialization of an N-ary Tree
Given an N-ary tree where each node has at most 'N' child nodes, the task is to serialize the tree into a sequence of bits and then deserialize it back to reco...read more
Serialization and deserialization of an N-ary tree involves converting the tree into a sequence of bits and reconstructing the original tree from this format.
Serialize the N-ary tree by traversing it in level order and representing each node and its children using a space-separated sequence of integers.
Deserialize the serialized tree by parsing the input sequence and reconstructing the tree structure based on the provided format.
Use a queue data structure for deserialization ...read more
Q45. Design a Constant Time Data Structure
Create a data structure that maintains mappings between keys and values, supporting the following operations in constant time:
1. INSERT(key, value): Add or update the inte...read more
Design a constant time data structure for key-value mappings with operations like INSERT, DELETE, SEARCH, GET, GET_SIZE, and IS_EMPTY.
Use a hash table to achieve constant time complexity for operations.
Implement INSERT, DELETE, SEARCH, GET, GET_SIZE, and IS_EMPTY functions.
Ensure key is a string and value is a positive integer.
Return appropriate results based on the operation type.
Handle edge cases like key not found or data structure being empty.
Q46. Ninja and Typing: Comparison of Edited Strings
Ninja needs to compare two strings printed on a text editor, where only lowercase English letters and backspace (represented by ‘#’) are used for typing.
You need ...read more
Q47. Similar Strings Problem Statement
Determine whether two given strings, A
and B
, both of length N
, are similar by returning a 1 if they are, otherwise return a 0.
Explanation:
String A
is similar to string B
if ...read more
The task is to determine if two strings are similar based on the given conditions.
Check if the strings are equal, if yes, return 1
Divide both strings into two parts and check if any combination satisfies the similarity condition
If none of the conditions hold true, return 0
Q48. Word Search Problem Statement
Given a two-dimensional grid of size N x M
consisting of upper case characters and a string 'WORD', determine how many times the 'WORD' appears in the grid.
The 'WORD' can be forme...read more
Count the number of occurrences of a given word in a 2D grid by moving in all eight possible directions.
Iterate through each cell in the grid and start searching for the word from that cell in all eight directions.
Keep track of the number of occurrences found while searching.
Handle edge cases like word length exceeding grid dimensions or starting from out-of-bounds cells.
Q49. Simplify Directory Path Problem Statement
You are provided with a directory path in Unix-style notation, and your task is to simplify it according to given rules.
In a Unix-style file system:
- A dot (.) refers ...read more
Given a Unix-style directory path, simplify it by following certain rules and return the simplified path.
Use a stack to keep track of directories while iterating through the input path.
Handle cases for '.', '..', and multiple slashes appropriately.
Return the simplified path by joining the directories in the stack with '/' separator.
Q50. Explain what is Binary Search Tree
Binary Search Tree is a data structure where each node has at most two children, with left child less than parent and right child greater.
Nodes have at most two children - left and right
Left child is less than parent, right child is greater
Allows for efficient searching, insertion, and deletion of elements
Q51. Counting Pairs Problem Statement
Given a positive integer N
, determine the count of all possible positive integral pairs (X, Y)
that satisfy the equation 1/X + 1/Y = 1/N
.
Example:
Input:
T = 1
N = 2
Output:
3
Ex...read more
Count the number of positive integral pairs (X, Y) that satisfy the given equation.
Iterate through all possible values of X and calculate corresponding Y to check if the equation is satisfied.
Optimize the solution by considering the constraints and properties of the equation.
Handle special cases like when N is 1 or when X and Y are equal.
Use mathematical properties to reduce the number of calculations needed.
Consider edge cases like when N is a prime number.
Q52. Matrix Word Search Problem
Explanation: You are given an 'M' x 'N' matrix of characters named CHARACTER_MATRIX
and a string WORD
. Your task is to identify and list all the occurrences of the string within the m...read more
Matrix Word Search Problem - Find occurrences of a given word in all eight possible directions within a matrix.
Iterate through each cell in the matrix and check for the starting character of the word.
For each occurrence of the starting character, check all eight directions for the complete word.
Keep track of the coordinates of each character in the word for each occurrence found.
Ensure boundaries are not crossed while searching in all directions.
Output the coordinates of each...read more
Q53. Shortest Bridge Problem Statement
Two characters, Tony Stark and Thanos, reside on two separate islands within a 2-D binary matrix of dimensions N x M. Each matrix cell has a value of either 1 (land) or 0 (wate...read more
The task is to find the shortest path of transformed 0s that connects two islands in a binary matrix.
Identify the two islands in the binary matrix.
Find the shortest path between the two islands by converting 0s to 1s.
Output the minimal length of the bridge needed to connect the two islands.
Q54. Buy and Sell Stock Problem Statement
Imagine you are Harshad Mehta's friend, and you have been given the stock prices of a particular company for the next 'N' days. You can perform up to two buy-and-sell transa...read more
The task is to determine the maximum profit that can be achieved by performing up to two buy-and-sell transactions on a given set of stock prices.
Iterate through the array of stock prices and calculate the maximum profit that can be achieved by buying and selling at different points.
Keep track of the maximum profit after the first transaction and the maximum profit overall by considering different combinations of buy and sell points.
Ensure to sell the stock before buying agai...read more
Q55. What is Asset Management
Asset management is the process of managing and optimizing a company's assets to maximize their value and minimize risk.
Asset management involves identifying, tracking, and evaluating assets
It includes developing strategies to optimize asset performance and minimize risk
Examples of assets that can be managed include financial investments, real estate, and equipment
Asset management can be done in-house or outsourced to a third-party firm
Q56. what is custodian banking
Custodian banking involves holding and safeguarding financial assets on behalf of clients.
Custodian banks provide services such as asset safekeeping, settlement of trades, and corporate actions processing.
They also offer reporting and analytics to clients on their holdings and transactions.
Examples of custodian banks include State Street, BNY Mellon, and J.P. Morgan.
Custodian banking is important for institutional investors such as pension funds, mutual funds, and hedge funds...read more
Q57. Fenwick Tree Problem Statement
You are provided with an array/list ARR
consisting of 'N' integers, along with 'Q' queries. Each query can be of one of the following two types:
- Type 1 (Range Sum): Given two int...read more
The problem involves executing range sum and point update queries on an array using Fenwick Tree data structure.
Use Fenwick Tree to efficiently handle range sum and point update queries.
For range sum queries, calculate prefix sums and use them to compute the sum in the given range.
For point update queries, update the Fenwick Tree accordingly to reflect the changes in the array.
Ensure to handle the queries efficiently to meet the time constraints.
Example: Given array [3, 2, 1,...read more
Q58. Maximize Matrix Binary Score
You are provided with a 2-D matrix called MAT
consisting solely of 0s and 1s. Each row of the matrix can be viewed as a binary number, and the aggregate sum of these binary numbers ...read more
Given a binary matrix, maximize the score by toggling rows or columns to convert them to binary numbers and summing them up.
Iterate through each row and column to calculate the score of toggling that row or column
Keep track of the maximum score obtained by toggling rows or columns
Return the maximum score obtained
Q59. Sudoku Solver Problem Statement
You are provided with a 9x9 2D integer matrix MAT
representing a Sudoku puzzle. The empty cells in the Sudoku are denoted by zeros, while the other cells contain integers from 1 ...read more
Implement a function to solve a Sudoku puzzle by filling empty cells with valid numbers.
Iterate through each empty cell and try filling it with a valid number (1-9) that satisfies Sudoku rules.
Use backtracking to backtrack and try different numbers if a cell cannot be filled with a valid number.
Check rows, columns, and 3x3 sub-grids to ensure each digit appears only once in each.
Recursively solve the puzzle by filling empty cells until a valid solution is found.
Q60. Morse Code to English Problem Statement
You are provided with a string of morse code(s) of length N. Your task is to convert this morse code into the corresponding alphanumeric code consisting of lowercase Engl...read more
Convert Morse code to alphanumeric code using a predefined table.
Iterate through the morse code string and convert each morse code to its corresponding alphanumeric character using the given table.
Join the converted characters to form the final alphanumeric string.
Handle spaces between morse code characters by adding a space in the final alphanumeric string.
Q61. what is private equity
Private equity is a type of investment where funds are raised from investors to acquire or invest in companies that are not publicly traded.
Private equity firms typically buy a controlling stake in a company and then work to improve its operations and profitability before selling it for a profit.
Private equity investments are typically made in mature companies with a proven track record of success.
Private equity firms may also invest in distressed companies with the goal of t...read more
Q62. 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
The task is to find the total number of ways to make change for a specified value using given denominations.
Create a dynamic programming table to store the number of ways to make change for each value up to the specified value.
Iterate through each denomination and update the table accordingly.
The final answer will be the value in the table at the specified value.
Consider edge cases such as when the specified value is 0 or when there are no denominations provided.
Q63. Regular Expression Match Problem Statement
Given a string str
and a string pat
, where str
may contain wildcard characters '?' and '*'.
If a character is '?', it can be replaced with any single character. If a c...read more
Given a string with wildcard characters, determine if it can be transformed to match another string under given rules.
Iterate through both strings simultaneously, handling wildcard characters '?' and '*' accordingly.
Use dynamic programming to keep track of matching characters.
Handle '*' by considering all possibilities of matching sequences.
Return true if at the end both strings match, false otherwise.
Q64. 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
Q65. Climbing the Leaderboard Problem Statement
In a game leaderboard, scores determine rankings where the highest score gets rank 1. Players with identical scores share the same rank, followed by the next rank down...read more
The task is to determine a player's leaderboard rank for each game score based on given leaderboard and game scores.
Iterate through each game score and compare it with leaderboard scores to determine the rank.
Use a hashmap to store the leaderboard scores and their corresponding ranks.
Handle cases where multiple players have the same score and share the same rank.
Return an array of ranks for each game score.
Q66. Flatten the Multi-Level Linked List Problem
You are provided with a multi-level linked list consisting of 'N' nodes. Each node contains a 'next' and 'child' pointer that may point to another node. Your task is ...read more
The task is to flatten a multi-level linked list into a singly linked list and return the head of the modified linked list.
Traverse the linked list and keep track of nodes with child pointers
Flatten the child linked list and merge it with the main linked list
Update the 'next' pointers to create a singly linked list
Return the head of the modified linked list
Q67. Design a HashSet
Create a HashSet data structure without using any built-in hash table libraries.
Functions Description:
1) Constructor: Initializes the data members as required. 2) add(value): Inserts an eleme...read more
Design a HashSet data structure with add, contains, and remove functions.
Implement a HashSet using an array and handling collisions using chaining or open addressing.
Use a hash function to map values to indices in the array.
For add function, insert the value at the hashed index.
For contains function, check if the value exists at the hashed index.
For remove function, delete the value at the hashed index and return it, or return -1 if not found.
Q68. Trapping Rain Water Problem Statement
You are given a long type array/list ARR
of size N
, representing an elevation map. The value ARR[i]
denotes the elevation of the ith
bar. Your task is to determine the tota...read more
Q69. Transitive Closure of Directed Graph Problem Statement
Given a directed graph with 'V' vertices and 'E' edges, determine if a vertex i
is reachable from vertex j
for all pairs of vertices (i, j)
. A vertex j
is ...read more
Determine reachability between all pairs of vertices in a directed graph.
Use Floyd Warshall algorithm to find transitive closure of the graph.
Initialize a V x V matrix with 1s on the diagonal and 0s elsewhere.
Update matrix by checking if there is a path from i to j through k.
Repeat the process for all vertices to get the transitive closure matrix.
Q70. Minimum Umbrellas Problem
You are provided with ‘N’ types of umbrellas, where each umbrella type can shelter a certain number of people. Given an array UMBRELLA
that indicates the number of people each umbrella...read more
Given 'N' types of umbrellas with different capacities, find the minimum number of umbrellas required to shelter exactly 'M' people.
Iterate through the umbrella capacities and try to cover 'M' people using the minimum number of umbrellas.
Sort the umbrella capacities in descending order to optimize the solution.
If it is not possible to cover 'M' people exactly, return -1.
Q71. Partition Set Into Two Subsets With Minimum Difference
Given an array of N non-negative integers, split the array into two subsets such that the absolute difference between their sums is minimized.
The task is ...read more
Split array into two subsets with minimum absolute difference between their sums.
Use dynamic programming to find the minimum absolute difference between the sums of two subsets.
Iterate through all possible sums of subsets and find the minimum difference.
Consider each element either being included in the first subset or the second subset.
Keep track of the minimum absolute difference found so far.
Return the minimum absolute difference between the sums of the two subsets.
Q72. 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
The task is to distribute candies to students based on their performance while minimizing the total candies distributed.
Create an array to store the minimum candies required for each student.
Iterate through the students' ratings array to determine the minimum candies needed based on the adjacent ratings.
Consider both left-to-right and right-to-left passes to ensure fair distribution.
Keep track of the total candies distributed and return the sum as the output.
Q73. Level Order Traversal Problem Statement
Given a binary tree of integers, return the level order traversal of the binary tree.
Input:
The first line contains an integer 'T', representing the number of test cases...read more
Level order traversal of a binary tree is returned for each test case.
Implement a function to perform level order traversal of a binary tree
Use a queue data structure to keep track of nodes at each level
Print the node values in level order traversal
Q74. Fastest Horse Problem Statement
Given ‘N’ horses running in separate lanes, each horse's finish time is provided in an array. You are tasked to process 'Q' queries. For each query, determine the time taken by t...read more
Given finish times of horses, find fastest horse in specified lane ranges for multiple queries.
Iterate through each query and find the minimum finish time within the specified range.
Use a loop to process each test case and query efficiently.
Ensure to handle edge cases like empty ranges or invalid inputs.
Optimize the solution to handle large input sizes efficiently.
Q75. Validate Binary Search Tree (BST)
You are given a binary tree with 'N' integer nodes. Your task is to determine whether this binary tree is a Binary Search Tree (BST).
BST Definition:
A Binary Search Tree (BST)...read more
Q76. Merge Intervals Problem Statement
You are provided with 'N' intervals, each containing two integers denoting the start time and end time of the interval.
Your task is to merge all overlapping intervals and retu...read more
Q77. Print Nodes at Distance K from a Given Node
Given an arbitrary binary tree, a node of the tree, and an integer 'K', find all nodes that are at a distance K from the specified node, and return a list of these no...read more
Given a binary tree, a target node, and an integer K, find all nodes at distance K from the target node.
Traverse the binary tree to find the target node.
Use BFS to traverse the tree from the target node to nodes at distance K.
Keep track of the distance while traversing the tree.
Return the values of nodes at distance K in any order.
Q78. Flatten The Multi-Level Linked List
You are given a multi-level linked list of N nodes, where each node can have two pointers: next and child. Flatten this multi-level linked list into a singly linked list, and...read more
Flatten a multi-level linked list into a singly linked list and return the head of the flattened list.
Traverse the linked list in level order
Use a stack to keep track of nodes with child pointers
Merge the child nodes into the main list
Q79. The Celebrity Problem
Imagine there are 'N' people at a party, each assigned a unique ID from 0 to N-1. A celebrity at the party is a person who is known by everyone but knows no one else.
Problem Statement:
Yo...read more
Identify the celebrity at a party where one person knows everyone but is not known by anyone.
Use a two-pointer approach to eliminate non-celebrities.
Start with two pointers at the beginning and end, move them based on 'knows' results.
If A knows B, A cannot be the celebrity; move A pointer. If A does not know B, B cannot be the celebrity; move B pointer.
Repeat until only one person remains, check if this person is known by everyone and knows no one.
Return the ID of the celebri...read more
Q80. Partition to K Equal Sum Subsets Problem
Given an array of integers and a positive integer 'K', determine if it is possible to divide the array into 'K' non-empty subsets such that the sum of elements in each s...read more
The problem involves dividing an array into K subsets with equal sum.
Use backtracking to try all possible combinations of dividing the array into K subsets.
Keep track of the sum of elements in each subset and check if they are equal to the target sum.
Optimize the backtracking algorithm by pruning branches that cannot lead to a valid solution.
Consider edge cases such as empty array, negative numbers, and unequal division of elements.
Ensure that the sum of all elements in the a...read more
Q81. Find Pairs in a Doubly-Linked List
A sorted doubly-linked list of distinct positive integers is provided, along with an integer 'X'. Your task is to identify and print all unique pairs from the list whose sum e...read more
Find pairs in a sorted doubly-linked list whose sum equals a given integer 'X'.
Traverse the list from both ends to find pairs with sum equal to 'X'.
Use two pointers approach to efficiently find the pairs.
Handle cases where the sum is less than, equal to, or greater than 'X'.
Q82. Largest Rectangle in Histogram Problem Statement
You are given an array/list HEIGHTS
of length N
, where each element represents the height of a histogram bar. The width of each bar is considered to be 1.
Your t...read more
Compute the area of the largest rectangle that can be formed within the bounds of a given histogram.
Iterate through the histogram bars and maintain a stack to keep track of increasing heights.
Calculate the area of the rectangle by considering the current height as the height of the rectangle and the width as the difference between the current index and the index at the top of the stack.
Update the maximum area found so far and return it as the result.
Q83. Smallest Window Problem Statement
Given two strings S
and X
containing random characters, the task is to find the smallest substring in S
which contains all the characters present in X
.
Input:
The first line co...read more
Find the smallest substring in a given string that contains all characters from another string.
Use a sliding window approach to find the smallest window in S that contains all characters in X.
Keep track of the characters in X using a hashmap.
Move the right pointer to expand the window until all characters in X are found, then move the left pointer to shrink the window while maintaining the condition.
Return the smallest window found.
Example: S = 'abdd', X = 'bd' -> Output: 'bd...read more
Q84. 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
The task is to find the smallest number greater than the given number with the same set of digits.
Iterate from right to left to find the first digit that can be swapped with a smaller digit to make the number greater.
Swap this digit with the smallest digit to its right that is greater than it.
Sort all digits to the right of the swapped digit in ascending order to get the smallest number.
Q85. Maximum Sum of Non-Adjacent Nodes in a Binary Tree
Given a binary tree with integer values assigned to each node, select nodes such that their sum is maximum, ensuring no two adjacent nodes are picked.
Input:
T...read more
Find the maximum sum of non-adjacent nodes in a binary tree.
Use dynamic programming to keep track of the maximum sum at each node considering whether to include or exclude the current node.
Recursively traverse the binary tree while keeping track of the maximum sum of non-adjacent nodes.
Consider the cases where the current node is included in the sum or excluded from the sum to calculate the maximum possible sum.
Q86. Merge Overlapping Intervals Problem Statement
Given a specified number of intervals, where each interval is represented by two integers denoting its boundaries, the task is to merge all overlapping intervals an...read more
Merge overlapping intervals and return sorted list of merged intervals.
Identify overlapping intervals based on start and end times
Merge overlapping intervals to form new intervals
Sort the merged intervals in ascending order of start times
Q87. Longest Palindromic Substring Problem Statement
You are provided with a string STR
of length N
. The goal is to identify the longest palindromic substring within this string. In cases where multiple palindromic ...read more
Given a string, find the longest palindromic substring, prioritizing the one with the smallest start index.
Iterate through the string and expand around each character to find palindromes.
Keep track of the longest palindrome found and its starting index.
Return the longest palindromic substring with the smallest start index.
Q88. Sort Array of Strings Problem Statement
Given an array of strings ARRSTR[]
of size N
, and a character C
, your task is to sort the ARRSTR[]
array according to a new alphabetical order that starts with the given ...read more
Sort an array of strings based on a new alphabetical order starting with a given character.
Iterate through the array of strings and compare each string with the given character to determine the new order.
Use a custom comparator function to sort the strings based on the new alphabetical order.
Handle lowercase English alphabet characters and strings of varying lengths.
Q89. Reverse Linked List in Groups of K
You are provided with a linked list containing 'N' nodes and an integer 'K'. The task is to reverse the linked list in groups of size K, which means reversing the nodes in eac...read more
Reverse a linked list in groups of size K.
Iterate through the linked list in groups of size K
Reverse each group of nodes
Handle cases where the number of elements in the last group is less than K
Q90. Rectangle Area Problem Statement
You are provided with a list of rectangles, each defined by an array of four integers: Rectangle[i] = [x1, y1, x2, y2]
. Here, (x1, y1)
represents the bottom-left corner, and (x2...read more
Calculate total area covered by overlapping rectangles given their coordinates.
Iterate through each rectangle and calculate its area
Check for overlaps between rectangles and calculate the overlapping area
Sum up the areas of all rectangles and subtract the total overlapping area to get the final result
Q91. Cousin Nodes in a Binary Tree
Determine if two nodes in a binary tree are cousins. Nodes are considered cousins if they are at the same level and have different parents.
Explanation:
In a binary tree, each node...read more
Determine if two nodes in a binary tree are cousins based on level and parent criteria.
Traverse the tree to find the levels and parents of the given nodes.
Check if the nodes are at the same level and have different parents.
Return 'YES' if the nodes are cousins, 'NO' otherwise.
Q92. Two and Four Wheeler Roads Problem Statement
There is a country with N
cities and M
bidirectional roads of 3 types:
Type 1: Two Wheeler Road - Only vehicles with two wheels can use this road. Type 2: Four Wheel...read more
Determine the maximum number of roads that can be removed while ensuring a path exists for every pair of cities for two-wheeler and four-wheeler vehicles.
Identify the type of road (two-wheeler, four-wheeler, or both) and its impact on the connectivity between cities.
Consider the constraints provided in the input to optimize the solution.
Remove roads strategically to maximize the number of roads removed while maintaining connectivity.
If not all cities can be reached, return -1...read more
Q93. Count Pairs with Given Sum
Given an integer array/list arr
and an integer 'Sum', determine the total number of unique pairs in the array whose elements sum up to the given 'Sum'.
Input:
The first line contains ...read more
Count the total number of unique pairs in an array whose elements sum up to a given value.
Use a hashmap to store the frequency of each element in the array.
Iterate through the array and for each element, check if (Sum - element) exists in the hashmap.
Increment the count of pairs if the complement exists in the hashmap.
Q94. LCA in a Binary Search Tree
You are given a binary search tree (BST) containing N nodes. Additionally, you have references to two nodes, P and Q, within this BST.
Your task is to determine the Lowest Common Anc...read more
Find the Lowest Common Ancestor (LCA) of two nodes in a Binary Search Tree (BST).
Traverse the BST from the root node to find the LCA of nodes P and Q.
Compare the values of nodes P and Q with the current node's value to determine the LCA.
If both nodes are on the same side of the current node, move to that side; otherwise, the current node is the LCA.
Handle cases where one node is the ancestor of the other or when one of the nodes is the current node.
Q95. Minimum Number of Swaps to Sort an Array
Find the minimum number of swaps required to sort a given array of distinct elements in ascending order.
Input:
T (number of test cases)
For each test case:
N (size of the...read more
The minimum number of swaps required to sort a given array of distinct elements in ascending order.
Use a graph-based approach to find cycles in the array
Count the number of swaps needed to fix each cycle
Sum up the swaps needed for all cycles to get the total minimum swaps
Q96. Consecutive Sum Representation of a Number
Find the number of ways the given number 'N' can be expressed as the sum of two or more consecutive natural numbers.
Example:
Input:
N = 9
Output:
2
Explanation:
The n...read more
Find the number of ways a given number can be expressed as the sum of two or more consecutive natural numbers.
Use a sliding window approach to iterate through all possible consecutive sums.
Keep track of the sum of the current window and adjust the window size accordingly.
Count the number of valid consecutive sum representations of the given number.
Example: For N = 9, valid representations are 2 + 3 + 4 and 4 + 5, so the output is 2.
Q97. Problem Statement: Minimize the Maximum
You are given an array of integers and an integer K
. For each array element, you can adjust it by increasing or decreasing it by a value of K
. Your goal is to minimize th...read more
The goal is to minimize the difference between the maximum and minimum elements of an array by adjusting each element by a given value.
Iterate through each test case and calculate the minimum possible difference between the maximum and minimum elements after modifications.
For each element in the array, consider increasing or decreasing it by the given value K to minimize the overall difference.
Return the calculated minimum difference for each test case.
Q98. Minimum Number of Platforms Needed Problem Statement
You are given the arrival and departure times of N trains at a railway station for a particular day. Your task is to determine the minimum number of platform...read more
The minimum number of platforms needed at a railway station to avoid train waiting times is determined based on arrival and departure times.
Sort the arrival and departure times in ascending order.
Iterate through the times and keep track of the number of platforms needed at any given time.
Update the minimum number of platforms needed as you iterate through the times.
Return the minimum number of platforms needed.
Q99. Counting Rectangles in a Grid
Given a grid with 'M' rows and 'N' columns, determine the total number of unique rectangles that can be formed using the rows and columns of this grid.
Input:
The first line contai...read more
The total number of unique rectangles that can be formed in a grid with M rows and N columns.
The total number of unique rectangles can be calculated using the formula: (M * (M + 1) / 2) * (N * (N + 1) / 2)
Each rectangle can be formed by selecting two rows and two columns from the grid
For example, for a grid with 3 rows and 4 columns, the total number of unique rectangles is 60
Q100. Check if Two Trees are Mirror
Given two arbitrary binary trees, your task is to determine whether these two trees are mirrors of each other.
Explanation:
Two trees are considered mirror of each other if:
- The r...read more
Check if two binary trees are mirrors of each other based on specific criteria.
Compare the roots of both trees.
Check if the left subtree of the first tree is the mirror of the right subtree of the second tree.
Verify if the right subtree of the first tree is the mirror of the left subtree of the second tree.
More about working at Goldman Sachs
Top HR Questions asked in Codingal
Interview Process at Codingal
Top Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month