Add office photos
Employer?
Claim Account for FREE

Microsoft Corporation

4.0
based on 1.7k Reviews
Video summary
Proud winner of ABECA 2024 - AmbitionBox Employee Choice Awards
Filter interviews by

100+ Hilton Interview Questions and Answers

Updated 8 Aug 2024
Popular Designations

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

Ans.

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.

View 2 more answers

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

Ans.

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.

Add your answer

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
Ans.

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

Add your answer

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 more
Ans.

Program 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

View 1 answer
Discover Hilton interview dos and don'ts from real experiences

Q5. 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

Ans.

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.

Add your answer

Q6. 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

Ans.

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.

Add your answer
Are these interview questions helpful?

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

Ans.

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

Add your answer

Q8. 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

Ans.

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.

Add your answer
Share interview questions and help millions of jobseekers 🌟

Q9. 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

Ans.

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.

Add your answer

Q10. 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
Ans.

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.

Add your answer

Q11. 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

Ans.

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.

Add your answer

Q12. 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

Ans.

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

Add your answer

Q13. 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

Ans.

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.

Add your answer

Q14. 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

Ans.

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.

View 1 answer

Q15. 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

Ans.

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.

Add your answer

Q16. 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

Ans.

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.

Add your answer

Q17. 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
Ans.

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

Add your answer

Q18. 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

Ans.

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

Add your answer

Q19. 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
Ans.

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)

Add your answer

Q20. 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

Ans.

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

Add your answer

Q21. 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

Ans.

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.

Add your answer

Q22. 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

Ans.

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

Add your answer

Q23. 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

Ans.

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.

Add your answer

Q24. 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

Ans.

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.

Add your answer

Q25. 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

Ans.

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.

Add your answer

Q26. 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

Ans.

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

Add your answer

Q27. 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 more
Ans.

Identifying 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.

Add your answer

Q28. 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

Ans.

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.

Add your answer

Q29. 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

Ans.

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

Add your answer
Q30. ...read more

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:

Ans.

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'.

Add your answer

Q31. 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

Ans.

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

Add your answer

Q32. 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

Ans.

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).

Add your answer

Q33. 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
Ans.

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.

Add your answer

Q34. 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

Ans.

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

Add your answer

Q35. 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
Ans.

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

Add your answer

Q36. 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 more
Ans.

Pick 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

Add your answer

Q37. 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

Ans.

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.

Add your answer

Q38. 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

Ans.

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.

Add your answer

Q39. 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

Ans.

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

Add your answer

Q40. 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
Ans.

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.

Add your answer

Q41. 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

Ans.

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

Add your answer

Q42. 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

Ans.

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.

Add your answer

Q43. 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 more
Ans.

Additional 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

Add your answer

Q44. 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 more
Ans.

Determining 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

Add your answer

Q45. Maximum Subarray Sum Problem Statement

Given an array 'ARR' of integers with length 'N', the task is to determine the sum of the subarray (including an empty subarray) that yields the maximum sum among all poss...read more

Ans.

Find the maximum sum of a subarray in an array of integers.

  • Iterate through the array and keep track of the maximum sum subarray ending at each index.

  • Use Kadane's algorithm to efficiently find the maximum subarray sum.

  • Consider the case where all elements are negative, in which case the maximum sum would be the largest negative number.

Add your answer

Q46. 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

Ans.

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.

Add your answer

Q47. 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
Ans.

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.

Add your answer

Q48. 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

Ans.

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.

Add your answer

Q49. 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

Ans.

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'.

Add your answer

Q50. 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

Ans.

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.

Add your answer

Q51. 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

Ans.

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.

Add your answer

Q52. 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

Ans.

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

Add your answer

Q53. 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

Ans.

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.

Add your answer

Q54. 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

Ans.

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.

Add your answer

Q55. 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

Ans.

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

Add your answer

Q56. 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 more
Ans.

Escape 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.

Add your answer

Q57. 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

Ans.

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.

Add your answer

Q58. 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

Ans.

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.

  • Example: For input [4, 2, 0, 3], the trapped water would be 3 units.

  • Exam...read more

Add your answer

Q59. 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
Ans.

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.

Add your answer

Q60. 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 more
Ans.

Count 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.

View 2 more answers

Q61. 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

Ans.

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

Add your answer

Q62. 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 more
Ans.

Relation 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

Add your answer

Q63. 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

Ans.

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.

Add your answer

Q64. 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

Ans.

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.

Add your answer

Q65. 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

Ans.

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.

Add your answer

Q66. 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

Ans.

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.

Add your answer

Q67. 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

Ans.

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.

Add your answer

Q68. 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

Ans.

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.

Add your answer

Q69. 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
Ans.

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'.

Add your answer

Q70. 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

Ans.

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.

Add your answer

Q71. 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

Ans.

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'.

Add your answer

Q72. 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

Ans.

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

Add your answer

Q73. 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

Ans.

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.

Add your answer

Q74. 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

Ans.

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.

Add your answer

Q75. What is deadlock?Conditions for that?What are the methods to prevent it?Write code to prevent the deadlock for OS, considering that there are two processes P0 and P1 in OS and they are requesting resources dyna...

read more
Ans.

Deadlock is a situation where two or more processes are unable to proceed due to a circular dependency on resources.

  • Deadlock occurs when two or more processes are waiting for resources held by each other.

  • Conditions for deadlock are mutual exclusion, hold and wait, no preemption, and circular wait.

  • Methods to prevent deadlock include resource allocation graph, banker's algorithm, and deadlock avoidance.

  • To prevent deadlock in OS, use resource allocation graph and banker's algori...read more

Add your answer

Q76. 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

Ans.

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

Add your answer

Q77. Left View of a Binary Tree Problem Statement

Given a binary tree, your task is to print the left view of the tree.

Example:

Input:
The input will be in level order form, with node values separated by a space. U...read more
Ans.

Print the left view of a binary tree given in level order form.

  • Traverse the tree level by level and print the first node of each level (leftmost node).

  • Use a queue to keep track of nodes at each level.

  • Time complexity should be O(n) where n is the number of nodes in the tree.

Add your answer

Q78. Time complexity of a function f(m) is O(m). If the array[i...n] &gt; contains either 1 or 0 in each of it's locations, determine the worst &gt; case time complexity of the following piece of code written in C-like &gt;...

read more
Ans.

Determining worst case time complexity of a code snippet with given time complexity of a function and array

  • The time complexity of the given code snippet is O(n)

  • The function f(m) is called only when a 0 is encountered in the array

  • The worst case time complexity is O(n)

  • The code snippet iterates through the entire array once

Add your answer

Q79. 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
Ans.

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.

Add your answer

Q80. “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 more
Ans.

Code 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

Add your answer

Q81. Given an integer array, find all (a,b,c) such that a^2 + b^2 = c^2 Solution is O(n^2) Write code and testcases

Ans.

Given an integer array, find all (a,b,c) such that a^2 + b^2 = c^2. Solution is O(n^2). Write code and testcases.

  • Use nested loops to iterate through all possible pairs of integers in the array

  • Check if the sum of squares of the two integers is a perfect square

  • If yes, add the triplet to the result list

  • Return the result list

Add your answer

Q82. 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 more
Ans.

The 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

Add your answer

Q83. 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 more
Ans.

Compress 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.

Add your answer

Q84. 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 ­&gt; 3 ­&gt; 5, LL2= 1­&gt;4­&gt;5, result should be LL3= 3­&gt;8­&gt;0...

read more
Ans.

The 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.

Add your answer

Q85. Increasing the RAM increases the efficiency of the CPU. The reason &gt; is &gt; a) Virtual memory increases &gt; b) Number of page Page faults decreases &gt; c) Page segmentation decreases &gt; d) Increasing the amount of mem...

read more
Ans.

Increasing RAM improves CPU efficiency due to virtual memory and reduced page faults.

  • Increasing RAM allows for more data to be stored in memory, reducing the need for frequent access to slower storage devices.

  • Virtual memory allows the operating system to use hard disk space as if it were RAM, increasing the effective amount of memory available to the CPU.

  • Reducing page faults, which occur when the CPU needs to access data that is not currently in memory, improves CPU efficienc...read more

Add your answer

Q86. 1. Write a routine to output the elements of the inorder traversal of a binary tree one by one in its each call. eg: Assuming the inorder traversal is 1, 2, 3, 4, 5, the routine should return 1 in its first cal...

read more
Ans.

The routine should output the elements of the inorder traversal of a binary tree one by one in each call.

  • Implement an inorder traversal algorithm recursively

  • Use a global variable or pass a reference to keep track of the current element

  • Call the routine repeatedly to get the next element in each call

Add your answer

Q87. 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 more
Ans.

The 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

Add your answer

Q88. 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 more
Ans.

Merge '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

Add your answer

Q89. What is the use of printf() and scanf() function?

Ans.

printf() is used to print formatted output to the screen, while scanf() is used to read formatted input from the user.

  • printf() is used to display output on the screen in a formatted way.

  • scanf() is used to read input from the user in a formatted way.

  • Example: printf("Hello, World!"); will display 'Hello, World!' on the screen.

  • Example: scanf("%d", &num); will read an integer input from the user and store it in 'num'.

View 2 more answers

Q90. 2 magnesium strips and a matchbox are given. Each burns in 60 minutes, with no relation between length burnt and time. Calculate 45 min

Ans.

Burning time of magnesium strips and matchbox given, calculate 45 min.

  • Calculate the total burning time of both magnesium strips and matchbox

  • Divide the total burning time by 4 to get the burning time of 1/4th of the material

  • Subtract the burning time of 1/4th of the material from the total burning time to get the remaining burning time

  • Divide the remaining burning time by 3 to get the burning time of 1/3rd of the remaining material

  • Add the burning time of 1/4th of the material an...read more

Add your answer

Q91. Given a pointer to the root of a binary tree, find whether the left and right subtrees are mirror images of each other

Ans.

Given a binary tree, check if left and right subtrees are mirror images of each other.

  • Traverse the tree and compare left and right subtrees recursively.

  • Use a stack or queue to traverse the tree iteratively.

  • Check if the left subtree is a mirror image of the right subtree by comparing their values and structures.

  • Consider an empty tree as a mirror image of itself.

Add your answer
Q92. Can you describe the ACID properties in DBMS?
Ans.

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

Add your answer

Q93. 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,

Ans.

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

Add your answer

Q94. If you chance to develop a software wich type of software do you want to develop?

Ans.

I would like to develop a mobile application that helps people track their daily water intake.

  • The app would allow users to set daily water intake goals and track their progress throughout the day.

  • It could also provide reminders to drink water and offer tips for staying hydrated.

  • The app could integrate with wearable devices to automatically track water intake.

  • Users could also log the type of water they are drinking, such as tap water or bottled water.

  • The app could provide insi...read more

Add your answer
Q95. Can you provide a code example that demonstrates communication between two processes?
Ans.

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.

Add your answer
Q96. Can you explain the concepts related to memory management in operating systems?
Ans.

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

Add your answer

Q97. How will you construct parse tree for ((a+b)*c)/d? what all data structures can you use?

Ans.

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.

Add your answer

Q98. Given two sorted arrays, say A and B, find A ­ B. Here, A ­ B means all those elements present in A but not in B. The expected time complexity was O(m + n), if A is of size m and B is of size n

Ans.

Find A-B of two sorted arrays A and B in O(m+n) time complexity.

  • Create two pointers, one for each array, and compare the elements at those pointers.

  • If the element in A is smaller, add it to the result array and move the A pointer forward.

  • If the element in B is smaller, move the B pointer forward.

  • Repeat until one of the pointers reaches the end of its array.

  • Add any remaining elements in A to the result array.

  • Time complexity is O(m+n) as we only iterate through each array once.

Add your answer

Q99. Given a linked list, invert every two nodes in the list.Eg. Given a ­&gt; b ­&gt; c ­&gt; d, result should be b ­&gt; a ­&gt; d ­&gt; c

Ans.

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.

Add your answer

Q100. Find the height og a binary tree without recursion. Write code and testcases

Ans.

Find height of binary tree without recursion

  • Use a stack to keep track of nodes

  • Iteratively traverse the tree and update height

  • Testcases: empty tree, single node tree, balanced tree, unbalanced tree

Add your answer
1
2

More about working at Microsoft Corporation

Top Rated Internet/Product Company - 2024
Contribute & help others!
Write a review
Share interview
Contribute salary
Add office photos

Interview Process at Hilton

based on 29 interviews
4 Interview rounds
Coding Test Round - 1
Coding Test Round - 2
One-on-one Round
HR Round
View more
Interview Tips & Stories
Ace your next interview with expert advice and inspiring stories

Top Software Developer Interview Questions from Similar Companies

4.0
 • 105 Interview Questions
3.5
 • 35 Interview Questions
4.3
 • 31 Interview Questions
3.5
 • 28 Interview Questions
1.9
 • 22 Interview Questions
3.8
 • 12 Interview Questions
View all
Share an Interview
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
70 Lakh+

Reviews

5 Lakh+

Interviews

4 Crore+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter