
Microsoft Corporation


200+ Microsoft Corporation Interview Questions and Answers for Freshers
Q1. Buses Origin Problem Statement
You have been provided with an array where each element specifies the number of buses that can be boarded at each respective bus stop. Buses will only stop at locations that are m...read more
Given an array representing number of buses at each bus stop, determine how many buses originate from each stop.
Iterate through the array and for each element, increment the count of buses originating from the corresponding bus stop.
Use an array to store the count of buses originating from each stop.
Remember to consider the constraint of 1-based indexing for bus stops.
Q2. Rotational Equivalence of Strings Problem Statement
Given two strings 'P' and 'Q' of equal length, determine if string 'P' can be transformed into string 'Q' by cyclically rotating it to the right any number of...read more
Check if one string can be transformed into another by cyclically rotating it to the right.
Iterate through all possible rotations of string P and check if any of them match string Q.
Use string concatenation to simulate cyclic rotations efficiently.
Compare the rotated strings with string Q to determine if they are equivalent.
Q3. Fruits and Baskets Problem Statement
You are given 'n' fruit trees planted along a road, numbered from 0 to n-1. Each tree bears a fruit type represented by an uppercase English alphabet. A Ninja walking along ...read more
The Ninja must collect fruits from trees in consecutive order, maximizing the number of fruits in two baskets.
Iterate through the trees while keeping track of the types of fruits collected in each basket.
Use a sliding window approach to find the maximum number of fruits collected.
Keep track of the count of each fruit type encountered to handle the condition of only two types of fruits in each basket.
Q4. Data Structure with Insert, Delete, and GetRandom Operations
Design a data structure that supports four operations: insert an element, remove an element, search for an element, and get a random element. Each op...read more
Design a data structure supporting insert, delete, search, and getRandom operations in constant time.
Use a combination of hashmap and array to achieve O(1) time complexity for all operations.
For insert operation, check if element exists in hashmap, if not add to array and hashmap.
For remove operation, check if element exists in hashmap, if yes, remove from array and hashmap.
For search operation, check if element exists in hashmap.
For getRandom operation, generate a random ind...read more
Q5. You have a cuboid (m*n*p) each block of the cuboid is having a metallic ball. Now we are passing X-ray from front face and getting a bool matrix1 of m*p the elements are set if there is a black spot.(as we are...
read moreYes, it is possible to get the accurate result from the given data.
The coordinates (i,j,k) where metallic balls are present can be determined by finding the set elements in both matrix1 and matrix2.
Additional data is not required as the given data is sufficient to determine the coordinates.
The coordinates can be obtained by iterating through the elements of matrix1 and matrix2 and checking for set elements.
Q6. Find All Triplets with Zero Sum
Given an array Arr
consisting of N
integers, find all distinct triplets in the array that sum up to zero.
Explanation:
An array is said to have a triplet {Arr[i], Arr[j], Arr[k]}...read more
Find all distinct triplets in an array that sum up to zero.
Use a nested loop to iterate through all possible combinations of triplets.
Sort the array to easily identify duplicates and skip unnecessary calculations.
Use two-pointer technique to find the remaining element for each pair of elements.
Q7. Distinct Strings With Odd and Even Swapping Allowed Problem Statement
You are provided with an array of strings, and your objective is to determine the number of unique strings within it.
A string is deemed uni...read more
Given an array of strings, determine the number of unique strings that cannot be transformed into another string by swapping characters at odd or even indices.
Iterate through each string in the array and check if it can be transformed into another string by swapping characters at odd or even indices.
Keep track of unique strings that cannot be transformed and return the count.
Example: For array = ["abcd", "cbad", "bdac", "adcb"], the output is 2 as only "bdac" is unique.
Q8. Kth Largest Element Problem
Given an array containing N
distinct positive integers and a number K
, determine the Kth largest element in the array.
Example:
Input:
N = 6, K = 3, array = [2, 1, 5, 6, 3, 8]
Output...read more
Find the Kth largest element in an array of distinct positive integers.
Sort the array in non-increasing order and return the Kth element.
Use a sorting algorithm like quicksort or heapsort for efficiency.
Ensure the array contains distinct positive integers for accurate results.
Q9. Sum Root to Leaf Numbers
You are given an arbitrary binary tree consisting of N nodes, each associated with an integer value from 1 to 9. Each root-to-leaf path can be considered a number formed by concatenatin...read more
Calculate the total sum of all root to leaf paths in an arbitrary binary tree.
Traverse the tree in a depth-first manner to calculate the sum of each root to leaf path.
Keep track of the current path sum and update it as you traverse the tree.
Return the total sum modulo (10^9 + 7) as the final result.
Q10. 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-celebrity candidates.
Start with two pointers at the beginning and end of the party.
If A knows B, A cannot be the celebrity; move A to the right.
If A does not know B, B cannot be the celebrity; move B to the left.
Repeat until only one person remains, check if this person is known by everyone.
Return the ID of the celebrity or -1 if none exists...read more
Q11. Longest Mountain Subarray Problem Statement
Given an array of integers representing the heights of mountains, determine the length of the longest subarray that forms a mountain shape.
A mountain subarray is def...read more
Find the length of the longest mountain subarray in an array of integers.
Iterate through the array to find peaks.
Expand from peaks to find ascending and descending slopes.
Track the length of the mountain subarray and return the maximum length.
Q12. Stock Buying and Selling Problem Statement
Given an array of stock prices where each element represents the stock price for a given day, determine the maximum profit you can achieve from buying and selling the ...read more
Determine maximum profit from buying and selling stocks on different days.
Iterate through the array of stock prices and calculate the profit for each pair of days.
Keep track of the maximum profit obtained by selling and buying stocks on different days.
Return the maximum profit achieved.
Q13. IP Address Formation from String
Given a string S
consisting only of digits from 0 to 9, your task is to find all potential IP addresses that can be formed from S
and list them in lexicographical order. If it's...read more
Given a string of digits, find all potential valid IP addresses that can be formed from it.
Split the string into four parts and check if each part is a valid IP segment (0-255).
Use backtracking to generate all possible combinations of valid IP addresses.
Ensure that the IP address does not contain leading zeroes.
Return the valid IP addresses in lexicographical order.
Q14. Dice Throws Problem Statement
You are given D
dice, each having F
faces numbered from 1 to F
. The task is to determine the number of possible ways to roll all the dice such that the sum of the face-up numbers e...read more
The task is to determine the number of possible ways to roll all the dice such that the sum of the face-up numbers equals the given 'target' sum.
Use dynamic programming to solve the problem efficiently.
Create a 2D array to store the number of ways to achieve each sum with the given number of dice.
Iterate through the dice and faces to calculate the number of ways to reach each sum.
Return the result modulo 10^9 + 7.
Optimize the solution to use no more than O(S) extra space by u...read more
Q15. Group Anagrams Problem Statement
Given an array or list of strings called inputStr
, your task is to return the strings grouped as anagrams. Each group should contain strings that are anagrams of one another.
An...read more
Group anagrams in an array of strings based on character frequency.
Iterate through each string in the input array
For each string, sort the characters and use the sorted string as a key in a hashmap to group anagrams
Return the grouped anagrams as arrays of strings
Q16. Convert BST to Sorted Doubly Linked List
You are given a Binary Search Tree (BST), and your task is to convert it into a sorted Doubly Linked List (DLL).
Example:
Consider the provided BST. The goal is to conve...read more
Convert a Binary Search Tree to a sorted Doubly Linked List efficiently.
Implement a function to convert a BST to a sorted DLL.
Use in-order traversal to efficiently convert the BST to DLL.
Maintain pointers for the head and tail of the DLL.
Ensure the left child of a node becomes the previous node and the right child becomes the next node in the DLL.
Q17. Time to Burn Tree Problem
You are given a binary tree consisting of 'N' unique nodes and a start node where the burning will commence. The task is to calculate the time in minutes required to completely burn th...read more
Calculate the time in minutes required to completely burn a binary tree starting from a given node.
Perform a depth-first search (DFS) to calculate the time taken to burn the entire tree.
Track the time taken for each node to catch fire and burn the tree accordingly.
Consider the adjacency of nodes to determine the spread of fire.
Handle cases where the start node is at different levels in the tree.
Optimize the solution to handle large binary trees efficiently.
Q18. Minimum Cost Path Problem Statement
Given an integer matrix with dimensions m x n
, determine the minimum cost required to reach from the cell (0, 0) to the cell (m-1, n-1).
You are allowed to move from a cell (...read more
The problem involves finding the minimum cost path in a matrix by moving right, down, or diagonally down-right.
Use dynamic programming to keep track of the minimum cost at each cell
Consider the three possible directions for movement and calculate the cost accordingly
Start from the top-left cell and iterate through the matrix to find the minimum cost path
Q19. Merge Sort Problem Statement
You are given a sequence of numbers, ARR
. Your task is to return a sorted sequence of ARR
in non-descending order using the Merge Sort algorithm.
Explanation:
The Merge Sort algorit...read more
Implement Merge Sort algorithm to sort a given sequence of numbers in non-descending order.
Divide the input array into two halves recursively until each array has only one element.
Merge the sorted halves to produce a completely sorted array.
Time complexity of Merge Sort is O(n log n).
Q20. Sum Tree Conversion Problem Statement
Transform a given binary tree into a sum tree where each node is replaced by the sum of its immediate children's values. Leaf nodes should be replaced with 0. Then, perform...read more
Convert a binary tree into a sum tree by replacing each node with the sum of its children's values, and return the preorder traversal.
Traverse the tree recursively and replace each node with the sum of its children's values
Leaf nodes should be replaced with 0
Perform a preorder traversal on the transformed sum tree to get the final result
Q21. Generate Binary Strings from Pattern
Given a string STR
containing '0', '1', and '?' special characters, generate all possible strings by replacing each '?' with either '0' or '1'.
Input:
The first line contain...read more
Generate all possible binary strings by replacing '?' with '0' or '1'.
Iterate through the input string and replace '?' with '0' and '1' recursively to generate all possible strings.
Use backtracking to explore all possible combinations.
Sort the generated strings lexicographically before returning the final result.
Q22. Flatten Binary Tree Problem Statement
Given a binary tree consisting of integer values, your task is to convert the binary tree into a linked list where the nodes of the linked list follow the same order as the...read more
Convert a binary tree into a linked list following pre-order traversal order.
Perform pre-order traversal of the binary tree and convert it into a linked list.
Use the right pointer of the binary tree as the 'next' pointer for the linked list.
Set the left pointer to NULL for each node in the linked list.
Example: Input - 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1, Output - 1 2 4 7 3 5 6
Q23. Buy and Sell Stock Problem Statement
You are tasked to help a friend with stock trading for the next 'N' days. He can either buy or sell a stock, with the condition that he can complete at most 2 transactions. ...read more
Determine maximum profit from at most 2 stock transactions over 'N' days.
Iterate through the prices array to find the maximum profit from 2 transactions.
Keep track of the maximum profit by buying and selling stocks at the right times.
Consider edge cases like when there are no profitable transactions.
Q24. Find the Lone Set Bit
Your task is to identify the position of the only '1' bit in the binary representation of a given non-negative integer N
. The representation contains exactly one '1' and the rest are '0's....read more
Find the position of the lone '1' bit in the binary representation of a given non-negative integer.
Iterate through the bits of the integer to find the position of the lone '1'.
Use bitwise operations to check if there is exactly one '1' bit in the binary representation.
Return the position of the lone '1' or -1 if there isn't exactly one '1'.
Q25. First Missing Positive Problem Statement
You are provided with an integer array ARR
of length 'N'. Your objective is to determine the first missing positive integer using linear time and constant space. This me...read more
Find the smallest positive integer missing from an array of integers.
Iterate through the array and mark positive integers as visited by changing the sign of the corresponding index.
After marking all positive integers, iterate again to find the first positive integer with a positive value.
Return the index of the first positive integer found plus one as the answer.
Q26. Tic-Tac-Toe Design Problem
Design a 2-player Tic-Tac-Toe game played on an N
* N
grid where Player 1 uses ‘X’ and Player 2 uses ‘O’. A move is always valid and occupies an empty spot.
If a player places N
of th...read more
Design a 2-player Tic-Tac-Toe game on an N x N grid where players take turns placing their marks, and the first player to get N marks in a row wins.
Implement a function move(row, col, player) to handle each player's move and check for a win condition.
Keep track of the board state and update it after each move.
Check for winning conditions horizontally, vertically, and diagonally after each move.
Return the result (0 for no win, 1 for Player 1 win, 2 for Player 2 win) after each...read more
Q27. Gray Code Problem Statement
You are given a number grayNumber
. Your task is to find and return the Gray code sequence.
Explanation
The Gray code sequence should satisfy the following conditions:
1. Include numb...read more
Find and return the Gray code sequence for a given number.
Generate Gray code sequence by following the conditions provided in the problem statement.
Ensure that consecutive numbers in the sequence differ by exactly 1 bit.
Start the sequence with 0 and include numbers up to 2^grayNumber - 1.
Return the sequence in decimal form as a list/vector.
If multiple valid sequences exist, return any of them.
Q28. Ninja and the Storyteller Problem
Ninja is eager to listen to stories from the renowned Storyteller of Ninjaland. The storyteller charges 'Y' coins per story. However, for every set of 'X' stories told, Ninja g...read more
Calculate the total number of stories a ninja can hear from a storyteller based on given conditions and constraints.
Calculate the number of stories Ninja can buy with available coins and without free stories.
Calculate the number of free stories Ninja can get based on the number of stories bought.
Add the total number of bought and free stories to get the final result.
Q29. Count Squares in a Matrix
Given a matrix of size N * M, your task is to count the number of squares present within it.
Since the count can be extremely large, the result should be computed modulo 109 + 7.
Examp...read more
Count the number of squares in a given matrix modulo 10^9 + 7.
Iterate through all possible square sizes from 1 to min(N, M)
For each square size, count the number of squares that can fit in the matrix
Return the total count modulo 10^9 + 7
Q30. Nice DP problem. Given an amount and an array containing possible coin denominations, determine the smallest no of coins in which the amount may be formed. Assume you have infinite units of each denomination
Given an amount and coin denominations, find the smallest no of coins to form the amount.
Use dynamic programming to solve the problem
Create a table to store the minimum number of coins required for each amount
Iterate through the denominations and update the table accordingly
Return the minimum number of coins required for the given amount
Q31. Longest Duplicate Substring Problem Statement
You are provided with a string 'S'. The task is to determine the length of the longest duplicate substring within this string. Note that duplicate substrings can ov...read more
Find the length of the longest duplicate substring in a given string.
Use binary search to find the length of the longest duplicate substring.
Implement Rabin-Karp algorithm for efficient substring search.
Consider using a rolling hash function for substring comparisons.
Q32. Count Inversions Problem Statement
Let A[0 ... n-1]
be an array of n
distinct positive integers. An inversion of A
is a pair of indices (i, j)
such that i < j
and A[i] > A[j]
. Given an integer array A, your tas...read more
Count the number of inversions in an array of distinct positive integers.
Use merge sort algorithm to count inversions efficiently.
Divide the array into two halves and recursively count inversions in each half.
Merge the two sorted halves while counting split inversions.
Time complexity can be optimized to O(n log n) using merge sort.
Example: For input A = [2, 4, 1, 3, 5], the output should be 3.
Q33. Kth Smallest Element Problem Statement
You are provided with an array of integers ARR
of size N
and an integer K
. Your task is to find and return the K
-th smallest value present in the array. All elements in th...read more
Find the K-th smallest element in an array of distinct integers.
Sort the array and return the element at index K-1.
Use a min-heap to find the K-th smallest element efficiently.
Implement quickselect algorithm for optimal performance.
Q34. Graph Coloring Problem Statement
You are provided with a graph consisting of N
vertices, numbered from 1 to N
, and M
edges. Your task is to color the graph using two colors, Blue and Red, such that no two adjac...read more
Given a graph with vertices and edges, determine if it can be colored using two colors without adjacent vertices sharing the same color.
Check if the graph is bipartite using graph coloring algorithm like BFS or DFS.
If the graph is bipartite, return 'Possible' with a valid coloring assignment.
If the graph is not bipartite, return 'Impossible'.
Q35. String Compression Problem Statement
Write a program to perform basic string compression. For each character that repeats consecutively more than once, replace the consecutive duplicate occurrences with the cha...read more
Write a program to compress a string by replacing consecutive duplicate characters with the character followed by the number of repetitions.
Iterate through the string and count consecutive occurrences of each character
Append the character and its count to a new string
Return the compressed string if it is shorter than the original, else return the original string
Handle edge cases like single characters or when compressed string is longer than original
Q36. 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
Q37. 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.
Q38. “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
Q39. 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
Q40. 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.
Q41. 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.
Q42. 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
Q43. 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
Q44. Palindrome Linked List Problem Statement
You are provided with a singly linked list of integers. Your task is to determine whether the given singly linked list is a palindrome. Return true
if it is a palindrome...read more
Q45. Mean, Median, Mode Calculation
You are given an array 'ARR' consisting of 'N' integers. Your task is to calculate the three statistical measures for the given array:
- Mean - Implement the function
mean()
to cal...read more
Implement functions to calculate mean, median, and mode of an array of integers.
Implement a function mean() to calculate the mean of the array by summing all elements and dividing by the total count.
Implement a function median() to calculate the median of the array by sorting the array and finding the middle element(s).
Implement a function mode() to find the mode of the array by counting frequencies and returning the smallest element with the highest frequency.
Q46. Find K’th Character of Decrypted String
You are given an encrypted string where repetitions of substrings are expressed as the substring followed by the count of these substrings. The task is to find the 'K'th ...read more
Q47. Dice Throw Problem Statement
You are provided with D
dice, each having F
faces numbered 1 to F
, inclusive. Your task is to determine the number of possible ways to roll the dice such that the sum of the face-up...read more
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
Q49. 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
Q50. Nth Term of Geometric Progression (GP) Series
Determine the Nth term of a geometric progression (GP) series given the first term, common ratio, and the term number.
Explanation:
The general form of a GP series ...read more
Calculate the Nth term of a geometric progression series given the first term, common ratio, and term number.
Use the formula for the Nth term of a GP series: A * (R^(N-1))
Ensure to take the modulo 10^9 + 7 as the output
Handle multiple test cases efficiently within the given time limit
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
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.
Q53. 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
Q54. 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.
Q55. Arithmetic Expression Evaluation Problem Statement
You are provided with a string expression
consisting of characters '+', '-', '*', '/', '(', ')' and digits '0' to '9', representing an arithmetic expression in...read more
Evaluate arithmetic expressions in infix notation with given operators and precedence rules.
Parse the infix expression to postfix using a stack.
Evaluate the postfix expression using a stack.
Handle operators precedence and parentheses while evaluating.
Ensure no division by zero cases and operands fit in 32-bit integer.
Q56. Distinct Subsequences of a String
Given a string S
of length N
that may contain duplicate alphabets, your task is to compute the count of distinct subsequences of this string.
Example:
Input:
S = "deed"
Output:...read more
Compute the count of distinct subsequences of a string with possible duplicates.
Use dynamic programming to keep track of distinct subsequences.
Consider the cases where the current character is included or excluded in the subsequence.
Use a hashmap to store the last occurrence index of each character to handle duplicates efficiently.
Q57. Given a linked list, invert every two nodes in the list.Eg. Given a > b > c > d, result should be b > a > d > c
The given linked list needs to be inverted in pairs of two nodes.
Iterate through the linked list, swapping every two adjacent nodes.
Keep track of the previous node to update the next pointers correctly.
Handle the edge cases of odd number of nodes or empty list.
Q58. Delete Kth Node from End of Linked List
This problem requires you to delete the Kth node from the end of a given singly linked list with N nodes containing integer data.
You are asked to efficiently remove this...read more
To delete the Kth node from the end of a singly linked list efficiently without finding the length of the list and using O(1) extra space.
Use two pointers approach - one pointer moves K steps ahead of the other.
When the first pointer reaches the end, the second pointer will be at the Kth node from the end.
Adjust the pointers to remove the Kth node efficiently.
Ensure to handle edge cases like deleting the head or tail node.
Example: For input 1 -> 2 -> 3 -> 4 -> NULL and K = 2,...read more
Q59. Given a string of unknown length, what is a good approach to find n-k th element from last
To find n-k th element from last in a string of unknown length
Traverse the string to find its length
Calculate the position of n-k th element from last
Traverse the string again to find the element at calculated position
Q60. Nth Element of Modified Fibonacci Series
Given two integers X
and Y
as the first two elements of a series, and another integer N
, find the Nth number of the series utilizing the Fibonacci rule: f(x) = f(x - 1) ...read more
Q61. Given 5 points in a plane, prove that there will be atleast two points such that their midpoint is an integer
Prove that given 5 points in a plane, there will be at least two points such that their midpoint is an integer.
Consider the x and y coordinates of the 5 points.
If any two points have the same x and y coordinates, their midpoint will be an integer.
If not, consider the differences between the x and y coordinates of each pair of points.
If any two pairs have differences that are both even or both odd, their midpoints will be integers.
By the Pigeonhole Principle, there must be at ...read more
Q62. Insert an element into a sorted circular linked list. (Consider all cases, inserting in the beginning, end and middle)
Insert an element into a sorted circular linked list.
Find the correct position to insert the element based on its value
Update the pointers of the previous and next nodes to include the new node
Handle special cases such as inserting at the beginning or end of the list
Example: Inserting 5 into a list with values 1, 3, 4, 6, 7 would result in 1, 3, 4, 5, 6, 7
Q63. Identical Trees Problem Statement
Given two binary trees with 'N' and 'M' nodes respectively, determine if the two trees are identical. Return true
if they are identical, otherwise return false
.
Input:
The firs...read more
Check if two binary trees are identical by comparing their nodes in level order.
Traverse both trees in level order and compare corresponding nodes for equality
Use a queue to keep track of nodes to be compared
Return false if nodes are not equal or if one tree has more nodes than the other
Q64. You have a Binary tree having numbers>=0 and a numeber N. Print all downwards paths from any node having the sum of elements equal to N
Print all downward paths from any node in a binary tree with sum of elements equal to N.
Traverse the binary tree and keep track of the sum of elements in the path from root to current node.
If the sum equals N, print the path from root to current node.
Recursively traverse the left and right subtrees with updated sum.
Use a stack to keep track of the current path being traversed.
Example: Binary tree with root 1, left child 2, right child 3, and N=3. Output: [1,2], [1,3].
Q65. Given a node in a binary tree, find the leftmost node in the same level. I wrote the pseudocode, and testcases
Find the leftmost node in the same level as a given node in a binary tree.
Traverse the tree level by level using BFS
For each level, keep track of the leftmost node encountered
Return the leftmost node at the same level as the given node
Q66. Euler Totient Function Calculation
Determine the count of numbers between 1 and a given integer 'N' (inclusive) that are coprime to 'N'.
Input:
T
, number of test casesN
, the integer for each test case
Output:
T...read more
Q67. Rotate Matrix by 90 Degrees Problem Statement
Given a square matrix 'MATRIX' of non-negative integers, rotate the matrix by 90 degrees in an anti-clockwise direction using only constant extra space.
Input:
The ...read more
Rotate a square matrix by 90 degrees in an anti-clockwise direction using constant extra space.
Iterate through each layer of the matrix from outer to inner layers
Swap elements in groups of 4 to rotate the matrix
Handle odd-sized matrices separately by adjusting the loop boundaries
Q68. Given a string of containing lower case letters and upper case characters. Find the number of occurrences of each character. The question was further modified to include the special characters as well. I was as...
read moreCount the occurrences of each character in a given string including special characters.
Create test cases for empty string
Test for string with only one character
Test for string with all characters being the same
Test for string with all characters being different
Test for string with special characters
Q69. Sort Stack Problem Statement
You are given a stack S
. Your task is to sort the stack recursively in descending order.
Constraints:
- Looping through the stack is not allowed.
- Return the stack sorted in descendin...read more
Sort a given stack in descending order recursively without using loops.
Use recursion to pop elements from the stack and insert them in the correct position.
Maintain a temporary stack to hold elements while sorting.
Compare the top element of the stack with the top element of the temporary stack to insert in descending order.
Q70. Longest Common Prefix After Rotation
You are given two strings 'A' and 'B'. While string 'A' is constant, you may apply any number of left shift operations to string 'B'.
Explanation:
Your task is to calculate ...read more
Calculate minimum left shift operations to achieve longest common prefix between two strings.
Apply left shift operations to string B to find longest common prefix with string A
Count number of shifts needed to achieve longest common prefix
Handle circular rotation of characters in string B
Return minimum number of left shift operations for each test case
Q71. Connect Nodes at the Same Level
Given a binary tree where each node has at most two children, your task is to connect all adjacent nodes at the same level. You should populate each node's 'next' pointer to its ...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 level, connect nodes from left to right using their 'next' pointers.
Set the 'next' pointer of the rightmost node in each level to NULL.
Example: For the given binary tree, connect nodes 2->3, 4->5, 5->6, and set 1, 3, 6 'next' pointers to NULL.
Q72. Longest Palindromic Subsequence Problem Statement
Given a string A
consisting of lowercase English letters, determine the length of the longest palindromic subsequence within A
.
Explanation:
- A subsequence is d...read more
The problem involves finding the length of the longest palindromic subsequence in a given string of lowercase English letters.
Iterate through the string and create a 2D array to store the lengths of palindromic subsequences for each substring.
Use dynamic programming to fill the array based on the characters in the string.
Consider the base cases where the length of the substring is 1 or 2.
Update the array based on whether the characters at the start and end of the substring ma...read more
Count total palindromic substrings in a given string.
Iterate through each character in the string and consider it as the center of a palindrome. Expand outwards to find all palindromic substrings.
Use dynamic programming to efficiently check if a substring is a palindrome.
Consider both odd-length and even-length palindromes.
Example: Input 'ababa', output 7 (a, b, a, b, a, aba, aba)
Q74. Problem Statement: Sibling Nodes
You are provided with a Binary Tree consisting of 'N' nodes, where each node holds an integer value. Your objective is to identify and list all nodes that do not possess a sibli...read more
Identify and list nodes in a Binary Tree that do not have a sibling.
Traverse the Binary Tree in level order and keep track of nodes without siblings.
Check if each node has a sibling by comparing with its parent's other child.
Output the values of nodes without siblings in ascending order.
Handle cases where the root node is considered a sibling node.
Q75. 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.
Q76. Write the backend server code for a tic tac toe game
Backend server code for a tic tac toe game
Create a RESTful API using a framework like Express.js
Implement game logic to check for winning conditions
Use a database to store game state and user information
Handle user authentication and authorization
Implement real-time updates using WebSockets
Q77. 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'.
Q78. 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
Q79. 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.
Q80. 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.
Q81. 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
Q82. 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
Q83. 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.
Q84. 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.
Q85. 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.
Q86. Find the nth power of a number in shortest computational time
Use exponentiation by squaring algorithm to find nth power of a number in shortest computational time.
Use recursion to divide the power by 2 and multiply the base accordingly
If power is odd, multiply the base with the result of recursive call
If power is negative, take reciprocal of base and make power positive
Handle edge cases like power=0 and base=0 or 1
Time complexity is O(log n)
Q87. Check the no of repeated occurences of a substring in a string
Count the number of times a substring appears in a string.
Use a loop to iterate through the string and check for the substring at each index.
Use the count() method to count the number of occurrences of the substring.
Consider using regular expressions to find all occurrences of the substring.
Handle edge cases such as empty strings or substrings.
Q88. Given a binary search tree and a no. N in the tree, print the leftmost node at the same level as N
Print the leftmost node at the same level as a given node in a binary search tree.
Traverse the tree level by level using BFS
Keep track of the leftmost node at each level
Return the leftmost node at the level of the given node
If the given node is not found, return null
Q89. Search for an element in a rotated sorted array (of course in sublinear time!)
Search for an element in a rotated sorted array in sublinear time.
Use binary search to find the pivot point where the array is rotated.
Determine which half of the array the target element is in.
Perform binary search on the appropriate half of the array to find the target element.
Time complexity is O(log n).
Q90. 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.
Q91. 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.
Q92. 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.
Q93. 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.
Q94. 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.
Q95. 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.
Q96. 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.
Q97. 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.
Q98. 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
Q99. 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
Q100. 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
More about working at Microsoft Corporation




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

Top Interview Questions from Similar Companies





