
Microsoft Corporation


700+ Microsoft Corporation Interview Questions and Answers
Q101. Find Nodes at Distance K in a Binary Tree
Your task is to find all nodes that are exactly a distance K from a given node in an arbitrary binary tree. The distance is defined as the number of edges between nodes...read more
Find all nodes at distance K from a given node in a binary tree.
Perform a depth-first search starting from the target node to find nodes at distance K.
Use a recursive function to traverse the tree and keep track of the distance from the target node.
Maintain a set to store visited nodes to avoid revisiting them.
Return the list of nodes found at distance K from the target node.
Example: If the target node is 5 and K is 2 in the given tree, the output should be [7, 4, 0, 8].
Q102. My Calendar Problem Statement
Given N
events, each represented with a start
and end
time as intervals, i.e., booking on the half-open interval [start, end). Initially, the calendar is empty. A new event can be ...read more
Given N events with start and end times, determine if each event can be added to the calendar without causing a triple booking.
Iterate through each event and check if adding it causes a triple booking by comparing its interval with previous events
Use a data structure like a list or dictionary to keep track of booked intervals
Return 'True' if the event can be added without causing a triple booking, 'False' otherwise
Q103. What is deadlock?Conditions for that?What are the methods to prevent it?Write code to prevent the deadlock for OS, considering that there are two processes P0 and P1 in OS and they are requesting resources dyna...
read moreDeadlock is a situation where two or more processes are unable to proceed due to a circular dependency on resources.
Deadlock occurs when two or more processes are waiting for resources held by each other.
Conditions for deadlock are mutual exclusion, hold and wait, no preemption, and circular wait.
Methods to prevent deadlock include resource allocation graph, banker's algorithm, and deadlock avoidance.
To prevent deadlock in OS, use resource allocation graph and banker's algori...read more
Q104. Remove K Digits Problem Statement
You are given a non-negative integer represented as a string num
and an integer k
. Your task is to determine the smallest possible integer by removing exactly k
digits from num...read more
Given a non-negative integer as a string and an integer k, find the smallest possible integer after removing k digits.
Use a stack to keep track of the digits in non-decreasing order from left to right.
Pop elements from the stack if the current digit is smaller than the top of the stack and k is greater than 0.
Handle edge cases like leading zeros and ensuring the final result is not an empty string.
Example: For num = "1432219" and k = 3, the smallest possible integer after rem...read more
Q105. Minimum Operations Problem Statement
You are given an array 'ARR'
of size 'N'
consisting of positive integers. Your task is to determine the minimum number of operations required to make all elements in the arr...read more
Determine minimum operations to make all array elements equal using addition, subtraction, multiplication, or division.
Iterate through array to find the maximum and minimum elements.
Calculate the difference between maximum and minimum elements.
The minimum number of operations needed is the difference between the maximum and minimum elements.
Q106. Left View of a Binary Tree Problem Statement
Given a binary tree, your task is to print the left view of the tree.
Example:
Input:
The input will be in level order form, with node values separated by a space. U...read more
Print the left view of a binary tree given in level order form.
Traverse the tree level by level and print the first node of each level (leftmost node).
Use a queue to keep track of nodes at each level.
Time complexity should be O(n) where n is the number of nodes in the tree.
Q107. Time complexity of a function f(m) is O(m). If the array[i...n] > contains either 1 or 0 in each of it's locations, determine the worst > case time complexity of the following piece of code written in C-like >...
read moreDetermining worst case time complexity of a code snippet with given time complexity of a function and array
The time complexity of the given code snippet is O(n)
The function f(m) is called only when a 0 is encountered in the array
The worst case time complexity is O(n)
The code snippet iterates through the entire array once
Q108. Pair Sum Problem Statement
You are given an integer array 'ARR' of size 'N' and an integer 'S'. Your task is to find and return a list of all pairs of elements where each sum of a pair equals 'S'.
Note:
Each pa...read more
Find pairs of elements in an array that sum up to a given value, sorted in a specific order.
Iterate through the array and for each element, check if the complement (S - current element) exists in a set.
If the complement exists, add the pair to the result list.
Sort the result list based on the criteria mentioned in the problem statement.
Q109. Median of Two Sorted Arrays
Given two sorted arrays A
and B
of sizes N
and M
, find the median of the merged array formed by combining arrays A
and B
. If the total number of elements, N + M
, is even, the median ...read more
Find the median of two sorted arrays by merging them and calculating the middle element(s).
Merge the two sorted arrays into one sorted array.
Calculate the median based on the total number of elements in the merged array.
If the total number of elements is even, take the mean of the two middle elements as the median.
Q110. Number of Islands Problem Statement
You are given a non-empty grid that consists of only 0s and 1s. Your task is to determine the number of islands in this grid.
An island is defined as a group of 1s (represent...read more
The task is to determine the number of islands in a grid of 0s and 1s connected horizontally, vertically, or diagonally.
Iterate through the grid and perform depth-first search (DFS) to find connected 1s forming islands
Mark visited cells to avoid counting the same island multiple times
Count the number of islands found during DFS traversal
Q111. Mirror String Problem Statement
Given a string S
containing only uppercase English characters, determine if S
is identical to its reflection in the mirror.
Example:
Input:
S = "AMAMA"
Output:
YES
Explanation:
T...read more
Determine if a given string is identical to its reflection in the mirror.
Iterate through the string and compare characters from start and end simultaneously.
If characters are not equal, return 'NO'.
If all characters match, return 'YES'.
Q112. Maximum Product Subarray Problem Statement
Given an array of integers, determine the contiguous subarray that produces the maximum product of its elements.
Explanation:
A subarray can be derived from the origin...read more
Find the contiguous subarray with the maximum product of elements in an array.
Iterate through the array and keep track of the maximum and minimum product ending at each index.
Update the maximum product by taking the maximum of current element, current element * previous maximum, and current element * previous minimum.
Update the minimum product by taking the minimum of current element, current element * previous maximum, and current element * previous minimum.
Return the maximu...read more
Q113. Quadratic Equation Root Finder
Given three integers A
, B
, and C
representing the coefficients of a quadratic equation A*X^2 + B*X + C = 0, your task is to determine the real roots of the equation. If no real ro...read more
Given coefficients of a quadratic equation, find the real roots or return -1 if no real roots exist.
Calculate the discriminant (B^2 - 4AC) to determine the nature of roots.
If discriminant is positive, roots are real and distinct. If zero, roots are real and repeated. If negative, roots are imaginary.
Use the quadratic formula to find the roots: (-B ± sqrt(discriminant)) / 2A.
Return the roots as integers, rounding down if necessary.
Q114. 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
Calculate the total amount of rainwater that can be trapped between given elevations in an array.
Iterate through the array and calculate the maximum height on the left and right of each bar.
Calculate the amount of water that can be trapped at each bar by taking the minimum of the maximum heights on the left and right.
Sum up the trapped water at each bar to get the total trapped water for the entire array.
Q115. Travelling Salesman Problem
Given a list of cities numbered from 0 to N-1 and a matrix DISTANCE
consisting of 'N' rows and 'N' columns, representing the distances between each pair of cities, find the shortest ...read more
Implement a function to find the shortest route visiting each city exactly once and returning to the starting city.
Use backtracking to explore all possible routes and find the minimum distance.
Keep track of visited cities to ensure each city is visited exactly once.
Consider pruning techniques like dynamic programming to optimize the solution.
Example: Start at city 0, visit cities 1 and 2 in any order, and return to city 0 for the first test case.
Example: Start at city 0, visi...read more
Q116. Minimum Number of Platforms Problem
Your task is to determine the minimum number of platforms required at a railway station so that no train has to wait.
Explanation:
Given two arrays:
AT
- representing the ar...read more
Determine the minimum number of platforms needed at a railway station so that no train has to wait.
Sort the arrival and departure times arrays in ascending order.
Use two pointers to iterate through the arrays and keep track of the number of platforms needed.
Increment the number of platforms needed when a train arrives and decrement when a train departs.
Return the maximum number of platforms needed at any point.
Q117. Suppose you have an array of elements which has duplicates except 1 number, ex. 1,2,3,4,3,2,1. You need write a pseudo code to find the unique number
Pseudo code to find the unique number in an array with duplicates.
Create an empty dictionary
Loop through the array and add each element as a key in the dictionary with value 1
If the key already exists, increment its value by 1
Loop through the dictionary and return the key with value 1
Q118. Running Median Problem
Given a stream of integers, calculate and print the median after each new integer is added to the stream.
Output only the integer part of the median.
Example:
Input:
N = 5
Stream = [2, 3,...read more
Calculate and print the median after each new integer is added to the stream.
Use two heaps - a max heap to store the smaller half of the numbers and a min heap to store the larger half.
Keep the sizes of the two heaps balanced to efficiently calculate the median.
If the total number of elements is odd, the median will be the top element of the max heap.
If the total number of elements is even, the median will be the average of the top elements of the max and min heaps.
Q119. Given a 2 dim array, find an element which is the maximum in its column and minimum in its row. You are assured that atleast one such element exists. You may return any one if multiple such elements exist. Writ...
read moreFind element in 2D array which is max in column and min in row with minimum comparisons
Iterate over rows and columns to find max and min elements respectively
Compare the max element of a column with the min element of its row
Return the element if it satisfies the condition
Consider edge cases like multiple elements satisfying the condition
Q120. LCA of Binary Tree Problem Statement
You are given a binary tree of distinct integers, along with two nodes, ‘X’ and ‘Y’. Your task is to determine the Lowest Common Ancestor (LCA) of ‘X’ and ‘Y’.
The LCA of tw...read more
Find the Lowest Common Ancestor of two nodes in a binary tree.
Traverse the binary tree to find the paths from the root to nodes X and Y.
Compare the paths to find the last common node, which is the LCA.
Handle cases where one node is an ancestor of the other.
Consider using recursion to solve the problem efficiently.
Q121. Possible Words From A Phone Number
After years of research, Ninja has invented a time machine and found himself in the era where T9 keypads were commonly used in mobile phones. Being curious, Ninja seeks to det...read more
Given a string of digits from 2 to 9, determine all possible strings that can be generated using T9 keypad letter mappings.
Create a mapping of digits to corresponding letters on a T9 keypad
Use recursion to generate all possible combinations of letters for the input string
Sort the generated strings lexicographically
Return the array of generated strings
Q122. Maximum Subarray Sum Problem Statement
Given an array arr
of length N
consisting of integers, find the sum of the subarray (including empty subarray) with the maximum sum among all subarrays.
Explanation:
A sub...read more
Find the sum of the subarray with the maximum sum among all subarrays in an array of integers.
Iterate through the array and keep track of the maximum sum subarray seen so far.
Use Kadane's algorithm to efficiently find the maximum subarray sum.
Consider the case where all elements in the array are negative.
Handle the case where the array contains only one element.
Q123. Total Area of Overlapping Rectangles Problem Statement
Determine the total area covered by two given rectangles on a 2-D coordinate plane, which may have an overlapping area.
Input:
The first line contains an i...read more
Calculate the total area covered by two overlapping rectangles on a 2-D coordinate plane.
Parse input coordinates for two rectangles
Calculate the area of each rectangle
Find the overlapping area by determining the intersection of the rectangles
Calculate the total area by adding the areas of both rectangles and subtracting the overlapping area
Q124. Find the Largest Common Ancestor Problem
Given a binary search tree and two distinct nodes within it, the task is to determine their largest common ancestor. This ancestor is defined as the common ancestor with...read more
Find the largest common ancestor of two nodes in a binary search tree.
Implement a function to find the largest common ancestor of two nodes in a binary search tree.
Use level order traversal input to construct the tree.
Ensure both nodes are present in the tree.
Return the value of the largest common ancestor.
Q125. 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 the value at the last index of the array.
Q126. Validate BST Problem Statement
Given a binary tree with N
nodes, determine whether the tree is a Binary Search Tree (BST). If it is a BST, return true
; otherwise, return false
.
A binary search tree (BST) is a b...read more
Validate if a 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.
Ensure that both the left and right subtrees are also binary search trees.
Q127. Ninja's Dance Competition Pairing Problem
Ninja is organizing a dance competition and wants to pair participants using a unique method. Each participant chooses a number upon entry, and Ninja selects a number ‘...read more
Find the number of distinct pairs of participants with a given difference in their chosen numbers.
Iterate through the list of numbers and check for pairs with the required difference 'K'.
Use a hash set to keep track of unique pairs to avoid counting duplicates.
Return the size of the hash set as the number of distinct pairs.
Q128. Spiral Matrix Problem Statement
You are given a N x M
matrix of integers. Your task is to return the spiral path of the matrix elements.
Input
The first line contains an integer 'T' which denotes the number of ...read more
The task is to return the spiral path of elements in a given matrix.
Iterate through the matrix in a spiral path by keeping track of boundaries.
Print elements in the order of top, right, bottom, and left sides of the matrix.
Handle cases where the matrix is not a square (N != M) separately.
Consider edge cases like single row, single column, and empty matrix.
Q129. Swap Numbers Without Temporary Variable
Your task is to interchange the values of two numbers given as variables 'X' and 'Y' without using a temporary variable or any additional variable.
Explanation:
You need ...read more
Swap two numbers without using a temporary variable.
Use bitwise XOR operation to swap the values of X and Y without using a temporary variable.
The XOR operation works by flipping the bits of the numbers.
After swapping, X = X XOR Y and Y = X XOR Y.
Finally, X = X XOR Y to get the original value of Y in X.
Q130. Minimum Steps for a Knight to Reach Target
Given a square chessboard of size 'N x N', determine the minimum number of moves a Knight requires to reach a specified target position from its initial position.
Expl...read more
Calculate minimum steps for a Knight to reach target position on a chessboard.
Use BFS algorithm to find shortest path from Knight's starting position to target position.
Consider all possible moves of the Knight on the chessboard.
Track visited positions to avoid revisiting them during traversal.
Q131. 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
Q132. 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 given string.
Use a sliding window approach to find the smallest window in S that contains all characters in X.
Maintain a frequency map for characters in X and a window map for characters in the current window.
Slide the window to the right, updating the window map and shrinking the window from the left if all characters in X are present.
Keep track of the smallest window found so far.
Return ...read more
Q133. Infix to Postfix Conversion
Convert a given infix expression, represented as a string EXP
, into its equivalent postfix expression.
Explanation:
An infix expression is formatted as a op b
where the operator is p...read more
Convert infix expression to postfix expression.
Use a stack to keep track of operators and operands.
Follow the rules of precedence for operators.
Handle parentheses to ensure correct order of operations.
Q134. Most Frequent Word Problem Statement
You are given two strings 'A' and 'B' composed of words separated by spaces. Your task is to determine the most frequent and lexicographically smallest word in string 'A' th...read more
Find the most frequent and lexicographically smallest word in string 'A' that is not present in string 'B'.
Split strings 'A' and 'B' into words
Count frequency of each word in 'A'
Check if word is not in 'B' and is the most frequent and lexicographically smallest
Return the word or -1 if no such word exists
Q135. “Compress a text string in place”. Having seen the famous string expansion in place problem many times, I promptly said run length encoding (i.e. compress aaaaaabbbbbccc to a6b5c3 for example). He asked me to c...
read moreCode a run length encoding algorithm to compress a text string in place.
Use a loop to iterate through the string and count consecutive characters
Create a new string to store the compressed version of the original string
Add the character and its count to the new string
Compare the length of the new string to the original string to determine if compression was successful
Q136. There is a roller which can have two types of wood blocks, 49 cm and 50 cm. Given two sensors 50 cm apart which call a function ring( ) whenever the sensor changes state, write the function ring( ) to calculate...
read moreThe function ring() calculates the number of blocks of both types based on sensor state changes.
Create a variable to keep track of the number of 49 cm blocks
Create another variable to keep track of the number of 50 cm blocks
Initialize both variables to 0
Whenever the sensor changes state, increment the corresponding block variable
Return the count of both block types as an array of strings
Q137. Given an integer array, find all (a,b,c) such that a^2 + b^2 = c^2 Solution is O(n^2) Write code and testcases
Given an integer array, find all (a,b,c) such that a^2 + b^2 = c^2. Solution is O(n^2). Write code and testcases.
Use nested loops to iterate through all possible pairs of integers in the array
Check if the sum of squares of the two integers is a perfect square
If yes, add the triplet to the result list
Return the result list
Q138. Snake and Ladder Problem Statement
Given a Snake and Ladder Board with 'N' rows and 'N' columns filled with numbers from 1 to N*N starting from the bottom left of the board, and alternating direction each row, ...read more
Find the minimum number of dice throws required to reach the last cell on a Snake and Ladder board.
Use Breadth First Search (BFS) to explore all possible paths with minimum dice throws.
Keep track of visited cells and the number of dice throws needed to reach each cell.
Consider the effect of snakes and ladders on the next position.
Return the minimum number of dice throws needed to reach the last cell.
If it is impossible to reach the last cell, return -1.
Q139. Given a M x N 2D array containing random alphabets and a function Dict(string word) which returns whether the 'word' is a valid English word. Find all possible valid words you can get from the 2D array, where t...
read moreGiven a 2D array of alphabets and a function to check valid English words, find all possible valid words adjacent to each other.
Create a recursive function to traverse the 2D array and check for valid words
Use memoization to avoid redundant checks
Consider edge cases such as words with repeating letters
Optimize the algorithm for time and space complexity
Q140. There are 4 people who want to cross a bridge. Minimum time they take to cross a bridge is 1, 2, 7 and 11 respectively. There is only 1 torch and at most 2 people can cross a bridge at a time. But no one can cr...
read moreQ141. 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 maintain the order of keys based on their recent usage.
Use a hashmap to store key-value pairs for quick access and update.
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 updated.
Handle get and put operations effic...read more
Q142. Reverse Stack with Recursion
Reverse a given stack of integers using recursion. You must accomplish this without utilizing extra space beyond the internal stack space used by recursion. Additionally, you must r...read more
Reverse a given stack of integers using recursion without using extra space or loops.
Use recursion to pop all elements from the original stack and store them in function call stack.
Once the stack is empty, push the elements back in reverse order using recursion.
Make use of the top(), pop(), and push() stack methods provided.
Example: If the input stack is [1, 2, 3], after reversal it should be [3, 2, 1].
Q143. Cycle Detection in a Singly Linked List
Determine if a given singly linked list of integers forms a cycle or not.
A cycle in a linked list occurs when a node's next
points back to a previous node in the list. T...read more
Detect if a singly linked list forms a cycle by checking if a node's next pointer points back to a previous node.
Use Floyd's Cycle Detection Algorithm to determine if there is a cycle in the linked list.
Maintain two pointers, one moving at twice the speed of the other.
If the two pointers meet at any point, there is a cycle in the linked list.
Q144. Boundary Traversal of a Binary Tree
Given a binary tree of integers, your task is to return the boundary nodes of the tree in Anti-Clockwise direction starting from the root node.
Input:
The first line contains...read more
Return the boundary nodes of a binary tree in Anti-Clockwise direction starting from the root node.
Traverse the left boundary nodes in a top-down manner
Traverse the leaf nodes in a left-right manner
Traverse the right boundary nodes in a bottom-up manner
Avoid duplicates in boundary nodes
Q145. Minimum Subarray with Required Sum Problem Statement
Given an array of positive integers ARR
and an integer X
, determine the minimum length subarray where the sum of its elements is strictly greater than X
.
Not...read more
Find the minimum length subarray with sum greater than X in a given array.
Iterate through the array while maintaining a sliding window to find the subarray with sum greater than X.
Keep track of the minimum length subarray found so far.
Return the subarray with the minimum length and sum greater than X.
Q146. Palindrome Partitioning Problem Statement
Given a string S
, the task is to partition S
so that every substring in the partition is a palindrome. Return all possible palindrome partitions of S
.
Example:
Input:
S...read more
Given a string, partition it into palindromic substrings and return all possible partitions.
Use backtracking to generate all possible partitions by checking if each substring is a palindrome.
Keep track of the current partition and add it to the result when the entire string is processed.
Optimize by using memoization to store the results of subproblems to avoid redundant calculations.
Q147. Flatten the Multi-Level Linked List
You are provided with a multi-level linked list containing N
nodes. Each node has pointers next and child, which could potentially point to additional nodes. The task is to f...read more
Flatten a multi-level linked list into a single-level linked list and return the head of the singly linked list.
Traverse the multi-level linked list using depth-first search (DFS).
Maintain a stack to keep track of nodes with child pointers.
Connect the child nodes to the current node's next pointer and update the current node.
Continue this process until all nodes are flattened into a single-level linked list.
Q148. Problem: Sort an Array of 0s, 1s, and 2s
Given an array/list ARR
consisting of integers where each element is either 0, 1, or 2, your task is to sort this array in increasing order.
Input:
The input starts with...read more
Sort an array of 0s, 1s, and 2s in increasing order.
Use a three-pointer approach to partition the array into sections for 0s, 1s, and 2s.
Iterate through the array and swap elements based on their values and the pointers.
After sorting, the array will have 0s at the beginning, followed by 1s, and then 2s.
Q149. Sort 0 1 2 Problem Statement
Given an integer array arr
of size 'N' containing only 0s, 1s, and 2s, write an algorithm to sort the array.
Input:
The first line contains an integer 'T' representing the number of...read more
Sort an array of 0s, 1s, and 2s in linear time complexity.
Use three pointers to keep track of the positions of 0s, 1s, and 2s in the array.
Iterate through the array and swap elements based on the values encountered.
This approach sorts the array in a single scan without using any extra space.
Q150. Angle Calculation Between Clock Hands
Given a specific time in hours and minutes, your task is to calculate the smallest possible angle between the hour hand and the minute hand of a clock.
Example:
Input:
T = ...read more
Calculate the smallest angle between the hour and minute hands of a clock given a specific time.
Calculate the angle formed by the hour hand with respect to 12 o'clock position
Calculate the angle formed by the minute hand with respect to 12 o'clock position
Find the absolute difference between the two angles and take the minimum of the two possible angles
Return the floor value of the calculated angle
Q151. Minimum Operation Needed to Convert to the Given String
You are given two strings str1
and str2
. Determine the minimum number of operations required to transform str1
into str2
.
Explanation:
An operation is def...read more
Determine the minimum number of operations needed to transform one string into another by moving characters to the end.
Iterate through each character in str1 and check if it matches the first character in str2.
If a match is found, calculate the number of operations needed to move the characters to the end.
Return the minimum number of operations needed for each test case, or -1 if transformation is not possible.
Q152. Diagonal Traversal of a Binary Tree
You are provided with a binary tree composed of integers. Your task is to determine all the diagonal paths within the binary tree. A diagonal path is defined as a sequence of...read more
Implement a function to find diagonal paths in a binary tree.
Traverse the binary tree in a diagonal manner, starting from the rightmost path and moving downwards.
Use a hashmap to store nodes at each diagonal level and then traverse the hashmap to get the diagonal paths.
Handle the case where nodes without left or right children are present by using -1.
Return the diagonal traversal as a single line with nodes arranged by their diagonal paths.
Q153. Total Number of BSTs Using Array Elements as Root Node
You are given a sequence array 'ARR' of 'N' integers. For each ARR[i] where 0 <= 'i' < 'N', your task is to find the number of Binary Search Trees (BST) po...read more
Find the number of BSTs possible with each element of an array as the root node.
Iterate through each element of the array and calculate the number of BSTs possible with that element as the root node.
Use dynamic programming to calculate the number of BSTs for each element efficiently.
Output the results modulo (10^9 + 7) to handle large numbers.
Q154. Binary Search Tree Insertion
Given the root node of a binary search tree and a positive integer, you need to insert a new node with the given value into the BST so that the resulting tree maintains the properti...read more
Insert a new node with a given value into a binary search tree while maintaining the properties of a BST.
Traverse the BST starting from the root node to find the correct position for insertion.
Compare the value to be inserted with the current node's value to determine whether to go left or right.
Create a new node with the given value and insert it at the appropriate position in the BST.
Ensure that the resulting tree maintains the binary search tree properties after insertion.
Q155. Division to N Decimal Places
Your task is to compute the division of two integers, X / Y, and output the result formatted to contain exactly N decimal places.
Input:
The first line contains an integer ‘T’, repr...read more
Compute the division of two integers and output the result formatted to contain exactly N decimal places.
Read the input values for X, Y, and N
Perform the division X / Y
Format the result to contain exactly N decimal places
Output the result as a string with N decimal places
Q156. 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.
Iterate through both strings simultaneously, handling wildcard characters '?' and '*' accordingly.
Use dynamic programming to keep track of matching characters.
Handle cases where '*' can match an empty sequence or multiple characters.
Return true if at the end both strings match, false otherwise.
Q157. Possible Words from a Phone Number: Problem Statement
Given a string S
composed of digits ranging from 2 to 9, determine all possible strings that can be created by mapping these digits to their corresponding l...read more
Given a phone number string, generate all possible words by mapping digits to letters on a T9 keypad.
Create a mapping of digits to corresponding letters on a T9 keypad
Use recursion to generate all possible combinations of letters for the input phone number
Sort the generated strings in lexicographical order
Q158. Robot Movement on Grid Problem
Given a matrix consisting of "."
and "X"
, and an array of moves represented as L, R, U, D
indicating left, right, up, and down respectively, determine the final coordinates of a r...read more
Q159. Clone Linked List with Random Pointer
Your task is to create a deep copy of a linked list, where each node has two pointers: one that points to the next node in the list, and a 'random' pointer which can point ...read more
Create a deep copy of a linked list with random pointers.
Iterate through the original linked list and create a new node for each node in the list.
Store the mapping of original nodes to their corresponding new nodes.
Update the next and random pointers of the new nodes based on the mapping.
Return the head of the newly created deep copied linked list.
Q160. Connect Nodes at Same Level Problem Statement
Given a binary tree, connect all adjacent nodes at the same level by populating each node's 'next' pointer to point to its next right node. If there is no next righ...read more
Connect adjacent nodes at the same level in a binary tree by populating each node's 'next' pointer.
Traverse the tree level by level using a queue.
For each node, connect it to the next node in the queue.
Set the 'next' pointer of the last node in each level to NULL.
Use constant extra space and do not alter the node structure.
Q161. Reverse a Linked List Problem Statement
Given a singly linked list of integers, your task is to return the head of the reversed linked list.
Example:
Input:
The given linked list is 1 -> 2 -> 3 -> 4-> NULL.
Out...read more
Reverse a singly linked list of integers and return the head of the reversed linked list.
Iterate through the linked list and reverse the pointers to point to the previous node instead of the next node.
Keep track of the previous, current, and next nodes while reversing the linked list.
Update the head of the reversed linked list to be the last node encountered.
Ensure to handle edge cases like an empty linked list or a linked list with only one node.
Q162. Valid Parentheses Problem Statement
Given a string 'STR' consisting solely of the characters “{”, “}”, “(”, “)”, “[” and “]”, determine if the parentheses are balanced.
Input:
The first line contains an integer...read more
The task is to determine if a given string consisting of parentheses is balanced or not.
Use a stack data structure to keep track of opening parentheses.
Iterate through the string and push opening parentheses onto the stack.
When encountering a closing parenthesis, pop the top element from the stack and check if it matches the corresponding opening parenthesis.
If the stack is empty at the end of the iteration and all parentheses have been matched, the string is balanced.
If the ...read more
Q163. Given a binary search tree , print the path which has the sum equal to k and has minimum hops. i.e if there are multiple paths with the sum equal to k then print the path with minimum number of nodes
Given a binary search tree, print the path with sum k and minimum hops.
Traverse the tree using DFS and keep track of the current path and its sum.
If the current sum equals k, compare the current path with the minimum path found so far.
If the current sum is greater than k, backtrack to the previous node and continue traversal.
If the current sum is less than k, continue traversal.
Return the minimum path found.
Time complexity: O(nlogn) for balanced tree, O(n^2) for skewed tree.
Q164. Data compression: Given a string “aabbbccc”, save it as “a2b3c3”. Here, I was asked to write a pseudocode, followed by a code in C++, optimize it and then all the testcases. Eg. “aabcc” would become “a2bc2” and...
read moreCompress a string by replacing consecutive characters with their count.
Iterate through the string and count consecutive characters.
Append the character and its count to a new string.
Handle edge cases like single characters.
Q165. Next Greater Element Problem Statement
Given a list of integers of size N
, your task is to determine the Next Greater Element (NGE) for every element. The Next Greater Element for an element X
is the first elem...read more
Find the Next Greater Element for each element in a list of integers.
Iterate through the list of integers from right to left.
Use a stack to keep track of elements for which the Next Greater Element is not yet found.
Pop elements from the stack until a greater element is found or the stack is empty.
Assign the Next Greater Element as the top element of the stack or -1 if the stack is empty.
Q166. Given a random function rand(n) , how ll u test that it returns exactly the random numbers between 1 to n?
To test the rand(n) function, generate a large number of random outputs and check if they fall within the range of 1 to n.
Generate a large number of random outputs using rand(n)
Check if each output falls within the range of 1 to n
Repeat the process multiple times to ensure consistency
Use statistical tests like chi-squared test to analyze the randomness
Q167. Two numbers are stored in two linked lists, with one digit in each node. Add the numbers and return the resultant sum in a linked list. eg. if LL1= 2 > 3 > 5, LL2= 1>4>5, result should be LL3= 3>8>0...
read moreThe question asks to add two numbers represented as linked lists and return the sum as a linked list.
Traverse both linked lists simultaneously, adding the corresponding digits and carrying over the carry.
Create a new linked list to store the sum digits.
Handle cases where one linked list is longer than the other.
Consider cases where the sum has an additional carry digit at the end.
Q168. Increasing the RAM increases the efficiency of the CPU. The reason > is > a) Virtual memory increases > b) Number of page Page faults decreases > c) Page segmentation decreases > d) Increasing the amount of mem...
read moreIncreasing RAM improves CPU efficiency due to virtual memory and reduced page faults.
Increasing RAM allows for more data to be stored in memory, reducing the need for frequent access to slower storage devices.
Virtual memory allows the operating system to use hard disk space as if it were RAM, increasing the effective amount of memory available to the CPU.
Reducing page faults, which occur when the CPU needs to access data that is not currently in memory, improves CPU efficienc...read more
Design a system similar to Red Bus for handling bookings and onboarding vendors and customers.
Implement a user-friendly interface for customers to search and book tickets
Create a vendor portal for vendors to manage their offerings and availability
Include payment gateway integration for secure transactions
Develop a robust backend system for managing bookings, cancellations, and refunds
Utilize a database to store user information, booking details, and vendor listings
Q170. Given a circular linked list containing sorted elements (int value). The head of the linked list points to a random node (not necessarily to the smallest or largest element). Problem is top write a code which w...
read moreInsert a node at its correct position in a circular linked list containing sorted elements.
Traverse the linked list until the correct position is found
Handle the case where the value to be inserted is smaller than the smallest element or larger than the largest element
Update the pointers of the neighboring nodes to insert the new node
Consider the case where the linked list has only one node
Q171. Remove duplicate characters from a given string keeping only the first occurrences (i.e order should not change). For ex- if the input is ‘bananas’ the output will be ‘bans’. -----/ (second method)
Remove duplicate characters from a string while preserving order.
Create an empty string to hold the result.
Iterate through each character in the input string.
If the character is not already in the result string, add it.
Return the result string.
Q172. 1. Write a routine to output the elements of the inorder traversal of a binary tree one by one in its each call. eg: Assuming the inorder traversal is 1, 2, 3, 4, 5, the routine should return 1 in its first cal...
read moreThe routine should output the elements of the inorder traversal of a binary tree one by one in each call.
Implement an inorder traversal algorithm recursively
Use a global variable or pass a reference to keep track of the current element
Call the routine repeatedly to get the next element in each call
Q173. Given a compact data structure to store strings sequentially, one byte stores length l of the string, next l bytes contain the string characters. Write a code to insert the given string at the ith place, making...
read moreThe code inserts a given string at the specified position in a compact data structure that stores strings sequentially.
To insert the string at the ith place, we need to shift all the strings after the ith position by the length of the new string.
We can use a loop to iterate through the data structure and find the ith position.
After finding the ith position, we can calculate the new length of the data structure and allocate memory accordingly.
We then shift all the strings afte...read more
Q174. You hand over 'n' identical linked lists to n salespersons. After the day's work, these salesperson return the lists. Merge these lists such that all insertions, deletions, updates are taken care of, so that yo...
read moreMerge 'n' identical linked lists from 'n' salespersons to handle insertions, deletions, and updates.
Iterate through each linked list and merge them into a single linked list
Handle insertions, deletions, and updates by traversing the merged list and making necessary changes
Repeat the process for the next day by resetting the merged list
Q175. Design an elevator system, where there are 5 elevators and 50 floors. What would be the design considerations on which elevator should come when a button is pressed on a given floor?
Design considerations for an elevator system with 5 elevators and 50 floors.
Traffic patterns and peak hours should be analyzed to determine the optimal number of elevators to be in operation at any given time.
Elevators should be programmed to prioritize stops based on the direction of travel and the proximity of the requested floor to the elevator's current location.
The system should be designed to minimize wait times and maximize efficiency.
Safety features such as emergency ...read more
Q176. Testing whether every left child's value is less than the right child's value in a binary tree
To test if every left child's value is less than the right child's value in a binary tree.
Traverse the binary tree using any traversal algorithm (e.g., in-order, pre-order, post-order)
Compare the value of each left child with its right child
If any left child's value is greater than or equal to its right child's value, return false
If all left child's values are less than their right child's values, return true
Q177. What would you do if there is an escalation and no solution is present currently
I would follow the escalation process and involve higher-level support and management to find a solution.
Review all available documentation and resources
Collaborate with colleagues and subject matter experts
Communicate regularly with the customer to provide updates and manage expectations
Escalate to higher-level support and management as necessary
Continue to troubleshoot and test potential solutions
Document all steps taken and findings for future reference
Q178. What is the use of printf() and scanf() function?
printf() is used to print formatted output to the screen, while scanf() is used to read formatted input from the user.
printf() is used to display output on the screen in a formatted way.
scanf() is used to read input from the user in a formatted way.
Example: printf("Hello, World!"); will display 'Hello, World!' on the screen.
Example: scanf("%d", &num); will read an integer input from the user and store it in 'num'.
Q179. Given the following prototype: int compact(int * p, int size); write a function that will take a sorted array, possibly with duplicates, and compact the array, returning the new length of the array. That is, if...
read moreQ180. Closest Palindrome Problem Statement
You are given a string 'S' that represents a number. Your task is to find the closest palindromic number to this integer represented by 'S'. The closest number is defined as...read more
Find the closest palindromic number to a given integer represented by a string.
Convert the string to an integer and iterate to find the closest palindromic number.
Check for palindromic numbers by reversing the digits and comparing with the original number.
Handle cases where multiple closest palindromic numbers exist by choosing the smaller one.
Optimal strategy to minimize number of drops to find highest floor an egg can be dropped without breaking.
Start by dropping the first egg from a lower floor and incrementally increase the floor until it breaks.
Once the first egg breaks, use the second egg to perform a binary search between the last successful drop and the floor below the breaking point.
This strategy ensures the minimum number of drops required to find the highest floor.
Q182. On circular queue and finding the last number which is highest and contains same number. Of digits a the given numbber
The question is about finding the last number in a circular queue that has the highest number of digits.
Implement a circular queue data structure
Iterate through the circular queue to find the last number with the highest number of digits
Compare the number of digits of each number in the circular queue
Keep track of the last number with the highest number of digits
Q183. 2 magnesium strips and a matchbox are given. Each burns in 60 minutes, with no relation between length burnt and time. Calculate 45 min
Burning time of magnesium strips and matchbox given, calculate 45 min.
Calculate the total burning time of both magnesium strips and matchbox
Divide the total burning time by 4 to get the burning time of 1/4th of the material
Subtract the burning time of 1/4th of the material from the total burning time to get the remaining burning time
Divide the remaining burning time by 3 to get the burning time of 1/3rd of the remaining material
Add the burning time of 1/4th of the material an...read more
Q184. Given a pointer to the root of a binary tree, find whether the left and right subtrees are mirror images of each other
Given a binary tree, check if left and right subtrees are mirror images of each other.
Traverse the tree and compare left and right subtrees recursively.
Use a stack or queue to traverse the tree iteratively.
Check if the left subtree is a mirror image of the right subtree by comparing their values and structures.
Consider an empty tree as a mirror image of itself.
Q185. How does a spell checker routine (common to both, word and PowerPoint) used? I mean is the code copied 2 times for each of the processes in the main memory, if they are different processes or how is it used if...
read moreSpell checker routine in Word and PowerPoint is shared in memory to avoid duplication.
Spell checker routine is typically shared in memory to avoid duplication of code.
Both Word and PowerPoint can access the same spell checker routine in memory.
If they are different processes, the spell checker routine is loaded into memory once and shared.
If they are threads within the same process, they can directly access the shared spell checker routine.
Q186. Launch Bing for France (Market Entry) a. What factors to look at ? b. What data sources ? What can be used from pre-existing (made me write 20+) and what new is required? c. Which market segment to target ? - M...
read moreFactors, data sources, and market segment for launching Bing in France
Factors to consider: language, culture, competition, user behavior
Data sources: market research, user surveys, competitor analysis
Pre-existing data: user demographics, search trends, market share
New data required: local user preferences, language nuances
Market segment: choose based on target audience, competition, growth potential
ACID properties in DBMS ensure data integrity and consistency.
Atomicity: All transactions are either fully completed or fully aborted. For example, transferring money from one account to another should be completed in its entirety.
Consistency: The database remains in a consistent state before and after the transaction. For example, if a constraint is violated during a transaction, the transaction will be rolled back.
Isolation: Transactions are isolated from each other until t...read more
Q188. Given a matrix, find an element that is max in its row and min in its col. The actual question (after I wrote the function) was whether there can be more than one such element in the matrix,
There can be multiple such elements in the matrix.
Multiple elements can be max in their row and min in their col
The function should return all such elements
The elements can be in different rows and columns
Q189. Given a binary tree, node structure has data, left, right and next ,where next of every node is NULL. Now you must make every next point to the immediate next node on the same level( as in next one on the right...
read moreConnect each node to its immediate right node on the same level in a binary tree.
Use level order traversal to connect nodes on the same level.
Use a queue to keep track of nodes at each level.
Update the 'next' pointer of each node to point to the next node in the queue.
Q190. If you chance to develop a software wich type of software do you want to develop?
I would like to develop a mobile application that helps people track their daily water intake.
The app would allow users to set daily water intake goals and track their progress throughout the day.
It could also provide reminders to drink water and offer tips for staying hydrated.
The app could integrate with wearable devices to automatically track water intake.
Users could also log the type of water they are drinking, such as tap water or bottled water.
The app could provide insi...read more
Q191. If Customer is Already Angry how will you make them calm.
I will listen to their concerns, empathize with them, and offer a solution to their problem.
Acknowledge their frustration and apologize for any inconvenience caused
Listen actively to their concerns and let them vent their frustrations
Empathize with them and show that you understand their perspective
Offer a solution to their problem and assure them that you will do everything possible to resolve the issue
Follow up with them to ensure that the issue has been resolved to their s...read more
Q192. . Design a attendance feature for WhatsApp for SME business who typically take attendance on registers a. asked me write problems of using a register b. Design the feature and lots of follow up questions on tha...
read moreDesign an attendance feature for WhatsApp for SME business
Identify problems with using a register for attendance
Design a feature that allows employees to mark attendance on WhatsApp
Include features like location tracking and time stamping
Ensure data privacy and security
Provide analytics and reporting options for employers
Demonstrate communication between two processes using inter-process communication (IPC) methods.
Use sockets for communication between two processes running on the same or different machines.
Implement message passing using shared memory or message queues.
Utilize pipes for communication between parent and child processes.
Memory management in operating systems involves allocation, deallocation, and optimization of memory usage.
Memory allocation: OS allocates memory to processes based on their requirements.
Memory deallocation: OS frees up memory when it is no longer needed by a process.
Memory optimization: OS optimizes memory usage through techniques like paging, segmentation, and virtual memory.
Examples: Paging in which memory is divided into fixed-size blocks and virtual memory which allows p...read more
Q195. Write a program to store a tree on a file. Also write code to reconstruct the tree from that file. Think of efficient techniques
Program to store and reconstruct a tree from a file with efficient techniques.
Use a recursive approach to traverse the tree and write each node to the file
Include information about the node's parent and children in the file
Use a unique identifier for each node to reconstruct the tree from the file
Use a data structure like a hash table to store the nodes and their identifiers for efficient reconstruction
Q196. Given an operation delfirst() and dellast() which deletes the first element and last element of the array respectively. Given an array. how many such operations is needed to get an array which satisfies the con...
read moreTo satisfy the condition 1, only one operation is needed - either delfirst() or dellast().
To satisfy the condition 1, you can either use delfirst() or dellast() operation once.
For example, if the array is ['a', 'b', 'c', 'd'], you can use delfirst() operation to get ['b', 'c', 'd'] or dellast() operation to get ['a', 'b', 'c'].
Q197. Assume you have an array that contains a number of strings (perhaps char * a[100]). Each string is a word from the dictionary. Your task, described in high-level terms, is to devise a way to determine and displ...
read moreFind and display all anagrams within an array of strings.
Iterate through each string in the array
Sort the characters of each string alphabetically
Use a hash table to group anagrams together
Display the groups of anagrams found
Q198. How will you construct parse tree for ((a+b)*c)/d? what all data structures can you use?
Constructing parse tree for ((a+b)*c)/d using data structures.
Use stack data structure to keep track of operators and operands.
Start with the innermost parentheses and work outwards.
Create a node for each operator and operand and link them together.
The root node will be the final result of the expression.
Example: ((a+b)*c)/d can be represented as / -> * -> + -> a, b, c, d.
Q199. Given n houses in a row and 3 colors , we need to paint all the houses with the condition that no two adjacent houses are in same color, The cost of painting depends on the color and house, we need to write cod...
read moreThe problem is to find the minimum cost to paint n houses with 3 colors, ensuring no adjacent houses have the same color.
Use dynamic programming to solve this problem efficiently
Create a 2D array to store the minimum cost of painting each house with each color
Iterate through the houses and colors, updating the minimum cost based on the previous adjacent house's color
Return the minimum cost from the last row of the 2D array
Q200. Reverse the order of words in a given sentence(an array of characters)
To reverse the order of words in a given sentence, we need to split the sentence into words and then reverse the order of the resulting array.
Split the sentence into words using a delimiter like space or comma
Reverse the resulting array of words
Join the reversed array of words using a delimiter to form the reversed sentence
More about working at Microsoft Corporation




Top HR Questions asked in Microsoft Corporation
Interview Process at Microsoft Corporation

Top Interview Questions from Similar Companies








Reviews
Interviews
Salaries
Users/Month

