
Goldman Sachs

300+ Goldman Sachs Interview Questions and Answers
Q1. Ninja and the Game of Words
In this game, Ninja is provided with a string STR
that might contain spaces, and a list or array WORDS
consisting of N
word strings. Ninja's task is to determine how many times each ...read more
The task is to determine the frequency of each word in a list of words that appears in a given string.
Iterate through each word in the list of words and count its frequency in the given string.
Maintain the order of words as provided in the list.
Return the frequency of each word in an array of strings.
Q2. 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.
Q3. Wildcard Pattern Matching Problem Statement
Implement a wildcard pattern matching algorithm to determine if a given wildcard pattern matches a text string completely.
The wildcard pattern may include the charac...read more
Implement a wildcard pattern matching algorithm to determine if a given wildcard pattern matches a text string completely.
Create a recursive function to match the pattern with the text character by character
Handle cases for '?' and '*' characters in the pattern
Keep track of the current position in both pattern and text strings
Return 'True' if the pattern matches the text completely, otherwise return 'False'
Q4. Chocolate Distribution Problem
You are given an array/list CHOCOLATES
of size 'N', where each element represents the number of chocolates in a packet. Your task is to distribute these chocolates among 'M' stude...read more
The task is to distribute chocolates among students such that the difference between the largest and smallest number of chocolates is minimized.
Sort the array of chocolates packets in ascending order.
Iterate through the array and find the minimum difference between the chocolates packets distributed to students.
Return the minimum difference as the output.
Q5. 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
Q6. Digits Decoding Problem
Ninja has a string of characters from 'A' to 'Z', encoded using their numeric values (A=1, B=2, ..., Z=26). The encoded string is given as a sequence of digits (SEQ). The task is to dete...read more
The task is to determine the number of possible ways to decode a given sequence of digits back into a string of characters from 'A' to 'Z'.
Use dynamic programming to solve the problem efficiently.
Consider different cases like single digit decoding, double digit decoding, and combinations of both.
Implement a recursive function with memoization to avoid redundant calculations.
Handle edge cases such as '0' and '00' in the input sequence.
Return the final count modulo 10^9 + 7 as ...read more
Q7. Group Anagrams Together
Given an array/list of strings STR_LIST
, group the anagrams together and return each group as a list of strings. Each group must contain strings that are anagrams of each other.
Example:...read more
Group anagrams together in a list of strings.
Iterate through the list of strings and sort each string alphabetically.
Use a hashmap to group anagrams together based on the sorted string as key.
Return the values of the hashmap as the grouped anagrams.
Q8. 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.
Q9. Gold Mine Problem Statement
You are provided with a gold mine, represented as a 2-dimensional matrix of size N x M with N rows and M columns. Each cell in this matrix contains a positive integer representing th...read more
The task is to determine the maximum amount of gold a miner can collect in a gold mine by moving in allowed directions.
Create a 2D array to represent the gold mine matrix.
Implement a dynamic programming approach to calculate the maximum amount of gold that can be collected.
Consider the constraints provided to optimize the solution.
Iterate through the matrix to calculate the maximum gold collection.
Keep track of the maximum gold collected at each cell based on the allowed move...read more
Q10. 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]
Q11. Boyer Moore Algorithm for Pattern Searching
You are given a string text
and a string pattern
. Your task is to find all occurrences of pattern
in the string text
and return an array of indexes of all those occur...read more
Implement Boyer Moore Algorithm to find all occurrences of a pattern in a given text.
Use Boyer Moore Algorithm to efficiently search for the pattern in the text.
Iterate through the text and compare the pattern with each substring to find matches.
Return an array of indexes where the pattern is found, or -1 if no occurrence is found.
Q12. If you are asked to play a game where you toss a fair coin again and again until you get consecutive heads and win Re. 1 or you get consecutive tails and lose and quit, how much will you be willing to pay to pl...
read moreI would be willing to pay 50 paise to play this game.
The expected value of the game is 50 paise.
This is because the probability of getting consecutive heads is 1/3 and the probability of getting consecutive tails is 1/4.
Therefore, the expected value of the game is (1/3 * 1) - (1/4 * 1) = 1/12 = 8.33 paise.
However, since the minimum amount that can be won is Re. 1, I would be willing to pay 50 paise to play the game.
Q13. Circular Tour Problem Statement
Consider a circular path with N petrol pumps. Each pump is numbered from 0 to N-1. Every petrol pump provides:
- The amount of petrol available at the pump.
- The distance to the ne...read more
The task is to find the first petrol pump from which a truck can complete a full circle or determine if it's impossible.
Iterate through each petrol pump and calculate the remaining petrol after reaching the next pump.
If the remaining petrol is negative at any point, reset the starting pump to the next pump and continue.
If the total remaining petrol at the end is non-negative, return the index of the starting pump.
If the total remaining petrol is negative, it's impossible to c...read more
Q14. 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]).
Q15. 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
Q16. 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.
Q17. Greatest Common Divisor Problem Statement
You are tasked with finding the greatest common divisor (GCD) of two given numbers 'X' and 'Y'. The GCD is defined as the largest integer that divides both of the given...read more
Finding the greatest common divisor (GCD) of two given numbers 'X' and 'Y'.
Iterate through each test case and calculate GCD using Euclidean algorithm
Handle edge cases like when one of the numbers is 0
Output the GCD for each test case
Q18. 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.
Q19. 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.
Q20. 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.
Q21. 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.
Q22. An IT sector multinational wants to expand its business into more countries. Suggest a strategy. This was the question given in the VC round by the Partner. It was followed by a lot of numerical and qualitative...
read moreTo expand into more countries, the IT sector multinational can adopt a market entry strategy that includes market research, partnerships, localization, and scalability.
Conduct thorough market research to identify potential countries for expansion
Establish strategic partnerships with local companies to leverage their knowledge and networks
Adapt products and services to meet the specific needs and preferences of each target market
Ensure scalability of operations to handle the i...read more
Q23. 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.
Q24. 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.
Q25. 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
Q26. 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
Q27. 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.
Q28. 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.
Q29. 1. What is the probability that a person starting at 1 and who takes single steps ahead/back with equal probabilities reach 0 before 100?
The probability is 1/2.
The person can either move forward or backward with equal probabilities.
The probability of reaching 0 before 100 is 1/2.
This is a simple random walk problem.
Q30. 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
Q31. 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.
Q32. 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.
Q33. 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
Q34. 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
Q35. 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
Q36. 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
Q37. 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.
Q38. 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
Q39. 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.
Q40. 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
Q41. 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.
Q42. Count Pairs with Difference K
Given an array of integers and an integer K
, determine and print the count of all pairs in the array that have an absolute difference of K
.
Input:
The first line of the input conta...read more
Q43. First and Last Position of an Element in a Sorted Array
Given a sorted array/list ARR
consisting of ‘N’ elements, and an integer ‘K’, your task is to find the first and last occurrence of ‘K’ in ARR
.
Explanatio...read more
Q44. 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.
Q45. Given 10 balls which weigh the same, except for one, and a beam balance, what is the minimum number of weighs to find the odd ball?
The minimum number of weighs to find the odd ball is 4.
Divide the 10 balls into 3 groups of 3, 3, and 4.
Compare the weights of the two groups of 3 balls.
If the weights are equal, the odd ball is in the group of 4.
If the weights are unequal, the odd ball is in the lighter group of 3.
Divide the lighter group of 3 balls into individual balls and compare their weights.
The odd ball will be identified in the 4th weigh.
Q46. 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
Q47. 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
Q48. 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.
Q49. How many years will it take the Delhi Metro to break even?
The Delhi Metro is expected to break even in 2025.
The Delhi Metro has been expanding rapidly and has seen a steady increase in ridership.
The metro has been able to generate revenue through advertising and property development.
The government has also provided financial support to the metro.
Based on current projections, the Delhi Metro is expected to break even in 2025.
Q50. 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
Q51. 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.
Q52. Dice rolled several times until sum of outcomes till now comes greater than equal to hundred. What is most likely number to occur as final sum?
The most likely number to occur as the final sum is 100.
The sum of the outcomes of the dice rolls will keep increasing until it reaches or exceeds 100.
Since the dice have equal probabilities for each outcome, the sum will have a higher chance of reaching 100.
The probability of rolling a sum greater than 100 decreases as the sum gets larger.
Q53. 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
Q54. 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
Q55. Why are gold prices increasing and why are US treasury bonds still valuable?
Gold prices are increasing due to economic uncertainty and inflation concerns. US treasury bonds remain valuable due to their safe-haven status and reliable returns.
Gold prices are increasing due to economic uncertainty and inflation concerns.
Investors often turn to gold as a safe-haven asset during times of market volatility.
The demand for gold is also influenced by factors such as geopolitical tensions and central bank policies.
US treasury bonds are still valuable because t...read more
Q56. 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
Q57. 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.
Q58. Given an island in the center of a lake, and you are standing outside the lake, how would you reach the center?
To reach the center of the island, one can use a boat or any other means to cross the lake.
Use a boat to reach the island
Swim across the lake if it's not too far
If the lake is frozen, walk or skate across the ice
If there is a bridge or causeway connecting the island, use it to reach the center
Q59. How many airplanes are flying in the Indian sky at the moment?
The exact number of airplanes flying in the Indian sky at the moment is not available.
The number of airplanes flying in the Indian sky changes constantly.
It depends on factors such as time of day, weather conditions, and airline schedules.
However, on average, there are around 2,000 flights in the Indian airspace at any given time.
This number includes both domestic and international flights.
The Indian aviation industry has been growing rapidly in recent years, with more and mo...read more
Q60. 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.
Q61. 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.
Q62. 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
Q63. 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.
Q64. 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.
Q65. 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
Q66. 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.
Q67. Cutting three random points on the circle of radius 1 centered at (0,0) . What is probability that point (1,0) lies in longest cut
Finding probability of point (1,0) lying in longest cut of three random points on circle of radius 1 centered at (0,0)
The longest cut will be the one that spans the smallest angle between two of the three points
The probability can be found by calculating the area of the region where the longest cut includes point (1,0)
This can be done by finding the angle between (1,0) and the two other points and using trigonometry to calculate the area of the corresponding sector of the cir...read more
Q68. 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
Q69. 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
Q70. 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
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. 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.
Q73. Convert a Number to Words
Given an integer number num
, your task is to convert 'num' into its corresponding word representation.
Input:
The first line of input contains an integer ‘T’ denoting the number of tes...read more
Convert a given integer number into its corresponding word representation.
Implement a function that takes an integer as input and returns the word representation of the number in English lowercase letters.
Break down the number into its individual digits and convert each digit into its corresponding word form.
Handle special cases like numbers between 10 and 19, multiples of 10, and numbers with zeros in between.
Concatenate the word forms of individual digits to form the final ...read more
Q74. 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
Q75. LRU Cache Design Problem Statement
Design and implement a data structure for a Least Recently Used (LRU) cache that supports the following operations:
get(key)
- Retrieve the value associated with the specifie...read more
Design and implement a Least Recently Used (LRU) cache data structure that supports get and put operations with a specified capacity.
Implement a doubly linked list to keep track of the order of keys based on their usage.
Use a hashmap to store key-value pairs for quick access and updates.
When a key is accessed or updated, move it to the front of the linked list to mark it as the most recently used.
When the cache reaches its capacity, evict the least recently used item from the...read more
Q76. 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.
Q77. 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.
Q78. 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
Q79. 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.
Q80. 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
Q81. 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
A parking lot system is designed to efficiently manage parking spaces and provide convenience to users.
The design includes entry and exit points for vehicles.
Parking spaces are clearly marked and organized for easy navigation.
There may be designated areas for different types of vehicles, such as compact cars or motorcycles.
The system may incorporate technology like sensors or cameras to monitor occupancy and assist in finding available spots.
Payment methods and ticketing syst...read more
Q83. 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
Q84. 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'.
Q85. 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.
Q86. 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
Q87. 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
Q88. 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
Q89. 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.
Q90. 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.
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. Pair Sum Problem Statement
You are provided with an array ARR
consisting of N
distinct integers in ascending order and an integer TARGET
. Your objective is to count all the distinct pairs in ARR
whose sum equal...read more
Count distinct pairs in an array whose sum equals a given target.
Use two pointers approach to iterate through the array and find pairs with sum equal to target.
Keep track of visited elements to avoid counting duplicate pairs.
Return -1 if no such pair exists with the given target.
Q93. 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.
Q94. 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
Q95. 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
Q96. 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.
Q97. 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.
Q98. 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
Q99. 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
Q100. DFS Traversal Problem Statement
Given an undirected and disconnected graph G(V, E)
, where V
is the number of vertices and E
is the number of edges, the connections between vertices are provided in the 'GRAPH' m...read more
DFS traversal problem to find connected components in an undirected and disconnected graph.
Use Depth First Search (DFS) algorithm to traverse the graph and find connected components
Maintain a visited array to keep track of visited vertices
Iterate through all vertices and perform DFS on unvisited vertices to find connected components
More about working at Goldman Sachs

Top HR Questions asked in Goldman Sachs
Interview Process at Goldman Sachs

Top Interview Questions from Similar Companies








Reviews
Interviews
Salaries
Users/Month

