Adobe
300+ Tech Mahindra Interview Questions and Answers
Q1. Delete the Middle Node from a Singly Linked List
Given a singly linked list of integers, the task is to remove the middle node from this list.
Input:
The first line of input includes an integer 'T' which denote...read more
The task is to delete the middle node of a singly linked list of integers.
If the linked list is empty or has only one node, there is no middle node to delete.
To delete the middle node, we need to find the middle node and update the pointers of the previous and next nodes.
To find the middle node in one traversal, we can use two pointers - a slow pointer and a fast pointer.
The slow pointer moves one node at a time, while the fast pointer moves two nodes at a time.
When the fast ...read more
Q2. Morty's Array Challenge
Rick has provided Morty with an array 'Arr' of length 'N' and an integer 'K'. Morty needs to split the array into non-empty sub-arrays to achieve the minimum possible cost, subject to th...read more
The challenge involves splitting an array into sub-arrays to minimize cost based on unique elements and repetitions.
Iterate through the array and keep track of unique elements and repetitions
Calculate cost for each sub-array based on the rules provided
Sum up the costs for all sub-arrays to get the total minimum cost
Q3. Sub Sort Problem Statement
You are given an integer array ARR
. Determine the length of the shortest contiguous subarray which, when sorted in ascending order, results in the entire array being sorted in ascendi...read more
The task is to find the length of the shortest contiguous subarray that needs to be sorted in order to sort the entire array.
Iterate through the array from left to right and find the first element that is out of order.
Iterate through the array from right to left and find the first element that is out of order.
Find the minimum and maximum elements within the subarray defined by the above two elements.
Expand the subarray to include any additional elements that are out of order ...read more
Q4. Problem: Search In Rotated Sorted Array
Given a sorted array that has been rotated clockwise by an unknown amount, you need to answer Q
queries. Each query is represented by an integer Q[i]
, and you must determ...read more
This is a problem where a sorted array is rotated and we need to search for given numbers in the array.
The array is rotated clockwise by an unknown amount.
We need to perform binary search to find the index of the given numbers.
If the number is found, return its index. Otherwise, return -1.
The time complexity of the solution should be O(logN).
Q5. Quick Sort Problem Statement
You are provided with an array of integers. The task is to sort the array in ascending order using the quick sort algorithm.
Quick sort is a divide-and-conquer algorithm. It involve...read more
The question asks to implement quick sort algorithm to sort an array of integers in ascending order.
Quick sort is a divide and conquer algorithm
Choose a pivot point and partition the array into two parts
Recursively sort the left and right parts of the array
Implement the quick sort algorithm to sort the given array
Q6. Swap Adjacent Bit Pairs Problem Statement
Given an integer N
, your task is to compute the number that results from swapping each even position bit of N
's binary representation with its adjacent odd bit to the r...read more
The task is to swap each even bit of an integer with its adjacent bit on the right in its binary representation.
Convert the given integer to its binary representation
Iterate through the binary representation and swap each even bit with its adjacent bit on the right
Convert the modified binary representation back to an integer
Print the resulting integer
Q7. Power Calculation Problem Statement
Given a number x
and an exponent n
, compute xn
. Accept x
and n
as input from the user, and display the result.
Note:
You can assume that 00 = 1
.
Input:
Two integers separated...read more
Calculate x raised to the power of n, given x and n as input from the user.
Accept two integers x and n as input from the user
Compute x^n and display the result
Handle the case where x=0 and n=0 separately (0^0 = 1)
Q8. LCA in a Binary Search Tree
You are given a binary search tree (BST) containing N nodes. Additionally, you have references to two nodes, P and Q, within this BST.
Your task is to determine the Lowest Common Anc...read more
The task is to find the lowest common ancestor (LCA) of two given nodes in a binary search tree (BST).
The LCA is the lowest node that has both given nodes as descendants.
In a BST, 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.
Start from the root node and compare it with the given nodes. If both nodes are smaller than the current node, move to the left subtree...read more
Q9. Merge Two Sorted Linked Lists Problem Statement
You are provided with two sorted linked lists. Your task is to merge them into a single sorted linked list and return the head of the combined linked list.
Input:...read more
The task is to merge two sorted linked lists into a single sorted linked list.
Create a new linked list to store the merged list
Compare the values of the nodes from both lists and add the smaller value to the new list
Move the pointer of the list with the smaller value to the next node
Repeat the comparison and addition until one of the lists is empty
Add the remaining nodes from the non-empty list to the new list
Return the head of the new list
Q10. 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 a given matrix.
Iterate through the matrix in a spiral pattern, starting from the outermost layer and moving towards the center.
Keep track of the current row, column, and the boundaries of the remaining unvisited matrix.
Print the elements in the spiral path as you traverse the matrix.
Q11. Minimum Cost to Make String Valid
Given a string containing only '{' and '}', determine the minimum cost required to make the string valid. A string is considered valid if for every opening bracket '{', there i...read more
Given a string with only '{' and '}', find the minimum cost to make it valid by converting brackets.
Iterate through the string and keep track of the opening and closing brackets
If there are more closing brackets than opening brackets, convert the excess closing brackets to opening brackets
If there are more opening brackets than closing brackets, convert the excess opening brackets to closing brackets
Return the total cost of conversions needed to make the string valid
Q12. Sort Array by Set Bit Count
Given an array of positive integers, your task is to sort the array in decreasing order based on the count of set bits in the binary representation of each integer.
If two numbers ha...read more
Sort the array in decreasing order based on the count of set bits in the binary representation of each integer.
Iterate through the array and calculate the set bit count for each integer using bitwise operations.
Use a custom comparator function to sort the array based on the set bit count.
Maintain the original order for integers with the same set bit count.
Modify the array in-place within the given function.
Q13. Prime with 3 Factors Problem Statement
You are provided with an array ARR
consisting of 'N' positive integers. Your task is to determine if each number in the array ARR
has exactly 3 factors.
You need to return...read more
Determine if each number in the array has exactly 3 factors.
Iterate through each number in the array and check if it has exactly 3 factors.
Factors of a number can be found by iterating from 1 to the square root of the number.
Count the number of factors and return 1 if it is exactly 3, else return 0.
Q14. Validate BST Problem Statement
Given a binary tree with N
nodes, determine whether the tree is a Binary Search Tree (BST). If it is a BST, return true
; otherwise, return false
.
A binary search tree (BST) is a b...read more
Validate if a binary tree is a Binary Search Tree (BST) based on given properties.
Check if left subtree contains only nodes with data less than current node's data
Check if right subtree contains only nodes with data greater than current node's data
Recursively check if both left and right subtrees are also BSTs
Q15. Maximum Non-Adjacent Subsequence Sum
Given an array of integers, determine the maximum sum of a subsequence without choosing adjacent elements in the original array.
Input:
The first line consists of an integer...read more
Find the maximum sum of a subsequence without choosing adjacent elements in the original array.
Iterate through the array and keep track of the maximum sum of non-adjacent elements.
At each index, compare the sum of including the current element with excluding the current element.
Return the maximum sum obtained.
Example: For input [3, 2, 7, 10], the maximum sum is 13 by selecting 3 and 10.
Example: For input [3, 2, 5], the maximum sum is 8 by selecting 3 and 5.
Q16. Reverse Linked List Problem Statement
Given a singly linked list of integers, return the head of the reversed linked list.
Example:
Initial linked list: 1 -> 2 -> 3 -> 4 -> NULL
Reversed linked list: 4 -> 3 -> 2...read more
Reverse a singly linked list of integers and return the head of the reversed linked list.
Iterate through the linked list and reverse the pointers to point to the previous node instead of the next node.
Use three pointers to keep track of the current, previous, and next nodes while reversing the linked list.
Ensure to update the head of the reversed linked list at the end of the process.
Example: Input: 1 -> 2 -> 3 -> 4 -> NULL, Output: 4 -> 3 -> 2 -> 1 -> NULL
Q17. Stack with getMin Operation
Create a stack data structure that supports not only the usual push and pop operations but also getMin(), which retrieves the minimum element, all in O(1) time complexity without usi...read more
Implement a stack with push, pop, top, isEmpty, and getMin operations in O(1) time complexity without using extra space.
Use two stacks - one to store the actual elements and another to store the minimum element at each level.
When pushing an element, check if it is smaller than the current minimum and update the minimum stack accordingly.
When popping an element, also pop from the minimum stack if the popped element is the current minimum.
For getMin operation, simply return the...read more
Q18. Minimum Number of Lamps Needed
Given a string S
containing dots (.) and asterisks (*), where a dot represents free spaces and an asterisk represents lamps, determine the minimum number of additional lamps neede...read more
Determine the minimum number of additional lamps needed to illuminate a string with dots and asterisks.
Iterate through the string and check for free spaces that are not already illuminated by existing lamps
Place a lamp at each free space that is not already illuminated by an existing lamp
Consider edge cases where the first and last positions may need additional lamps
Q19. Colourful Knapsack Problem Statement
You are given N
stones labeled from 1 to N
. The i-th stone has the weight W[i]
. There are M
colors labeled by integers from 1 to M
. The i-th stone has the color C[i]
which i...read more
The task is to fill a Knapsack with stones of different colors and weights, minimizing unused capacity.
Given N stones with weights W and colors C, choose M stones (one of each color) to fill Knapsack with total weight not exceeding X
Minimize unused capacity of Knapsack by choosing stones wisely
If no way to fill Knapsack, output -1
Example: N=5, M=3, X=10, W=[1, 3, 3, 5, 5], C=[1, 2, 3, 1, 2] -> Output: 1
Q20. Minimum Fountains Activation Problem
In this problem, you have a one-dimensional garden of length 'N'. Each position from 0 to 'N' has a fountain that can provide water to the garden up to a certain range. Thus...read more
Find the minimum number of fountains to activate to water the entire garden.
Iterate through the array and keep track of the farthest point each fountain can cover.
Activate the fountain that covers the farthest point not covered by any previous fountain.
Continue this process until the entire garden is covered.
Return the count of activated fountains as the minimum number required.
Q21. Longest Common Prime Subsequence Problem Statement
Imagine Ninja is tackling a puzzle during his long summer vacation. He has two arrays of integers, each with lengths 'N' and 'M'. Ninja's task is to determine ...read more
Find the length of the longest subsequence common to two arrays consisting only of prime numbers.
Iterate through both arrays and check if the numbers are prime.
Use dynamic programming to find the longest common subsequence of prime numbers.
Keep track of the length of the common prime subsequence.
Return the length of the longest common prime subsequence.
Q22. Palindromic Partitioning Problem Statement
Given a string ‘str’, calculate the minimum number of partitions required to ensure every resulting substring is a palindrome.
Input:
The first line contains an intege...read more
The problem involves calculating the minimum number of partitions needed to ensure every resulting substring is a palindrome.
Iterate through the string and check for palindromes at each possible partition point.
Keep track of the minimum cuts needed to partition the string into palindromic substrings.
Consider edge cases such as when the string is already a palindrome or when all characters are unique.
Example: For input 'AACCB', the valid partition 'A | A | CC | B' requires 2 c...read more
Q23. Search in a Row-wise and Column-wise Sorted Matrix Problem Statement
You are given an N * N matrix of integers where each row and each column is sorted in increasing order. Your task is to find the position of ...read more
Q24. You have a lot of small integers in an array. You have to multiply all of them. You need not worry about overflow and range, you have enough support for that. What can you do to speed up the multiplication on y...
read moreTo speed up multiplication of small integers in an array, we can use bitwise operations and parallel processing.
Use bitwise operations like shifting and ANDing to perform multiplication faster.
Divide the array into smaller chunks and perform multiplication in parallel using multi-threading or SIMD instructions.
Use lookup tables for frequently used values to avoid repeated calculations.
Use compiler optimizations like loop unrolling and vectorization.
Consider using specialized ...read more
Q25. Equilibrium Index Problem Statement
Given an array Arr
consisting of N integers, your task is to find the equilibrium index of the array.
An index is considered as an equilibrium index if the sum of elements of...read more
Find the equilibrium index of an array where sum of elements on left equals sum of elements on right.
Iterate through the array and calculate the total sum of elements.
For each index, calculate the sum of elements on the left and right side and check for equilibrium.
Return the left-most equilibrium index found, or -1 if none exist.
Q26. Maximum Meetings Problem Statement
Given the schedule of N meetings with their start time Start[i]
and end time End[i]
, you need to determine which meetings can be organized in a single meeting room such that t...read more
Given N meetings with start and end times, find the maximum number of meetings that can be organized in a single room without overlap.
Sort the meetings based on end times.
Iterate through the sorted meetings and select the next meeting whose start time is greater than or equal to the end time of the previous meeting.
Return the selected meetings in the order they are organized.
Q27. Split Array Problem Statement
You are given an integer array/list arr
of size N
. Your task is to split the array into the maximum number of subarrays such that the first and last occurrence of every distinct el...read more
Split the array into maximum number of subarrays such that first and last occurrence of every distinct element lies within a single subarray.
Iterate through the array and keep track of the first and last occurrence of each element.
Use a hashmap to store the indices of each element.
Count the number of subarrays where the first and last occurrence of each element are within the same subarray.
Q28. Split Array into 'K' Consecutive Subarrays Problem
Given an integer array arr
of size N
, determine if it is possible to split the array into K
consecutive non-overlapping subarrays of length M
such that each su...read more
The problem involves splitting an array into 'K' consecutive subarrays of length 'M' with each subarray containing a single distinct element.
Iterate through the array and check if each subarray of length 'M' contains only one distinct element.
Keep track of the count of distinct elements in each subarray.
Return 1 if it is possible to split the array according to the condition, otherwise return 0.
Q29. Kevin and His Cards Problem Statement
Kevin has two packs of cards. The first pack contains N cards, and the second contains M cards. Each card has an integer written on it. Determine two results: the total num...read more
Q30. Tiling Problem Statement
Given a board with 2 rows and N columns, and an infinite supply of 2x1 tiles, determine the number of distinct ways to completely cover the board using these tiles.
You can place each t...read more
Q31. Count Distinct Substrings
You are provided with a string S
. Your task is to determine and return the number of distinct substrings, including the empty substring, of this given string. Implement the solution us...read more
Count distinct substrings of a given string using trie data structure.
Implement a trie data structure to store all substrings of the given string.
Count the number of nodes in the trie to get the distinct substrings count.
Handle empty string case separately.
Example: For 'ab', distinct substrings are: '', 'a', 'b', 'ab'.
Q32. Intersection of Two Arrays Problem Statement
Given two arrays A
and B
with sizes N
and M
respectively, both sorted in non-decreasing order, determine their intersection.
The intersection of two arrays includes ...read more
The problem involves finding the intersection of two sorted arrays efficiently.
Use two pointers to iterate through both arrays simultaneously.
Compare elements at the pointers and move the pointers accordingly.
Handle cases where elements are equal, and update the intersection array.
Return the intersection array as the result.
Q33. Max Product Subset Problem Statement
Given an array/list arr
of size n
, determine the maximum product possible by taking any subset of the array/list arr
. Return the result modulo 10^9+7
since the product can b...read more
Find the maximum product of a subset of an array modulo 10^9+7.
Iterate through the array and keep track of the maximum positive product and minimum negative product encountered so far.
Handle cases where the array contains zeros separately.
Return the maximum product modulo 10^9+7.
Q34. Split Array Into Maximum Subarrays Problem Statement
You are given an integer array arr
of size N
. Your task is to split the array into the maximum number of subarrays such that the first and last occurrence of...read more
Given an array, split it into maximum subarrays with first and last occurrence of each element in a single subarray.
Iterate through the array and keep track of the first and last occurrence of each element.
Use a hashmap to store the indices of each element.
Split the array whenever the last occurrence of an element is found.
Q35. Equalize Water in Buckets
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 water volume in each bucket equal ...read more
Given an array of positive integers representing water in buckets, find the minimum amount of water to be removed to equalize all buckets.
Sort the array in non-decreasing order to easily identify the buckets with excess water.
Calculate the average water volume by dividing the total water volume by the number of buckets.
Iterate through the array and calculate the excess water in each bucket compared to the average.
Sum up the excess water in all buckets to get the minimum amoun...read more
Q36. Minimize Cash Flow Problem
You are provided with a list of 'transactions' involving 'n' friends who owe each other money. Each entry in the list contains information about a receiver, sender, and the transactio...read more
Minimize cash flow 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.
Use a recursive algorithm to settle debts by minimizing cash flow.
Update the graph after each transaction to reflect the new balances.
Repeat the process until all balances are settled.
Q37. Maximum Sum Problem Statement
You are given an array ARR
of N integers. Your task is to perform operations on this array until it becomes empty, and maximize the sum of selected elements. In each operation, sel...read more
The task is to maximize the sum of selected elements from an array by following specific rules.
Select elements strategically to maximize the sum
Remove occurrences of selected element, and its neighbors
Repeat the process until the array becomes empty
Q38. Chocolate Distribution Problem
You are given an array/list CHOCOLATES
of size 'N', where each element represents the number of chocolates in a packet. Your task is to distribute these chocolates among 'M' stude...read more
Q39. Leaders in an Array Problem Statement
You are given a sequence of numbers. Your task is to find all leaders in this sequence. A leader is defined as an element that is strictly greater than all the elements to ...read more
Find all leaders in a sequence - elements greater than all elements to their right.
Iterate from right to left, keep track of maximum element encountered so far
If current element is greater than maximum, it is a leader
Return the leaders in the same order as the input sequence
Q40. Next Greater Element Problem Statement
You are provided with an array or list ARR
containing N
positive integers. Your task is to determine the Next Greater Element (NGE) for each element in the array.
The Next...read more
Find the Next Greater Element for each element in an array.
Iterate through the array from right to left
Use a stack to keep track of elements with no greater element to the right
Pop elements from the stack until finding a greater element or stack is empty
Number In Arithmetic Progression Problem
Given three integers X
, C
, and Y
, where X
is the first term of an arithmetic sequence with a common difference of C
, determine if Y
is part of this arithmetic sequence.
Check if a given number is part of an arithmetic sequence with a given first term and common difference.
Calculate the arithmetic sequence using the formula: nth term = X + (n-1) * C
Check if Y is equal to any term in the sequence to determine if it belongs to the sequence
Return 'True' if Y belongs to the sequence, otherwise return 'False'
Q42. There are N cities spread in the form of circle. There is road connectivity b/w city 1 and 2, then city 2 and 3 and so on till city n and 1. Each ith city has a petrol pump where you can pick pith petrol and di...
read moreQ43. Maximum Sum Path in a Binary Tree Problem Statement
You are provided with a binary tree consisting of N
nodes where each node has an integer value. The task is to determine the maximum sum achievable by a simpl...read more
Find the maximum sum achievable by a simple path between any two nodes in a binary tree.
Traverse the binary tree to find all possible paths and calculate their sums.
Keep track of the maximum sum encountered during traversal.
Consider paths that may include the same node twice.
Implement a recursive function to explore all possible paths.
Handle cases where nodes have negative values.
Q44. Populating Next Right Pointers in Each Node
Given a complete binary tree with 'N' nodes, your task is to determine the 'next' node immediately to the right in level order for each node in the given tree.
Input:...read more
Implement a function to update 'next' pointers in a complete binary tree.
Iterate level by level using a queue
Connect nodes at each level using 'next' pointers
Handle null nodes appropriately
Ensure the tree is a complete binary tree
Q45. Wildcard Pattern Matching Problem Statement
Implement a wildcard pattern matching algorithm to determine if a given wildcard pattern matches a text string completely.
The wildcard pattern may include the charac...read more
Implement a wildcard pattern matching algorithm to determine if a given wildcard pattern matches a text string completely.
Create a recursive function to match the pattern with the text character by character.
Handle cases for '?' and '*' characters separately.
Use dynamic programming to optimize the solution.
Check for edge cases like empty pattern or text.
Q46. Maximum Frequency Number Problem Statement
Given an array of integers with numbers in random order, write a program to find and return the number which appears the most frequently in the array.
If multiple elem...read more
Find the number with the maximum frequency in an array of integers.
Iterate through the array and keep track of the frequency of each number using a hashmap.
Find the number with the maximum frequency and return it.
If multiple elements have the same maximum frequency, return the one that appears first in the array.
Q47. Longest Zero Sum Subarray Problem
Given an array of integers consisting of both positive and negative numbers, find the length of the longest subarray whose sum is zero. This problem will be presented with mult...read more
Find the length of the longest subarray with zero sum in an array of integers.
Iterate through the array and keep track of the running sum using a hashmap.
If the running sum is seen before, it means there is a subarray with zero sum.
Calculate the length of the subarray with zero sum and update the maximum length found so far.
Q48. Detect and Remove Loop in Linked List
For a given singly linked list, identify if a loop exists and remove it, adjusting the linked list in place. Return the modified linked list.
Expected Complexity:
Aim for a...read more
Detect and remove loop in a singly linked list in place with O(n) time complexity and O(1) space complexity.
Use Floyd's Cycle Detection Algorithm to identify the loop in the linked list.
Once the loop is detected, use two pointers to find the start of the loop.
Adjust the pointers to remove the loop and return the modified linked list.
Q49. Given a program: int i; int main() { int j; int *k = (int *) malloc (sizeof(int)); … } Where are each of these variables stored?
i is stored in global data segment, j is stored in stack, k is stored in heap.
i is a global variable and is stored in the global data segment
j is a local variable and is stored in the stack
k is a pointer variable and is stored in the stack, while the memory it points to is allocated on the heap using malloc()
Q50. Rat In a Maze Problem Statement
Given a N * N
maze with a rat placed at position MAZE[0][0]
, find and print all possible paths for the rat to reach its destination at MAZE[N-1][N-1]
. The rat is allowed to move ...read more
Find all possible paths for a rat in a maze to reach its destination.
Implement a backtracking algorithm to explore all possible paths in the maze.
Keep track of the current path and mark visited cells to avoid loops.
Return the paths that lead from the start position to the destination.
Example: [[1, 0, 0], [1, 1, 0], [0, 1, 1]]
Q51. Min Jumps Problem Statement
In Ninja town, represented as an N * M
grid, people travel by jumping over buildings in the grid's cells. Santa is starting at cell (0, 0) and must deliver gifts to cell (N-1, M-1) o...read more
Santa needs to find the quickest path to deliver gifts in Ninja town by jumping over buildings with least travel time.
Santa can jump to (x+1, y+1), (x+1, y), or (x, y+1) from any cell (x, y) within grid boundaries.
The travel time between two buildings equals the absolute difference in their heights.
Find the shortest path from (0, 0) to (N-1, M-1) using dynamic programming or Dijkstra's algorithm.
Consider all possible paths and choose the one with the minimum total travel time...read more
Q52. Zigzag Binary Tree Traversal Problem Statement
Determine the zigzag level order traversal of a given binary tree's nodes. Zigzag traversal alternates the direction at each level, starting from left to right, th...read more
Zigzag level order traversal of a binary tree alternating direction at each level.
Use a queue to perform level order traversal of the binary tree.
Maintain a flag to alternate the direction of traversal at each level.
Store nodes at each level in separate lists and reverse the list if traversal direction is right to left.
Q53. Spiral Matrix Path Problem
You are provided with a two-dimensional array named MATRIX
of size N x M, consisting of integers. Your task is to return the elements of the matrix following a spiral order.
Input:
Th...read more
Implement a function to return elements of a matrix in spiral order.
Iterate through the matrix in a spiral order by adjusting the boundaries of rows and columns.
Keep track of the direction of traversal (right, down, left, up) to properly move through the matrix.
Handle edge cases such as when the matrix is empty or has only one row or column.
Q54. Cycle Detection in a Linked List
Determine if a given Singly Linked List of integers forms a cycle.
Explanation:
A cycle exists in a linked list if a node's next pointer points back to a previous node, creating...read more
Detect if a singly linked list forms a cycle by checking if a node's next pointer points back to a previous node.
Traverse the linked list using two pointers, one moving at double the speed of the other.
If the two pointers meet at any point, there is a cycle in the linked list.
Use Floyd's Cycle Detection Algorithm for efficient detection.
Example: Input: 3 2 0 -4 -1, 1 Output: true
Q55. Anagram Pairs Verification Problem
Your task is to determine if two given strings are anagrams of each other. Two strings are considered anagrams if you can rearrange the letters of one string to form the other...read more
Check if two strings are anagrams of each other by comparing the sorted characters.
Sort the characters of both strings and compare them.
Use a dictionary to count the occurrences of characters in each string.
Ensure both strings have the same length before proceeding.
Handle edge cases like empty strings or strings with different lengths.
Example: str1 = 'listen', str2 = 'silent' should return True.
Q56. Digit Count In Range Problem Statement
Given an integer K
, and two numbers A
and B
, count the occurrences of the digit K
in the range [A, B].
Include both the lower and upper limits in the count.
Input:
The fir...read more
Count occurrences of a digit in a given range.
Iterate through the range [A, B] and count occurrences of digit K.
Convert integers to strings for easier digit comparison.
Handle edge cases like when A or B is equal to K.
Q57. Rearrange The Array Problem Statement
You are given an array/list 'NUM' of integers. Rearrange the elements of 'NUM' such that no two adjacent elements are the same in the rearranged array.
Example:
Input:
NUM[...read more
The task is to rearrange an array such that no two adjacent elements are the same.
Iterate through the array and check if any adjacent elements are the same.
If adjacent elements are the same, swap one of them with a different element.
Return 'YES' if a valid rearrangement is possible, 'NO' otherwise.
Q58. Tree Symmetricity Problem Statement
You are provided with a binary tree structure, where each node consists of an integer value. Your task is to determine whether this binary tree is symmetric.
A symmetric tree...read more
Determine if a binary tree is symmetric by checking if its left and right subtrees are mirror images of each other.
Check if the left and right subtrees of the root node are mirror images of each other
Recursively check if the left subtree of the left child is a mirror image of the right subtree of the right child, and vice versa
Base case: If both nodes are null, return true; If one node is null and the other is not, return false
Example: For the input tree 1 2 2 3 4 4 3, the tr...read more
Q59. Predecessor and Successor in Binary Search Tree (BST)
Given a binary search tree (BST) with 'N' nodes, find the predecessor and successor of a given 'KEY' node in the BST.
Explanation:
The predecessor of a node...read more
Find predecessor and successor of a given node in a binary search tree (BST).
Predecessor is the node visited just before the given node in an inorder traversal.
Successor is the node visited immediately after the given node in an inorder traversal.
Return -1 if predecessor or successor does not exist.
Implement inorder traversal to find predecessor and successor.
Q60. Count Ways to Reach the N-th Stair Problem Statement
You are provided with a number of stairs, and initially, you are located at the 0th stair. You need to reach the Nth stair, and you can climb one or two step...read more
The problem involves counting the number of distinct ways to climb N stairs by taking 1 or 2 steps at a time.
Use dynamic programming to solve the problem efficiently.
The number of ways to reach the Nth stair is the sum of the number of ways to reach the (N-1)th stair and the (N-2)th stair.
Handle base cases for N=0 and N=1 separately.
Apply modulo operation to avoid overflow while calculating the result.
Consider using memoization to optimize the solution by storing intermediate...read more
Q61. Good Arrays Problem Statement
You are given an array 'A' of length 'N'. You must choose an element from any index in this array and delete it. After deleting the element, you will obtain a new array of length '...read more
Given an array, find the number of 'good' arrays that can be formed by deleting one element.
Iterate through each element in the array and check if deleting it results in a 'good' array
Keep track of the sum of elements at odd and even indices to determine if the array is 'good'
Return the count of 'good' arrays
Q62. Write a client server simple code. How will you handle multiple requests? Will increasing number of threads solve the problem. What should be the optimal number of threads depending upon your computer architect...
read moreClient-server code with optimal thread handling for multiple requests
Use a thread pool to handle multiple requests efficiently
Optimal number of threads depends on CPU cores and available memory
Increasing threads beyond optimal number can lead to resource contention and performance degradation
Q63. Binary Tree Mirror Conversion Problem
Given a binary tree, your task is to convert it into its mirror tree.
A binary tree is a data structure where each parent node has at most two children.
The mirror of a bin...read more
Convert a binary tree into its mirror tree by interchanging left and right children of non-leaf nodes.
Traverse the binary tree in a recursive manner.
Swap the left and right children of each non-leaf node.
Continue this process until all nodes are visited.
Output the inorder traversal of the mirror tree.
Q64. Find K'th Character of Decrypted String
You are given an encrypted string where repeated substrings are represented by the substring followed by its count. Your task is to find the K'th character of the decrypt...read more
Given an encrypted string with repeated substrings represented by counts, find the K'th character of the decrypted string.
Parse the encrypted string to extract substrings and their counts
Iterate through the decrypted string to find the K'th character
Handle cases where counts are more than one digit or in parts
Q65. Queue Using Stacks Problem Statement
Implement a queue data structure which adheres to the FIFO (First In First Out) principle, utilizing only stack data structures.
Explanation:
Complete predefined functions t...read more
Implement a queue using only stack data structures, supporting FIFO principle.
Use two stacks to simulate a queue: one for enqueueing and one for dequeueing.
For enQueue operation, push elements onto the enqueue stack.
For deQueue operation, if dequeue stack is empty, transfer elements from enqueue stack.
For peek operation, return top element of dequeue stack.
For isEmpty operation, check if both stacks are empty.
Q66. Stack using Two Queues Problem Statement
Develop a Stack Data Structure to store integer values using two Queues internally.
Your stack implementation should provide these public functions:
Explanation:
1. Cons...read more
Implement a stack using two queues to store integer values with specified functions.
Create a stack class with two queue data members.
Implement push, pop, top, size, and isEmpty functions.
Ensure proper handling of edge cases like empty stack.
Use queue operations like enqueue and dequeue to simulate stack behavior.
Maintain the size of the stack and check for emptiness.
Example: Push 42, pop to get 42, push 17, top to get 17.
Q67. Suppose there is an unsorted array. What will be the maximum window size, such that when u sort that window size, the whole array becomes sorted. Eg, 1 2 6 5 4 3 7 . Ans: 4 (6 5 4 3)
Find the maximum window size to sort an unsorted array.
Identify the longest decreasing subarray from the beginning and longest increasing subarray from the end
Find the minimum and maximum element in the identified subarrays
Expand the identified subarrays until all elements in the array are covered
The length of the expanded subarray is the maximum window size
Q68. Print Binary Tree Representation
Given a binary tree of integers, your task is to represent the binary tree in a 2-D array of strings with specific formatting rules.
Specifications:
- There should be ‘H’ number ...read more
The task is to represent a binary tree in a 2-D array of strings with specific formatting rules.
Create a 2-D array of strings with 'H' rows and odd number of columns.
Fill in the array based on the given binary tree, following the specified formatting rules.
Leave empty strings for unfilled cells and adjust spacing for empty subtrees.
Ensure the output matches the example provided in the question.
Q69. Ways to Reach Nth Stair
Given the number of stairs, initially at the 0th stair, you need to reach the Nth stair. Each time, you can either climb one step or two steps. Determine the number of distinct ways to c...read more
Calculate the number of distinct ways to climb N stairs by either taking one or two steps at a time.
Use dynamic programming to keep track of the number of ways to reach each stair
The number of ways to reach a stair is the sum of the number of ways to reach the previous two stairs
Return the result modulo 10^9+7
Q70. Level Order Traversal of Binary Tree
Given a binary tree of integers, return its level order traversal.
Input:
The first line contains an integer 'T' which represents the number of test cases. For each test cas...read more
Level Order Traversal of Binary Tree returns nodes in level order traversal.
Perform a level order traversal of the binary tree starting from the root node.
Visit nodes level by level, printing them in the order they are encountered.
Use a queue data structure to keep track of nodes at each level.
Q71. Top View of Binary Tree Problem Statement
Given a binary tree, your task is to print the Top View of the Binary Tree. The Top View is the set of nodes visible when the tree is viewed from the top. Please ensure...read more
The task is to print the Top View of a Binary Tree, which is the set of nodes visible when viewed from the top, in left to right order.
Traverse the binary tree in level order and maintain a map to store the horizontal distance of each node from the root.
For each node, if the horizontal distance is not already in the map, add the node's value to the result.
Print the values from the map in ascending order of horizontal distance to get the Top View of the Binary Tree.
Q72. Search In Rotated Sorted Array Problem Statement
Given a rotated sorted array ARR
of size 'N' and an integer 'K', determine the index at which 'K' is present in the array.
Note:
1. If 'K' is not present in ARR,...read more
Given a rotated sorted array, find the index of a given integer 'K'.
Perform binary search to find the pivot point where the array is rotated.
Based on the pivot point, apply binary search on the appropriate half of the array to find 'K'.
Handle cases where 'K' is not present in the array by returning -1.
Q73. K-Sum Path in a Binary Tree Problem Statement
You are presented with a binary tree where each node holds an integer, along with a specified number 'K'. The task is to identify and print every path that exists w...read more
The task is to identify and print every path in a binary tree whose node values sum up to a specified number 'K'.
Traverse the binary tree to find paths with sum equal to 'K'.
Print each valid path in the order encountered in the tree.
Handle cases where nodes may have missing children (-1).
Q74. Puzzle : There is a pond in which there is x kg ice on 1st November, it becomes 2x on 2nd November then 4x,8x,16x,32x and so on.Like this whole pond is filled with ice on last day i.e. 30th November. On which d...
read morePuzzle: On which day in November was the pond filled with half the ice?
The amount of ice in the pond doubles each day in November
The pond is filled with ice on the last day of November
To find the day when the pond was half-filled, work backwards from the last day
The Diamond Problem is a conflict that occurs when a class inherits from two classes that have a common base class.
The Diamond Problem arises in multiple inheritance.
It occurs when a class inherits from two classes that have a common base class.
This leads to ambiguity in accessing the common base class members.
To fix the Diamond Problem, virtual inheritance is used.
Virtual inheritance ensures that only one instance of the common base class is inherited.
Q76. Unbounded Knapsack Problem Statement
Given ‘N’ items, each with a specific profit and weight, and a knapsack with a weight capacity ‘W’. The objective is to fill the knapsack such that the total profit is maxim...read more
The Unbounded Knapsack Problem involves maximizing profit by filling a knapsack with items of specific profit and weight.
Iterate through each item and calculate the maximum profit that can be obtained by including or excluding the item in the knapsack.
Use dynamic programming to store and reuse subproblem solutions to optimize the solution.
The final answer will be the maximum profit that can be obtained by filling the knapsack with the given items.
Q77. Missing Numbers Problem Statement
You are provided with an array called ARR
, consisting of distinct positive integers. Your task is to identify all the numbers that fall within the range of the smallest and lar...read more
Identify missing numbers within the range of smallest and largest elements in an array.
Find the smallest and largest elements in the array.
Generate a list of numbers within this range.
Remove numbers that are present in the array.
Sort and return the missing numbers.
Q78. 33) You are given two hour glasses(those glasses are filled with sand). One hour glass gets emptied by 4 minutes another by 7 minutes. Find how will you calculate 9 minutes. Same puzzle was asked to me in GoldM...
read moreUsing two hour glasses, one emptied in 4 minutes and another in 7 minutes, calculate 9 minutes.
Start both hour glasses simultaneously
When the 4-minute hour glass is empty, flip it again
When the 7-minute hour glass is empty, 4 minutes have passed
Flip the 7-minute hour glass again and wait for it to empty
When it's empty, 9 minutes have passed
Q79. Linked List Merge Point Problem
You are given two singly linked lists and a third linked list, such that the two lists merge at some node of the third linked list. Determine the data value at the node where thi...read more
Given two linked lists that merge at some point, find the data value at the merging node.
Traverse both lists to find their lengths and the difference in lengths
Move the pointer of the longer list by the difference in lengths
Traverse both lists simultaneously until the nodes match to find the merging node
Q80. Find the Second Largest Element
Given an array or list of integers 'ARR', identify the second largest element in 'ARR'.
If a second largest element does not exist, return -1.
Example:
Input:
ARR = [2, 4, 5, 6, ...read more
Find the second largest element in an array of integers.
Iterate through the array to find the largest and second largest elements.
Handle cases where all elements are identical.
Return -1 if a second largest element does not exist.
Q81. How do you implement naming of threads from the point of view of a multi-threaded OS.Implement rand5 using rand7.Implement functions to render circles and other figures. (This was mainly about my development at...
read moreImplementing naming of threads in a multi-threaded OS and implementing rand5 using rand7
Use thread ID or thread name to name threads in a multi-threaded OS
Implement a function that generates a random number between 1 and 7
Use rejection sampling to implement rand5 using rand7
Ensure thread names are unique to avoid confusion
Test the implementation thoroughly to ensure correctness
Q82. Count Subarrays Problem
You are given an array or list consisting of 0s and 1s only. Your task is to find the sum of the number of subarrays that contain only 1s and the number of subarrays that contain only 0s...read more
Count the number of subarrays containing only 1s and 0s in a given array of 0s and 1s.
Iterate through the array and count consecutive 1s and 0s separately.
Use two variables to keep track of the count of 1s and 0s subarrays.
Add the counts of 1s and 0s subarrays to get the final result.
Virtual destructors in C++ are used to ensure that the correct destructor is called when deleting an object through a pointer to its base class.
Virtual destructors are declared in the base class and are used when deleting an object through a pointer to the base class.
They allow proper destruction of derived class objects.
Without virtual destructors, only the base class destructor would be called, leading to memory leaks and undefined behavior.
Virtual destructors are necessary...read more
Q84. Given a set of words one after another, give me a data structure so that you’ll know whether a word has appeared already or not
Use a hash table to store the words and check for existence in constant time.
Create a hash table with the words as keys and a boolean value as the value.
For each new word, check if it exists in the hash table. If it does, it has appeared before. If not, add it to the hash table.
Alternatively, use a set data structure to store only the unique words and check for existence in the set.
Q85. 26) There are m machines. each machine generates coins of 10 g.only one machine is defective which generates coins of 9 g.how to find that defective machine in one weighing only. Now there are two defective mac...
read moreQ86. How much memory is made available to a user program by the kernel, is there any limit to it? What is the range of addresses a user program can have at max, what determines it?What happens if excess memory is al...
read moreQ87. 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
The task is to 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.
Consider null nodes as well while traversing the tree.
To measure 45 minutes using two wires of different lengths that burn for one hour when ignited at both ends.
Ignite one end of the first wire and both ends of the second wire simultaneously.
After 30 minutes, the second wire will burn out completely.
At this point, ignite the other end of the first wire.
When the first wire burns out completely, 45 minutes will have passed.
Q89. 1>linked list node contain a string field and next.find if by concatenating all string fields the string formed is palindrome or not? 2-> merge to sorted array in which one arra is large enough to accomodate el...
read moreThe first question is about checking if a string formed by concatenating all string fields in a linked list is a palindrome or not.
Traverse the linked list and concatenate all string fields
Check if the concatenated string is a palindrome by comparing characters from both ends
Consider edge cases like empty linked list or single node with an empty string field
Semaphores are synchronization primitives used in operating systems to control access to shared resources.
Binary semaphore: Can take only two values, 0 and 1. Used for mutual exclusion.
Counting semaphore: Can take any non-negative integer value. Used for resource allocation.
Mutex semaphore: A binary semaphore used for mutual exclusion.
Named semaphore: A semaphore that can be accessed by multiple processes.
Unnamed semaphore: A semaphore that can only be accessed by threads wit...read more
Q91. What is merge sort and Quick sort. Adv and Disadv of each and which one would u use to sort huge list and Y
Merge sort and Quick sort are sorting algorithms used to sort arrays of data.
Merge sort is a divide and conquer algorithm that divides the input array into two halves, sorts each half recursively, and then merges the sorted halves.
Quick sort is also a divide and conquer algorithm that selects a pivot element and partitions the array around the pivot, sorting the two resulting sub-arrays recursively.
Merge sort has a time complexity of O(n log n) and is stable, but requires add...read more
Q92. Puzzle: There is a grid of soldier standing. Soldier ‘A’ is chosen: The tallest men from every column and the shortest among them. Soldier ‘B’ is chosen: The shortest men from every row and the tallest among th...
read moreComparison of heights of two soldiers chosen based on different criteria from a grid of soldiers.
Soldier A is chosen based on tallest men from every column and shortest among them.
Soldier B is chosen based on shortest men from every row and tallest among them.
The height of Soldier A and Soldier B cannot be determined without additional information about the grid of soldiers.
Q93. There is a paragraph having million characters. You have to find out the first non –repeating character in the complete paragraph. For example:- aab cld jb then answer should be :- c
Q94. Given a polygon (could be regular, irregular, convex, concave), find out whether a particular point lies inside it or outside it
To determine if a point is inside a polygon, use the ray casting algorithm.
Create a line from the point to a point outside the polygon
Count the number of times the line intersects with the polygon edges
If the count is odd, the point is inside the polygon; otherwise, it is outside
Q95. Write a function which returns 1 when 2 is passed and return 2 when 1 is passed.1 number is missing from an array(1 to n). find thatHe just wanted sum of n terms minus sum of array solution.Now correlate the ab...
read moreQ96. U have n vending machine out of which 1 is defected find the defected machine in O(1) on solving this he modified it give general solution for the case in which 2 machine are defected O(1) solution were require...
read moreTo find 2 defective vending machines out of n machines in O(1) time, label each machine with a unique number and use XOR operation.
Label each machine with a unique number from 1 to n
Calculate the XOR of all the numbers from 1 to n and the XOR of all the numbers of the working machines
The result of XORing these two values will give the XOR of the two defective machines
Find the rightmost set bit in the XOR result, divide the machines into two groups based on that bit, and XOR t...read more
Q97. How to find a loop in a Linked List and how to remove it
To find and remove a loop in a Linked List, we can use Floyd's Cycle Detection Algorithm.
Use two pointers, slow and fast, to detect if there is a loop in the Linked List
If the two pointers meet at some point, there is a loop
To remove the loop, set one of the pointers to the head of the Linked List and move both pointers one step at a time until they meet again
The meeting point is the start of the loop, set the next pointer of this node to NULL to remove the loop
Q98. Given an expression, remove unnecessary parenthesis. For example if (((a + b)) * c) is given make it (a + b) * c, as it evaluates in the same way without those parenthesis also
To remove unnecessary parenthesis from an expression, we need to apply a set of rules to identify and eliminate them.
Identify and remove parenthesis around single variables or constants
Identify and remove parenthesis around expressions with only one operator
Identify and remove parenthesis around expressions with operators of equal precedence
Identify and remove parenthesis around expressions with operators of different precedence
Apply the rules recursively until no more unnece...read more
Q99. 100 white eggs and 100 black eggs are distributed in 2 bags and now choosen a egg. The way to be distribute the eggs so that the probability of getting a black egg is maximum?
Distribute 50 white and 100 black eggs in one bag and 50 white and 0 black eggs in the other bag.
Distribute the black eggs in one bag and white eggs in the other bag
Ensure that both bags have equal number of white eggs
The bag with black eggs will have a higher probability of getting a black egg
Q100. Design a clock in which if you want to know about time in any region of this world, you can know .Hardware given is such that it has already built calculation device inside it. Long Discussion on various approa...
read moreDesign a clock to know time in any region of the world with built-in calculation device.
Create a clock with a world map and time zones marked on it.
Use the built-in calculation device to calculate the time difference between the user's location and the desired location.
Display the time in the desired location on the clock face.
Allow the user to input the desired location using a keypad or touchscreen.
Include a database of time zones and their offsets for accurate calculations...read more
More about working at Adobe
Top HR Questions asked in Tech Mahindra
Interview Process at Tech Mahindra
Top Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month