
Goldman Sachs

50+ Goldman Sachs Software Developer Intern Interview Questions and Answers
Q1. 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.
Q2. 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.
Q3. 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.
Q4. 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.
Q5. 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
Q6. 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.
Q7. 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.
Q8. 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 to group anagrams together.
Use a hashmap to store the sorted string as key and the original string as value.
Return the values of the hashmap as the grouped anagrams.
Q9. 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.
Q10. 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
Q11. 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.
Q12. 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
Q13. 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.
Q14. 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
Implement a function to determine a player's leaderboard rank for each game score.
Iterate through the game scores and compare them with the leaderboard scores to determine the rank.
Handle cases where players have identical scores by assigning them the same rank.
Ensure the leaderboard scores are in descending order and game scores are in ascending order.
Return the ranks for each game score in an array.
Q15. 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
Q16. 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
Q17. 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 of linked lists to handle collisions.
Use a hash function to determine the index in the array for each element.
For add function, check if the element already exists before inserting.
For contains function, search for the element in the corresponding linked list.
For remove function, find and remove the element from the linked list.
Example: If Q=5, queries are [(1, 5), (2, ...read more
Q18. 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.
Q19. 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.
Q20. 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
Validate if a given binary tree is a Binary Search Tree (BST) or not.
Check if the left subtree of a node contains only nodes with data less than the node's data.
Check if the right subtree of a node contains only nodes with data greater than the node's data.
Recursively check if both the left and right subtrees are also binary search trees.
Example: For a node with data 4, left subtree nodes should be less than 4 and right subtree nodes should be greater than 4.
Q21. 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
Q22. 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.
Q23. 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.
Q24. 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.
Q25. 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
Q26. 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.
Q27. 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.
Q28. 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
Q29. 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
Q30. 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.
Use dynamic programming to solve this problem efficiently.
Create a 2D array to store the number of ways to make change for each value up to the specified value.
Iterate through each denomination and update the array accordingly.
The final answer will be in the last cell of the array.
Example: For N=3, D=[1, 2, 3], V=4, the output is 4 as there are 4 ways to make change for...read more
Q31. 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.
Q32. 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.
Q33. 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
Q34. 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.
Q35. Middle of a Linked List
You are given the head node of a singly linked list. Your task is to return a pointer pointing to the middle of the linked list.
If there is an odd number of elements, return the middle ...read more
Return the middle element of a singly linked list, or the one farther from the head if there are even elements.
Traverse the linked list with two pointers, one moving twice as fast as the other
When the fast pointer reaches the end, the slow pointer will be at the middle
If there are even elements, return the one that is farther from the head node
Handle edge cases like linked list of size 1 or empty list
Q36. Rearrange Odd and Even Places
Given the head of a singly linked list, your task is to group all the nodes with odd indices together followed by the nodes with even indices, and then return the reordered list's ...read more
Rearrange nodes in a singly linked list by grouping odd and even indices together while maintaining relative order.
Create two separate linked lists for odd and even nodes
Traverse the original list and append nodes to respective odd/even lists
Connect the last node of odd list to the head of even list
Return the head of the rearranged list
Q37. Excel Sheet Column Number Problem Statement
You are provided with a string STR
representing a column title in an Excel Sheet. Your task is to determine the corresponding column number.
Example:
A typical exampl...read more
Given a string representing an Excel column title, determine the corresponding column number.
Iterate through the characters of the string from right to left
Calculate the corresponding value of each character based on its position and multiply by 26^position
Sum up all the values to get the final column number
Q38. 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
Q39. 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.
Q40. Beautiful City Problem Statement
Ninja plans to visit a city where each house is connected via roads in a binary tree structure. Each level of the tree can have at most 2^K houses. Houses at the same level cann...read more
The task is to connect houses at the same level in a binary tree structure using 'next' pointers.
Traverse the binary tree level by level using BFS
Connect nodes at the same level using 'next' pointers
Use a queue to keep track of nodes at each level
Q41. Matrix Rank Calculation
Given a matrix ARR
of dimensions N * M
, your task is to determine the rank of the matrix ARR
.
Explanation:
The rank of a matrix is defined as:
(a) The maximum number of linearly independ...read more
Calculate the rank of a matrix based on the number of linearly independent column or row vectors.
Determine the rank of the matrix by finding the maximum number of linearly independent column vectors or row vectors.
Check for linear independence by verifying if there is a nontrivial linear combination that equates to the zero vector.
Implement a function that takes the matrix dimensions and elements as input and returns the rank of the matrix.
Q42. Number of Triangles in an Undirected Graph
Determine how many triangles exist in an undirected graph. A triangle is defined as a cyclic path of length three that begins and ends at the same vertex.
Input:
The f...read more
Count the number of triangles in an undirected graph using adjacency matrix.
Iterate through all possible triplets of vertices to check for triangles.
For each triplet, check if there are edges between all three vertices.
Increment the count if a triangle is found.
Return the total count of triangles for each test case.
Q43. Maximum Value of an Equation Problem Statement
Given an array/list of integers points
containing coordinates (x, y) of N points in a 2D plane, sorted by x-values in non-decreasing order. You need to determine t...read more
Find the maximum value of an equation involving coordinates of points in a 2D plane.
Iterate through all pairs of points and calculate the equation value
Keep track of the maximum value encountered
Consider the constraint |xi - xj| ≤ K while calculating the equation value
Q44. 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.
Consider edge cases where the stock prices ...read more
Q45. Problem: Search In Rotated Sorted Array
Given a sorted array that has been rotated clockwise by an unknown amount, you need to answer Q
queries. Each query is represented by an integer Q[i]
, and you must determ...read more
Search for integers in a rotated sorted array efficiently.
Use binary search to find the pivot point where the array is rotated.
Based on the pivot point, apply binary search on the appropriate half of the array.
Return the index of the integer if found, else return -1.
Example: For input N=5, A=[4, 5, 6, 7, 0, 1, 2], Q=3, Q[i]=[0, 3, 6], output should be 4, -1, 2.
Q46. Rearrange Words in a Sentence
You are provided with a sentence 'TEXT'. Each word in the sentence is separated by a single space, and the sentence starts with a capital letter. Your task is to rearrange the word...read more
Rearrange words in a sentence based on increasing order of their length.
Split the sentence into words and calculate the length of each word.
Sort the words based on their lengths, keeping the original order for words with the same length.
Join the sorted words back into a sentence.
Q47. Excel Column Number Conversion
Given a column title as it appears in an Excel sheet, your task is to return its corresponding column number.
Example:
Input:
S = "AB"
Output:
28
Explanation:
The sequence is as f...read more
Convert Excel column title to corresponding column number.
Map each letter to its corresponding value (A=1, B=2, ..., Z=26)
Iterate through the input string from right to left, calculate the value of each letter based on its position and add it to the result
Multiply the result by 26 for each additional letter to the left
Q48. First Non-Repeating Character Problem Statement
You are given a string consisting of English alphabet characters. Your task is to identify and return the first character in the string that does not repeat. If e...read more
Given a string, find and return the first non-repeating character. If none exists, return the first character of the string.
Create a dictionary to store the count of each character in the string.
Iterate through the string and populate the dictionary.
Iterate through the string again and return the first character with count 1.
If no such character exists, return the first character of the string.
Q49. Ninja's Apartment Problem Statement
Ninja plans to build an apartment in the shape of a rectangle. The goal is to determine the length and breadth of this rectangle such that the length is greater than the brea...read more
Given the area of a rectangle, find the length and breadth such that the length is greater than the breadth and the difference between them is minimized.
Iterate through possible combinations of length and breadth
Calculate the area for each combination and check if length is greater than breadth
Select the combination with minimal difference between length and breadth
Q50. Excel Column Number Problem Statement
Given a column title as it appears in an Excel sheet, return its corresponding column number.
Example:
Input:
"AB"
Output:
28
Explanation:
Column title "AB" corresponds to ...read more
Convert Excel column title to corresponding column number
Iterate through the characters in the column title from right to left
Calculate the corresponding value of each character using its position in the alphabet
Multiply the value by 26 raised to the power of its position from right
Sum up all the values to get the final column number
More about working at Goldman Sachs

Interview Process at Goldman Sachs Software Developer Intern

Top Software Developer Intern Interview Questions from Similar Companies








Reviews
Interviews
Salaries
Users/Month

