
Microsoft Corporation


700+ Microsoft Corporation Interview Questions and Answers
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. Chess Tournament Problem Statement
In Ninjaland, a chess tournament is being organized with C
chess players attending. They will all stay in a hotel that has N
available rooms. Each player will choose one room,...read more
Assign rooms to chess players to maximize overall focus level by minimizing distance between rooms.
Sort the positions of rooms in ascending order.
Calculate the distances between adjacent rooms.
Select rooms with minimum distances to maximize overall focus level.
Q3. Day of the Week Calculation
Your task is to create a function that determines the day of the week for any given date, whether in the past or the future.
Input:
The first line consists of an integer 'T', represe...read more
Create a function to determine the day of the week for any given date.
Parse the input integers to create a date object
Use a library or algorithm to calculate the day of the week for the given date
Return the corresponding day of the week as a string
Q4. You are given infinite sequence of continuos natural numbers-1,2,3,4,5,6.......... Initially you delete every 2nd element so sequence will be 1,3,,5,7,9,11,13..... now in the resultant sequence you delete every...
read moreProgram to check if a given number is a lucky number or not.
Create a function that takes an integer n as input
Initialize a variable count to 2
Loop through the sequence and delete every count-th element
Repeat the above step until the end of the sequence
If n is present in the final sequence, return true, else return false
Q5. 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.
Q6. 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.
Q7. 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
Q8. 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.
Q9. 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.
Q10. 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.
Q11. 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.
Q12. 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
Q13. Word Wrap Problem Statement
You are tasked with arranging 'N' words of varying lengths such that each line contains at most 'M' characters, with each word separated by a space. The challenge is to minimize the ...read more
The goal is to minimize the total cost of arranging 'N' words on each line with a maximum character limit 'M'.
Calculate the cost of each line as the cube of extra space characters needed to reach 'M'.
Minimize the total cost by arranging words to fit within the character limit on each line.
Ensure each word appears fully on one line without breaking across lines.
Q14. 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
Q15. 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
Q16. 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.
Q17. 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
Q18. 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.
Q19. Matrix Rank Calculation
Given a matrix ARR
of dimensions N * M
, your task is to determine the rank of the matrix ARR
.
Explanation:
The rank of a matrix is defined as:
(a) The maximum number of linearly independ...read more
Calculate the rank of a matrix based on linearly independent column or row vectors.
Determine the number of linearly independent column vectors or row vectors in the matrix.
Use Gaussian elimination or row reduction to simplify the matrix and find the rank.
The rank of a matrix is the maximum number of linearly independent vectors it contains.
Q20. 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.
Q21. 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.
Q22. Look-And-Say Sequence Problem Statement
The Look-And-Say sequence is a series of positive integers generated in a specific pattern:
1, 11, 21, 1211, 111221, 312211, 13112221,...
To construct this sequence:
- The...read more
The Look-And-Say sequence is a series of positive integers generated in a specific pattern based on the count of digits in the previous number.
Implement a function to generate the Nth term of the Look-And-Say sequence efficiently.
Use a loop to iterate through the sequence generation process.
Keep track of the count of consecutive digits in each number to generate the next number.
Handle the constraints of the number of test cases and the Nth term efficiently.
Example: For N=4, t...read more
Q23. 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.
Q24. N Queens Problem
Given an integer N
, find all possible placements of N
queens on an N x N
chessboard such that no two queens threaten each other.
Explanation:
A queen can attack another queen if they are in the...read more
The N Queens Problem involves finding all possible placements of N queens on an N x N chessboard without threatening each other.
Use backtracking algorithm to explore all possible configurations.
Keep track of rows, columns, and diagonals to ensure queens do not threaten each other.
Generate all valid configurations and print them as output.
Q25. Maximum Stock Profit with Two Transactions
You are provided with the prices of a particular stock over the next ‘N’ days. You can perform at most two transactions to maximize your profit. A transaction consists...read more
Q26. Alternating Largest Problem Statement
Given a list of numbers, rearrange them such that every second element is greater than its adjacent elements. Implement a function to achieve this rearrangement.
Input:
The...read more
Rearrange a list of numbers such that every second element is greater than its adjacent elements.
Iterate through the array and swap elements if needed to satisfy the condition
Keep track of the current and next elements to compare and swap
Ensure that the swapped elements maintain the desired order
Q27. 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
Q28. Nearest Multiple of 10 Problem Statement
Given an integer N
, find the nearest multiple of 10. If there are multiple nearest multiples, return the smallest one.
Input:
The first line contains an integer 'T', den...read more
Given an integer, find the nearest multiple of 10. If multiple nearest multiples, return the smallest one.
Iterate through each test case
Calculate the remainder when dividing N by 10
If remainder is less than or equal to 5, nearest multiple is N - remainder
If remainder is greater than 5, nearest multiple is N + (10 - remainder)
Q29. 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
Q30. 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
Q31. Detect the First Node of the Loop in a Singly Linked List
You are provided with a singly linked list that may contain a cycle. Your task is to return the node where the cycle begins, if such a cycle exists.
A c...read more
To detect the first node of the loop in a singly linked list, we can use Floyd's Cycle Detection Algorithm.
Use Floyd's Cycle Detection Algorithm to find the meeting point of the slow and fast pointers in the linked list.
Reset one of the pointers to the head of the linked list and move both pointers at the same speed until they meet at the start of the cycle.
The node where the pointers meet is the first node of the loop in the linked list.
Q32. Total Strings Problem Description
Given a positive integer N
, your task is to determine the number of strings of length N
that can be created using only the characters 'a', 'b', and 'c'. The strings must adhere...read more
The problem involves determining the number of strings of length N that can be created using only the characters 'a', 'b', and 'c', with constraints on the number of 'b' and 'c' allowed.
Use dynamic programming to count the number of valid strings for each length N.
Consider the constraints on the number of 'b' and 'c' allowed in each string.
Implement a function to calculate the result modulo 1000000007.
For N = 2, valid strings are: 'aa', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'cc...read more
Q33. Distinct Islands Problem Statement
Given a two-dimensional array/list consisting of integers 0s and 1s, where 1 represents land and 0 represents water, determine the number of distinct islands. A group of conne...read more
Count the number of distinct islands in a 2D array of 0s and 1s.
Identify islands by performing depth-first search (DFS) on the grid
Use a set to store the shape of each island and check for duplicates
Consider translations to determine distinct islands
Q34. 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
Q35. 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.
Q36. 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
Q37. 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.
Q38. Ninja and the Tree: Correcting a Mistaken Binary Search Tree
Ninja is exploring the data structure of trees and while learning about Binary Search Trees (BST), she created her own. However, she unknowingly swap...read more
Identify and reverse the swap in a Binary Search Tree to recover the original structure.
Identify the two nodes that are swapped in the Binary Search Tree.
Swap the two nodes to restore the Binary Search Tree integrity.
Ensure that the left subtree of a node contains only nodes with data less than the node's data, and the right subtree contains only nodes with data greater than the node's data.
Q39. Which of the following numbers cannot be represented accurately in > binary? > a) 0.1 b) 6.5 c) 1/16 d)1.32 e) 0.590625 (not sure abt option e) > > 1. a only > 2. a and b > 3. a, b and d > 4. a, b and e > (not...
read moreIdentifying which numbers cannot be accurately represented in binary.
Binary cannot accurately represent decimal fractions that do not have a power of 2 as their denominator.
Option a (0.1) and option e (0.590625) cannot be accurately represented in binary.
Option b (6.5) and option d (1.32) can be accurately represented in binary.
Option c (1/16) can be accurately represented in binary as 0.0001.
Q40. 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.
Q41. Maximum Path Sum Between Two Leaves of a Binary Tree Problem Statement
You are provided with a non-empty binary tree where each node has a non-negative integer value. Compute and return the maximum possible sum...read more
Find the maximum path sum between two leaves in a binary tree.
Traverse the binary tree to find the maximum path sum between two leaves.
Keep track of the maximum sum encountered during traversal.
Consider all possible paths that include leaf nodes.
Handle cases where there is only one leaf node or no leaf nodes.
Implement a recursive function to calculate the maximum path sum.
Rearrange Array to Form Largest Number
Given an array ARR
consisting of non-negative integers, rearrange the numbers to form the largest possible number. The digits within each number cannot be changed.
Input:
Rearrange the array elements to form the largest possible number by concatenating them.
Sort the array elements in a custom way to form the largest number.
Convert integers to strings for comparison while sorting.
Handle edge cases like leading zeros in the final number.
Example: For input [12, 5, 34], the output should be '53412'.
Q43. Polynomial Simplification Problem Statement
You are provided with two arrays representing the coefficients and degrees of a polynomial expression. Your task is to simplify this polynomial into its general form ...read more
Simplify a polynomial expression by combining like terms and arranging them in descending order of degrees.
Iterate through the coefficients and degrees arrays to combine like terms
Create a map to store coefficients based on degrees
Sort the map keys in descending order to get the simplified polynomial
Q44. 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).
Q45. 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
Q46. 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.
Q47. 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
Q48. Construct Binary Tree from Inorder and Preorder Traversal
Given the preorder and inorder traversal sequences of a binary tree, your task is to construct the binary tree using these traversals.
Input:
The input ...read more
Yes, it is possible to achieve a solution with O(N) time complexity using a hashmap to store the indices of elements in the inorder traversal.
Use a hashmap to store the indices of elements in the inorder traversal for quick lookup.
Recursively build the binary tree by selecting the root node from the preorder traversal and finding its index in the inorder traversal.
Divide the inorder traversal into left and right subtrees based on the root node index.
Repeat the process for the...read more
Q49. 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.
Q50. What are the steps which you will follow if a customer calls and tell you that he is not able to do any editing in Microsoft word?
Steps to follow when a customer reports inability to edit in Microsoft Word
Ask the customer if they are receiving any error messages
Check if the document is in read-only mode
Check if the customer has the necessary permissions to edit the document
Check if the customer's version of Microsoft Word is up to date
Try repairing or reinstalling Microsoft Word
If all else fails, escalate the issue to a higher level of support
Q51. Add Two Numbers Represented by Linked Lists
Given two singly linked lists, each representing a positive number without leading zeros, your task is to add these two numbers. The result should be returned as a li...read more
Add two numbers represented by linked lists and return the sum as a linked list.
Traverse both linked lists simultaneously while keeping track of carry.
Create a new linked list to store the sum.
Handle cases where one linked list is longer than the other.
Update the next pointer of the current node to point to the new node with the sum.
Handle the carry if it exists after reaching the end of both linked lists.
Q52. Cycle Detection in a Linked List
Determine if a given Singly Linked List of integers forms a cycle or not.
Explanation:
A cycle occurs when a node's next
points back to a previous node in the list. This means 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.
Traverse the linked list using two pointers, one moving one step at a time and the other moving two steps at a time.
If the two pointers meet at any point, there is a cycle in the linked list.
If one of the pointers reaches the end of the list (null), there is no cycle.
Q53. Delete N Nodes After M Nodes in a Linked List
Given a singly linked list and two integers 'N' and 'M', traverse the linked list to retain 'M' nodes and then delete the next 'N' nodes. Continue this process unti...read more
Traverse a linked list to retain 'M' nodes and then delete the next 'N' nodes, repeating until the end of the list.
Create a function that takes the head of the linked list, 'N', and 'M' as input parameters.
Traverse the linked list, retaining 'M' nodes and deleting the next 'N' nodes in each iteration.
Continue this process until the end of the linked list is reached.
Update the next pointers accordingly to skip 'N' nodes after retaining 'M' nodes.
Return the modified linked list...read more
Q54. Simplify Directory Path Problem Statement
You are provided with a directory path in Unix-style notation, and your task is to simplify it according to given rules.
In a Unix-style file system:
- A dot (.) refers ...read more
The task is to simplify a directory path in Unix-style notation according to given rules.
Use a stack to keep track of directories while iterating through the input path.
Handle cases for '.', '..', and multiple slashes to simplify the path.
Return the simplified path starting with a slash and without a trailing slash.
Q55. 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.
Q56. Cash Flow Minimization Problem
You are presented with a list of financial transactions among ‘n’ friends, where each transaction specifies who pays whom and how much. The objective is to minimize the cash flow ...read more
The problem involves minimizing cash flow among friends by reorganizing debts through direct transfers or reducing total transactions.
Given a list of financial transactions among 'n' friends, where each transaction specifies who pays whom and how much.
Objective is to minimize the cash flow among the friends by reorganizing debts through direct transfers or reducing total transactions.
Output a 2-D matrix showing the optimized transactions for each test case.
Example: For input ...read more
Q57. You have 3 baskets- one containing apples, one oranges and the last containing both. All baskets are incorrectly labelled.You can pick *one* fruit from *any one* basket and are supposed to correctly label all o...
read morePick a fruit from the basket containing both fruits and label the baskets accordingly.
Pick a fruit from the basket labelled 'apples and oranges'
If you pick an apple, label the basket containing only apples
If you pick an orange, label the basket containing only oranges
Label the remaining basket as containing both fruits
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. 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
Q60. A process doesn't require additional processors to carry out 40% of > it's execution since 40% is mostly sequential. Determine how many > additional processors are required to execute the process in 150s if > t...
read moreAdditional processors required to execute a process in 150s with 40% sequential execution.
Process takes 300s on a single processor
40% of the process is sequential and doesn't require additional processors
Calculate the time taken by the remaining 60% of the process
Determine the speedup required to execute the remaining 60% in 150s
Calculate the number of additional processors required based on the speedup
Q61. Given a string s[1...n] and a reverse function reverse(s, i, k) > which reverses the character sequence from i to k (inclusive of both) > in string s, determine what the following operations result in. > 1 > re...
read moreDetermining the result of string reversal and rotation operations using a reverse function.
The first operation reverses the first half and second operation reverses the second half of the string, resulting in a rotation of the string left k positions.
The third operation reverses the entire string, resulting in a reversal of the string.
Therefore, the correct answer is (b) Rotates the String left k positions.
Example: s = 'abcdefg', k = 3, reverse(s, 1, 3) = 'cbadefg', reverse(s...read more
Q62. 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
Q63. Sum of Leaf Nodes at Maximum Level Problem Statement
Given a binary tree of integers, your task is to calculate the sum of all the leaf nodes which are present at the deepest level of the binary tree. If there ...read more
Calculate the sum of leaf nodes at the deepest level of a binary tree.
Traverse the binary tree to find the deepest level.
Keep track of leaf nodes at the deepest level and calculate their sum.
Handle null nodes represented by -1.
Ensure the sum fits in a 32-bit integer.
Q64. 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.
Q65. 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
Q66. 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.
Q67. Check Word Presence in String
Given a string S
and a list wordList
containing N
distinct words, determine if each word in wordList
is present in S
. Return a boolean array where the value at index 'i' indicates ...read more
Given a string and a list of words, check if each word in the list is present in the string and return a boolean array.
Iterate through each word in the wordList and check if it is present in the string S.
Use a boolean array to store the presence of each word in the string.
Remember that the presence of a word is case sensitive.
Do not use built-in string-matching methods.
Return the boolean array without printing it.
Q68. 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'.
Q69. 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.
Q70. Maximum Meetings Problem Statement
Given the schedule of N meetings with their start time Start[i]
and end time End[i]
, you need to determine which meetings can be organized in a single meeting room such that t...read more
Given N meetings with start and end times, find the maximum number of meetings that can be organized in a single room without overlap.
Sort the meetings based on their end times.
Iterate through the sorted meetings and select the first meeting that doesn't overlap with the previous one.
Repeat the process until all meetings are considered.
Return the selected meetings in the order they are organized.
Q71. Minimum Number of Platforms Needed Problem Statement
You are given the arrival and departure times of N trains at a railway station for a particular day. Your task is to determine the minimum number of platform...read more
Determine the minimum number of platforms needed at a railway station based on arrival and departure times of trains.
Sort the arrival and departure times in ascending order.
Use two pointers to keep track of overlapping schedules.
Increment the platform count when a new train arrives before the previous one departs.
Return the maximum platform count needed.
Q72. Rearrange String Problem Statement
Given a string ‘S’, your task is to rearrange its characters so that no two adjacent characters are the same. If it's possible, return any such arrangement, otherwise return “...read more
Given a string, rearrange its characters so that no two adjacent characters are the same.
Iterate through the string and count the frequency of each character.
Use a priority queue to rearrange the characters based on their frequency.
Check if it's possible to rearrange the string without any two adjacent characters being the same.
Return 'Yes' if possible, 'No' otherwise.
Q73. 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
Q74. 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
Q75. Check Permutation Problem Statement
Determine if two given strings, 'str1'
and 'str2'
, are permutations of each other.
Explanation:
Two strings are permutations of each other if one string's characters can be r...read more
Check if two strings are permutations of each other.
Create a character frequency map for both strings and compare them.
If the frequency of characters in both maps is the same, return true.
Handle edge cases like empty strings or strings of different lengths.
Q76. N-Queens Problem Statement
Given an integer N
, your task is to position N
queens on an N x N
chessboard in such a way that no two queens threaten each other.
A queen can attack other queens that are in the same...read more
Position N queens on an N x N chessboard so that no two queens threaten each other.
Use backtracking to explore all possible configurations.
Keep track of rows, columns, and diagonals to ensure no two queens threaten each other.
Display all valid configurations found.
Q77. You're in the center of a circular pond, with an *intelligent* lion at the circumference - intelligent implies you can't trivially fool it. Given that, your swimming speed = x, lion's running speed on land = 4x...
read moreEscape from an intelligent lion at the circumference of a circular pond with given speeds.
Swim towards the circumference of the pond to make the lion run a longer distance.
Once the lion is at a considerable distance, get out of the pond and run in the opposite direction.
Use obstacles like trees or rocks to slow down the lion.
Try to confuse the lion by changing directions frequently.
Q78. Given a bit pattern (in an integer INPUT), and another pattern (in an integer PATTERN, with a number n signifying the number of trailing bits to be considered as pattern - remaining bits are zero. Example: PATT...
read moreCount the number of occurrences of a given bit pattern in an integer.
Extract the n trailing bits from the pattern and create a mask with all other bits set to zero.
Use a sliding window approach to compare the extracted pattern with all possible n-bit sequences in the input integer.
Increment a counter every time the extracted pattern matches with a sequence in the input integer.
Q79. 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
Q80. 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
Q81. When a sorted array is ‘Rotated’, its last element becomes the first element and the remaining elements shift to the right. Write a function which takes an input array and returns the no. of times an array has...
read moreFunction to find the no. of times a sorted array has been rotated.
Find the index of the minimum element in the array using binary search.
The number of times the array has been rotated is equal to the index of the minimum element.
Handle the case where the array is not rotated (minimum element at index 0).
Q82. If len is the length of the string and num is the number of > characters printed on the screen > Give the relation between num and len. > > void abc (char *s){ > if(s[0]=='�') > return; > > abc(s+1); > abc(s+1)...
read moreRelation between num and len in a given code snippet
The code recursively calls the function abc() twice for each character in the string
The printf() statement prints each character once
The number of '>' characters printed on the screen is equal to num
The length of the string is equal to len
The relation between num and len is num = 2^len - 1
Q83. Water Equalization Problem Statement
You are provided with an array ARR
of positive integers. Each integer represents the number of liters of water in a bucket. The goal is to make the liters of water in every ...read more
Given an array of water buckets, find the minimum liters of water to remove to make all buckets contain the same amount of water.
Iterate through the array to find the most common amount of water in the buckets.
Calculate the total liters of water that need to be removed to equalize all buckets to the most common amount.
Return the total liters of water to be removed.
Q84. Rat in a Maze Problem Statement
You need to determine all possible paths for a rat starting at position (0, 0) in a square maze to reach its destination at (N-1, N-1). The maze is represented as an N*N matrix w...read more
Find all possible paths for a rat in a maze from source to destination.
Use backtracking to explore all possible paths in the maze.
Keep track of visited cells to avoid revisiting them.
Explore all possible directions (up, down, left, right) from each cell.
Add the current direction to the path and recursively explore further.
If the destination is reached, add the path to the list of valid paths.
Q85. Minimum Fountains Activation Problem
In this problem, you have a one-dimensional garden of length 'N'. Each position from 0 to 'N' has a fountain that can provide water to the garden up to a certain range. Thus...read more
Find the minimum number of fountains to activate to water the entire garden.
Iterate through the array to find the coverage of each fountain.
Keep track of the farthest coverage reached by activating fountains.
Activate the fountain that covers the farthest point not yet covered.
Repeat until the entire garden is watered.
Q86. Minimize Cash Flow Problem
You are provided with a list of 'transactions' involving 'n' friends who owe each other money. Each entry in the list contains information about a receiver, sender, and the transactio...read more
Minimize cash flow problem among friends by optimizing transactions.
Create a graph where nodes represent friends and edges represent transactions.
Calculate net amount each friend owes or is owed by summing up all transactions.
Use a recursive algorithm to minimize cash flow by settling debts between friends.
Update the graph and repeat the process until all debts are settled.
Q87. 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.
Q88. 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.
Q89. Spiral Order Traversal of a Binary Tree Problem Statement
Given a binary tree with 'N' nodes, your task is to print the nodes in spiral order traversal.
Example:
Input:
The binary tree is represented in level o...read more
Print nodes of a binary tree in spiral order traversal.
Use a queue to perform level order traversal of the binary tree.
Alternate between printing nodes from left to right and right to left at each level.
Handle null nodes represented by '-1' appropriately.
Example: For input '1 2 3 -1 -1 4 5 -1 -1 -1 -1', the output should be '1 3 2 4 5'.
Q90. Word Break Problem Statement
You are given a list of N
strings called A
. Your task is to determine whether you can form a given target string by combining one or more strings from A
.
The strings from A
can be u...read more
Given a list of strings, determine if a target string can be formed by combining one or more strings from the list.
Iterate through all possible combinations of strings from the list to form the target string.
Use recursion to try different combinations of strings.
Check if the current combination forms the target string.
Return true if a valid combination is found, otherwise return false.
Q91. 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
Q92. 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.
Q93. 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
Q94. 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.
Q95. How do we solve the power bi report refresh issue, if the credentials are fine and report is refreshing fine at desktop ?
Check if the data source is accessible and refresh schedule is set up correctly.
Verify if the data source is accessible from the Power BI service.
Check if the refresh schedule is set up correctly.
Ensure that the credentials used for refreshing the report are correct.
Check if there are any errors or warnings in the refresh history.
Try refreshing the report manually from the Power BI service.
Check if there are any issues with the data model or queries used in the report.
Q96. Rooms and Keys Problem Statement
Given some information about rooms in a military camp, where rooms are numbered from 0 to 'N-1'. Each room may contain keys to some other rooms. You can only visit a room if you...read more
Determine if all rooms can be visited starting from room 0 with given keys information.
Use depth-first search (DFS) to traverse through rooms and keys.
Keep track of visited rooms to avoid infinite loops.
Check if all rooms have been visited at the end.
Q97. 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'.
Q98. 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
Q99. 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.
Q100. 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.
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

