
Microsoft Corporation


60+ Microsoft Corporation Software Developer 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. 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.
Q3. 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.
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. 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.
Q6. 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.
Q7. 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.
Q8. 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.
Q9. 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
Q10. 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.
Q11. 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.
Q12. 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.
Q13. 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
Q14. 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
Q15. 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
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. 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).
Q19. 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
Q20. 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.
Q21. 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
Q22. 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.
Q23. 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.
Q24. 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
Q25. 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'.
Q26. 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.
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. 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
Q29. 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 over the matrix in a spiral path by keeping track of the boundaries.
Print the elements in the spiral path as you traverse the matrix.
Handle cases where the matrix is not a square matrix separately.
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
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
Q45. 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
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.
Q48. 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.
Q49. 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.
Q50. 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
Q51. 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
Q52. 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
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)
Q54. 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)
Q55. 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.
Q56. 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
Q57. 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).
Q58. Given a node in a binary tree, find the leftmost node in the same level
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 in the level of the given node
Q59. Find the nth largest number in a binary tree
Find the nth largest number in a binary tree
Traverse the tree in-order and store the values in an array
Return the (n-1)th index of the sorted array in descending order
Use a max heap to keep track of the largest n elements
Q60. What type of program
I'm sorry, could you please clarify what type of program you are referring to?
Ask for more information about the program in question
Provide examples of different types of programs
Clarify the context of the question
More about working at Microsoft Corporation




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

Top Software Developer Interview Questions from Similar Companies








Reviews
Interviews
Salaries
Users/Month

