Add office photos
Engaged Employer

Amazon

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

300+ Mathatech Interview Questions and Answers

Updated 27 Dec 2024
Popular Designations

Q201. A person can take one or two steps at a time. Find the number of ways in which n steps can be travelled

Ans.

The number of ways to travel n steps by taking one or two steps at a time.

  • This is a classic problem that can be solved using dynamic programming.

  • The number of ways to travel n steps is equal to the sum of the number of ways to travel n-1 steps and n-2 steps.

  • Use an array to store the number of ways for each step, starting with base cases for 0 and 1 steps.

  • Iterate through the array to calculate the number of ways for each step up to n.

Add your answer

Q202. Find sum of all numbers that are formed from root to leaf path (code) expected time complexity O(n)

Ans.

The question asks to find the sum of all numbers formed from root to leaf path in a tree.

  • Traverse the tree using depth-first search (DFS)

  • At each node, calculate the number formed by concatenating the current number with the node's value

  • If the node is a leaf, add the formed number to the sum

  • Return the sum as the result

View 2 more answers

Q203. what is array and its implementation

Ans.

An array is a data structure that stores a collection of elements of the same type in contiguous memory locations.

  • Arrays have a fixed size determined at the time of declaration.

  • Elements in an array are accessed using an index starting from 0.

  • Example: string[] names = {"Alice", "Bob", "Charlie"};

View 7 more answers

Q204. Given a bst. Replace the value in each node with sum of all the nodes which have values greater than the node itself

Ans.

The given question asks to replace the value in each node of a binary search tree with the sum of all nodes greater than the current node.

  • Traverse the BST in reverse order (right, root, left)

  • Keep track of the sum of all greater nodes encountered so far

  • Update the value of each node with the sum and update the sum

Add your answer
Discover Mathatech interview dos and don'ts from real experiences

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

Ans.

Remove unnecessary parenthesis from an expression.

  • Identify the innermost expression enclosed in parenthesis.

  • Check if the parenthesis are necessary for evaluation.

  • If not, remove the parenthesis and repeat the process.

  • Stop when no more unnecessary parenthesis are found.

Add your answer
Q206. How would you design a system to create a clone of Facebook?
Ans.

Designing a system to create a clone of Facebook

  • Identify key features of Facebook such as user profiles, news feed, friend connections, messaging, etc.

  • Design database schema to store user data, posts, comments, likes, etc.

  • Implement user authentication and authorization mechanisms for security.

  • Develop front-end and back-end components using technologies like React, Node.js, and MongoDB.

  • Scale the system to handle millions of users by using load balancing, caching, and sharding....read more

Add your answer
Are these interview questions helpful?
Q207. How can you check if two strings are anagrams of each other?
Ans.

Check if two strings are anagrams by comparing the sorted versions of the strings.

  • Sort both strings and compare if they are equal.

  • Use a hashmap to store the frequency of characters in each string and compare the maps.

  • Ignore spaces and punctuation when comparing the strings.

Add your answer

Q208. Delete all nodes on a DLL whose data is a multiple of 5. O(n) time

Ans.

Delete nodes in a DLL with data multiple of 5 in O(n) time.

  • Traverse the DLL and check if the data is a multiple of 5.

  • If it is, delete the node and update the pointers of the previous and next nodes.

  • Continue traversing until the end of the DLL is reached.

  • Time complexity is O(n) as each node is visited only once.

Add your answer
Share interview questions and help millions of jobseekers šŸŒŸ

Q209. If a/b is recurring like 10/3 print 10/3 as 3.(3), 16/6 as 2.(6)

Ans.

Printing recurring decimals for a/b fractions.

  • Divide numerator by denominator and get quotient and remainder.

  • If remainder is 0, print quotient as it is.

  • If remainder is not 0, keep dividing remainder by denominator and print quotient as repeating decimal.

  • Enclose repeating decimal in parentheses.

Add your answer

Q210. Given a preorder of binary tree such that in tree each node have either 0 or no childern. and each leaf node is represented by N. construct a tree from this

Ans.

Given a preorder of binary tree with leaf nodes represented by N, construct the tree.

  • Start by creating an empty stack.

  • Iterate through the preorder list.

  • If the current element is N, create a leaf node and push it onto the stack.

  • If the current element is not N, create a new node and set its left child to the top of the stack.

  • Pop the top of the stack and set it as the right child of the new node.

  • Push the new node onto the stack.

  • Repeat until all elements in the preorder list are ...read more

Add your answer

Q211. Given a BST find the number of pair of nodes which sum upto a given value. O(n) time, O(1) space

Ans.

Find number of pairs of nodes in a BST that sum up to a given value in O(n) time and O(1) space.

  • Traverse the BST in-order and store the nodes in an array

  • Use two pointers approach to find pairs that sum up to the given value

  • Time complexity is O(n) and space complexity is O(1)

  • Example: BST with nodes 5, 3, 7, 2, 4, 6, 8 and target sum 10 has 2 pairs (2, 8) and (4, 6)

Add your answer

Q212. Given a 2D plane and n points, find the line which passes through maximum number of lines

Ans.

Find line passing through maximum number of points on a 2D plane

  • Use two nested loops to iterate over all pairs of points

  • Calculate the slope and y-intercept of the line passing through the pair of points

  • Store the line equation in a dictionary with the slope and y-intercept as keys

  • Count the number of times each line equation appears in the dictionary

  • Return the line equation with the highest count

Add your answer

Q213. Find the next larger element in a BST, given key might not be in the BST. O(logn) time and O(1) space

Ans.

Find next larger element in BST, given key might not be in BST. O(logn) time and O(1) space

  • Start at root node and traverse down the tree

  • If key is less than or equal to current node, go left

  • If key is greater than current node, go right and update successor

  • If right subtree exists, find the smallest element in it

  • If no right subtree, return successor

  • Time complexity is O(logn) and space complexity is O(1)

Add your answer

Q214. Inside a system with 4 gb ram OS only uses around 3.2 gb. Why is rest of the memory lying waste?

Ans.

The remaining memory is not wasted, but reserved for other system processes and applications.

  • The operating system reserves a portion of the RAM for its own processes and functions.

  • The unused memory can be used for caching data, improving system performance.

  • Applications and processes may not require the full amount of RAM at all times.

  • The unused memory can be allocated to other applications when needed.

  • Virtual memory and paging techniques allow the system to use disk space as ...read more

Add your answer

Q215. How to make a file mutually exclusive on a shared file system

Ans.

Use file locking mechanisms like flock or lockfile to make a file mutually exclusive on a shared file system.

  • Use flock or lockfile to acquire a lock on the file before accessing it.

  • Release the lock once the operation is complete.

  • Ensure all processes accessing the file use the same locking mechanism.

  • Example: flock /path/to/file -c 'command to execute'

  • Example: lockfile /path/to/file && command to execute && rm -f /path/to/file

Add your answer

Q216. given an array find the next minimum element in array for each element. for example if give array is 4,2,1,5,3 resultant array would be 2,1,-1,3,-1

Ans.

Given an array, find the next minimum element for each element.

  • Iterate through the array

  • For each element, compare it with the elements on its right

  • Find the minimum element greater than the current element

  • If no such element exists, assign -1

  • Build the resultant array

Add your answer

Q217. Replace every element in array with its closest maximum element in right. As amortized analysis was involved he asked for mathematical proof

Ans.

Replace every element in array with its closest maximum element in right.

  • Iterate through the array from right to left

  • Keep track of the maximum element seen so far

  • Replace each element with the maximum element seen so far

View 1 answer

Q218. Given an Infix expression, how to evaluate its answer

Ans.

Infix expression can be evaluated using the concept of operator precedence and associativity.

  • Convert the infix expression to postfix expression using stack data structure

  • Evaluate the postfix expression using stack data structure

  • Use operator precedence and associativity rules to determine the order of evaluation

  • Parentheses can be used to override the default order of evaluation

Add your answer

Q219. There is pointer of base class pointing to derived class. Explain the working with respect to the pointer, if this pointer calls the virtual function of base class

Ans.

Explaining working of pointer of base class pointing to derived class calling virtual function of base class

  • Pointer of base class can access only the members of base class

  • If base class has a virtual function, derived class's implementation will be called

  • This is known as runtime polymorphism

  • Example: Base class Animal with virtual function makeSound() and derived class Dog with implementation of makeSound()

  • If pointer of Animal class points to Dog object and makeSound() is calle...read more

Add your answer

Q220. Multiple requests for storing multiple files on a server. How to keep them mutually exclusive?

Ans.

Use file locking mechanism to ensure mutual exclusion.

  • Implement file locking mechanism to prevent simultaneous access to files.

  • Use semaphores or mutexes to ensure only one process can access a file at a time.

  • Implement a queue system to handle multiple requests and process them one by one.

  • Use transactional file systems to ensure atomicity of file operations.

  • Implement a timeout mechanism to prevent deadlocks.

  • Consider implementing a load balancer to distribute requests across mu...read more

Add your answer
Q221. What is the difference between Mutex and Semaphores? Please provide a real-life example.
Ans.

Mutex is used for exclusive access to a resource by only one thread at a time, while Semaphores can allow multiple threads to access a resource simultaneously.

  • Mutex is binary and allows only one thread to access a resource at a time, while Semaphores can have a count greater than one.

  • Mutex is used for protecting critical sections of code, while Semaphores can be used for controlling access to a pool of resources.

  • Example: Mutex can be used to control access to a shared variabl...read more

Add your answer

Q222. How to implement word suggestions like that in Eclipse

Ans.

Word suggestions in Eclipse can be implemented using algorithms like Trie or N-gram models.

  • Use Trie data structure to store the dictionary of words

  • Implement auto-complete feature using Trie

  • Use N-gram models to suggest words based on context

  • Train the N-gram model on a large corpus of text data

  • Combine both approaches for better accuracy

  • Consider user's typing speed and frequency of words for better suggestions

Add your answer

Q223. Given a linked list and some no n . you have to reverse the node of linked list in pair of n. consider all test cases for this

Ans.

Reverse the nodes of a linked list in pairs of n

  • Iterate through the linked list in pairs of n

  • Reverse the nodes within each pair

  • Connect the reversed pairs together

  • Handle cases where the number of nodes is not a multiple of n

Add your answer

Q224. Given a Integer, find the maximum number that can be formed from the digits. Input : 8754365 output : 8765543

Ans.

To find the maximum number that can be formed from the digits of an integer.

  • Convert the integer to a string

  • Sort the characters in descending order

  • Join the sorted characters to form the maximum number

Add your answer

Q225. Frog can jump 1 or 2 steps write the code to find out number of ways to go up to n steps. Discussed the complexity of it with mathematical proof

Ans.

The code finds the number of ways to reach n steps by jumping 1 or 2 steps at a time.

  • Use dynamic programming to solve the problem

  • Create an array to store the number of ways to reach each step

  • Initialize the array with base cases for 0 and 1 steps

  • Iterate through the array and calculate the number of ways for each step

  • Return the value at the last step

Add your answer

Q226. Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them. For example : ABC -> A BC, AB C, ABC, A B C

Ans.

Print all possible strings by placing spaces (zero or one) in between given string.

  • Use recursion to generate all possible combinations.

  • For each character, either include it with a space or without a space.

  • Stop recursion when all characters have been processed.

  • Print all generated combinations.

Add your answer

Q227. Given an array of integers, find the length of the longest consecutive sub array which forms an AP

Ans.

The length of the longest consecutive subarray forming an arithmetic progression in an array of integers.

  • Iterate through the array and keep track of the longest consecutive subarray forming an AP.

  • Use a hashmap to store the difference between each element and the previous element.

  • If the difference is the same as the previous difference, increment the length of the current subarray.

  • If the difference is different, update the length of the longest subarray and reset the current s...read more

Add your answer

Q228. Given a binary tree, build a doubly linked list for the leaves of the tree in the given order without using any extra space

Ans.

The question asks to convert the leaves of a binary tree into a doubly linked list without using extra space.

  • Traverse the binary tree in a depth-first manner

  • When a leaf node is encountered, update its left and right pointers to form the doubly linked list

  • Keep track of the previous leaf node to update its right pointer

  • Return the head of the doubly linked list

Add your answer

Q229. A stream of characters is coming, at any moment you have to tell ā€˜kā€™ elements closest to a given number (code)

Ans.

The code should find the 'k' elements closest to a given number from a stream of characters.

  • Use a priority queue to keep track of the 'k' closest elements.

  • For each character in the stream, calculate its distance from the given number and add it to the priority queue.

  • If the priority queue size exceeds 'k', remove the element with the maximum distance.

  • At any moment, the 'k' elements in the priority queue will be the closest to the given number.

Add your answer

Q230. Given a table m*n , find the number of ways of reaching from one corner to opposite corner, if a person can only move in two directions( towards the goal)

Ans.

Count number of ways to reach opposite corner of a m*n table moving in two directions only.

  • Use dynamic programming to solve the problem

  • The number of ways to reach a cell is the sum of the number of ways to reach the cell above it and the cell to the left of it

  • The number of ways to reach the opposite corner is the number of ways to reach the cell in the last row and last column

  • Example: For a 2*2 table, there are 2 ways to reach opposite corner

  • Example: For a 3*3 table, there ar...read more

Add your answer

Q231. Design data structure that supports insert(), remove(), find-max(), delete-max() operations. All operations should run in O(1) time. Lots of discussion was there, discussed many approaches

Ans.

Design a data structure with O(1) insert(), remove(), find-max(), delete-max() operations.

  • Use a doubly linked list to store the elements and a hash table to store the pointers to the nodes.

  • Keep track of the maximum element in a separate variable and update it on insert() and delete-max() operations.

  • For remove() operation, use the hash table to find the node and remove it from the linked list.

  • All operations should be implemented in constant time complexity O(1).

Add your answer

Q232. Reverse a binary search tree in such a manner so that parent child relationship maintained and left child become right child and vice versa

Ans.

Reverse a binary search tree while maintaining parent-child relationship.

  • Start by swapping the left and right child of each node recursively.

  • Use a depth-first search approach to traverse the tree.

  • Make sure to update the parent-child relationships accordingly.

Add your answer

Q233. how to check singly linked list is palindrome or not

Ans.

To check if a singly linked list is a palindrome, reverse the second half and compare it with the first half.

  • Traverse the linked list to find the middle node

  • Reverse the second half of the linked list

  • Compare the reversed second half with the first half to check for palindrome

Add your answer

Q234. How to identify that if a tree is a bst or not?

Ans.

To identify if a tree is a BST, check if the inorder traversal of the tree results in a sorted sequence.

  • Perform an inorder traversal of the tree

  • Check if the resulting sequence is sorted in ascending order

  • If yes, the tree is a BST; otherwise, it is not

Add your answer

Q235. There is a big file containing numbers and we have to sort all of them

Ans.

We can use any sorting algorithm like quicksort, mergesort, heapsort, etc.

  • Choose the appropriate sorting algorithm based on the size of the file and the range of numbers

  • Implement the chosen algorithm in the programming language of choice

  • Read the numbers from the file into an array or list

  • Apply the sorting algorithm to the array or list

  • Write the sorted numbers back to the file

Add your answer

Q236. Search an element in sorted rotated array.

Ans.

Search an element in sorted rotated array.

  • Use binary search to find the pivot point where the array is rotated.

  • Divide the array into two subarrays and perform binary search on the appropriate subarray.

  • Handle the cases where the target element is at the pivot point or not present in the array.

View 2 more answers

Q237. Given a sorted array(array can contain duplicates). Find the first occurance of given key elements in this array

Ans.

Find the first occurrence of a given key element in a sorted array with duplicates.

  • Use binary search to find the key element.

  • If the key element is found, check if it is the first occurrence by checking the previous element.

  • If the key element is not found, return -1.

Add your answer

Q238. What is hashing. Implement domain search using hashing

Ans.

Hashing is a technique to convert any data into a fixed size value. Domain search using hashing can be implemented using hash tables.

  • Hashing is used to index and retrieve items in a database

  • Hashing is used to encrypt passwords

  • Hash tables can be used to implement domain search using hashing

Add your answer

Q239. Given n-ary tree, print the nodes in level-order zig-zag manner. O(n) time

Ans.

Print nodes of n-ary tree in level-order zig-zag manner in O(n) time.

  • Use a queue to traverse the tree level by level.

  • For each level, alternate between printing nodes from left to right and right to left.

  • Push the children of each node into the queue for the next level.

  • Time complexity is O(n) as each node is visited once.

  • Example: For a tree with root node A and children B, C, and D, and B has children E and F, the output would be A C B D F E.

Add your answer

Q240. A stream of numbers are coming and I have to keep track of the kth largest number in it

Ans.

Keep track of kth largest number in a stream of numbers.

  • Use a min-heap of size k to keep track of kth largest number.

  • For each incoming number, compare it with the root of the heap.

  • If it is larger than the root, replace the root with the new number and heapify.

  • The root of the heap will always be the kth largest number.

Add your answer

Q241. Given an array of integers, find the maximum product which can be formed by three numbers

Ans.

Find the maximum product of three integers in an array.

  • Sort the array in descending order.

  • Check the product of the first three numbers and the product of the first and last two numbers.

  • Return the maximum product.

  • Handle negative numbers by checking the product of two smallest negative numbers and the largest positive number.

Add your answer
Q242. What is the running median of an input stream?
Ans.

Running median of an input stream is the median value of the numbers seen so far in a continuous stream of data.

  • Maintain two heaps - a max heap for the lower half of the numbers and a min heap for the upper half.

  • Keep the number of elements in the two heaps balanced or differ by at most 1.

  • If the total number of elements is odd, the median is the root of the max heap. If even, it is the average of the roots of the two heaps.

Add your answer

Q243. 2 coding questions ā€¢ Find the diameter of a tree ā€¢ Print all anagrams pair in separate line

Ans.

Answering 2 coding questions: finding the diameter of a tree and printing all anagram pairs.

  • To find the diameter of a tree, we can use DFS or BFS to traverse the tree and keep track of the maximum distance between any two nodes.

  • To print all anagram pairs, we can use a hash table to store the sorted version of each word and then iterate through the hash table to find pairs with the same sorted version.

  • Example for finding diameter of a tree: https://www.geeksforgeeks.org/diamet...read more

Add your answer

Q244. Given a single linked list of certain nodes. Switch adjacent nodes. Eg. 1 2 3 4 will be 2 1 4 3

Ans.

Switch adjacent nodes in a single linked list.

  • Traverse the linked list and swap adjacent nodes.

  • Keep track of previous node to update its next pointer.

  • Handle edge cases for first two nodes and last node.

  • Example: 1->2->3->4 becomes 2->1->4->3.

Add your answer
Q245. Implement a Trie data structure and write functions to insert and search for a few words in it.
Ans.

Implement a Trie data structure with insert and search functions.

  • Create a TrieNode class with children and isEndOfWord attributes.

  • Implement insert function to add words by iterating through characters.

  • Implement search function to check if a word exists by traversing the Trie.

  • Example: Insert 'apple', 'banana', 'orange' and search for 'apple' and 'grape'.

Add your answer

Q246. Design the most optimal data structure for storing a word and its meaning. Note that a word could have multiple meanings

Ans.

Optimal data structure for storing words and their meanings

  • Use a hash table with the word as the key and a list of meanings as the value

  • Each meaning can be stored as a string or an object with additional information

  • Consider using a trie data structure for efficient prefix search

  • Implement a search function that can handle partial matches and synonyms

Add your answer

Q247. Given an array, find the Next Greatest Element to the right for each element

Ans.

Find the Next Greatest Element to the right for each element in an array.

  • Iterate through the array from right to left

  • Use a stack to keep track of elements

  • Pop elements from stack until a greater element is found

  • If no greater element is found, assign -1

  • Reverse the result array

Add your answer

Q248. Design the most optimal data structure for a never ending stream of numbers. It should be optimized for insertion, deletion, searching, finding kth largest and kth smallest

Ans.

Design optimal data structure for never-ending stream of numbers for insertion, deletion, searching, kth largest and kth smallest.

  • Use a balanced binary search tree like AVL or Red-Black tree for efficient insertion, deletion, and searching.

  • Maintain two heaps, one for kth largest and one for kth smallest.

  • For finding kth largest, use a min heap of size k and for kth smallest, use a max heap of size k.

  • Alternatively, use a skip list or a hash table for constant time insertion and...read more

Add your answer

Q249. Given array of stock prices get the date of selling and buying so that profit is maximum

Ans.

Algorithm to find the best buying and selling dates for maximum profit from given stock prices array.

  • Iterate through the array and keep track of minimum price and maximum profit.

  • If current price is less than minimum price, update minimum price.

  • If current price minus minimum price is greater than maximum profit, update maximum profit and buying and selling dates.

  • Return buying and selling dates.

  • Example: [10, 7, 5, 8, 11, 9] => Buy on day 3 (price = 5) and sell on day 5 (price =...read more

Add your answer

Q250. Given a Binary Tree, if it is a BST or not

Ans.

Check if a Binary Tree is a Binary Search Tree (BST)

  • A BST has the property that all nodes in the left subtree of a node have values less than the node's value, and all nodes in the right subtree have values greater than the node's value

  • We can traverse the tree in-order and check if the resulting sequence is sorted

  • Alternatively, we can recursively check if each node satisfies the BST property

Add your answer

Q251. Insertion sort for a singly linked list.

Ans.

Insertion sort for a singly linked list.

  • Traverse the list and compare each node with the previous nodes

  • If the current node is smaller, swap it with the previous node

  • Repeat until the end of the list is reached

  • Time complexity is O(n^2)

View 1 answer

Q252. Take a infix expression as input and print its postfix expression

Ans.

Convert infix expression to postfix expression.

  • Use a stack to keep track of operators.

  • Iterate through the infix expression and push operands to output.

  • If an operator is encountered, pop operators from stack until a lower precedence operator is found.

  • Push the operator to stack.

  • After iterating, pop remaining operators from stack and append to output.

  • Reverse the output to get postfix expression.

Add your answer
Q253. What are the ACID properties in DBMS?
Ans.

ACID properties in DBMS ensure data integrity and consistency.

  • Atomicity: All operations in a transaction are treated as a single unit of work, either all succeed or all fail.

  • Consistency: Database remains in a consistent state before and after the transaction.

  • Isolation: Transactions are isolated from each other until they are completed.

  • Durability: Once a transaction is committed, the changes made by it are permanent and survive system failures.

  • Example: If a bank transfer trans...read more

Add your answer

Q254. find the median of input stream in minimum time complexcity.(Online algo)

Ans.

Find median of input stream in minimum time complexity using online algorithm.

  • Use two heaps, one max heap for elements smaller than current median and one min heap for elements greater than current median.

  • Maintain balance between the two heaps by ensuring that the size difference is at most 1.

  • If the size of both heaps is equal, median is the average of the top elements of both heaps. Else, median is the top element of the heap with larger size.

  • Time complexity: O(log n) for in...read more

Add your answer

Q255. Find the minimum and maximum element in stack in O(1)

Ans.

To find min and max element in stack in O(1), we can use an auxiliary stack.

  • Create an auxiliary stack to keep track of the minimum and maximum elements.

  • Push the first element to both the main and auxiliary stack.

  • For each subsequent element, compare it with the top element of the auxiliary stack and push the smaller element to the auxiliary stack.

  • To get the minimum element, simply return the top element of the auxiliary stack.

  • To get the maximum element, follow the same steps b...read more

Add your answer

Q256. Gievn a binary tree and return all root to leaf node pathss row,col and value

Ans.

Return all root to leaf node paths of a binary tree with row, col and value.

  • Traverse the binary tree recursively and keep track of the current path.

  • When a leaf node is reached, add the path to the result.

  • Include row, col and value of each node in the path.

  • Use a data structure like a list or array to store the paths.

  • Consider edge cases like empty tree or single node tree.

Add your answer

Q257. Implement Merge Sort.

Ans.

Merge Sort is a divide and conquer algorithm that sorts an array by dividing it into two halves, sorting them separately, and then merging the sorted halves.

  • Divide the array into two halves

  • Recursively sort the two halves

  • Merge the sorted halves

Add your answer

Q258. Explain working of DNS, implement domain search in DNS

Ans.

DNS translates domain names to IP addresses. Domain search is implemented using DNS recursive query.

  • DNS stands for Domain Name System

  • DNS translates domain names to IP addresses

  • Domain search is implemented using DNS recursive query

  • DNS resolver sends query to root server, then to TLD server, then to authoritative server

  • DNS cache is used to speed up the process

Add your answer

Q259. Clone a linked list having an arbit pointer

Ans.

Clone a linked list with an arbit pointer

  • Create a new node for each node in the original list

  • Store the mapping of original node to new node in a hash table

  • Set the next and arbit pointers of the new nodes based on the mapping

Add your answer

Q260. Write COMPLETE code for implementing a hash table?

Ans.

Implementing a hash table in code

  • Choose a hash function to map keys to indices in the table

  • Create an array to hold the values at each index

  • Handle collisions by using a collision resolution strategy

  • Implement methods for inserting, retrieving, and deleting values

  • Consider load factor and resizing the table if necessary

Add your answer

Q261. Check whether given link list represents palindrome

Ans.

Check if a given linked list is a palindrome.

  • Traverse the linked list and push each element onto a stack.

  • Traverse the linked list again and compare each element with the top of the stack.

  • If all elements match, the linked list is a palindrome.

  • Alternatively, reverse the linked list and compare it with the original linked list.

Add your answer

Q262. Reverse a linked list in group of n element.

Ans.

Reverse a linked list in groups of n elements.

  • Divide the linked list into groups of n elements.

  • Reverse each group individually.

  • Connect the reversed groups to form the final linked list.

  • Handle cases where the number of elements is not a multiple of n.

  • Example: 1->2->3->4->5->6->7->8, n=3 -> 3->2->1->6->5->4->8->7

Add your answer

Q263. Given a binary search tree. Traverse only the left sub-tree

Ans.

Traverse only the left sub-tree of a binary search tree.

  • Start at the root node

  • If the left child exists, visit it and repeat the process

  • If the left child does not exist, return to the parent node

  • Continue until all nodes in the left sub-tree have been visited

Add your answer

Q264. Find shortest path in an unweighted graph

Ans.

Shortest path in an unweighted graph

  • Use Breadth First Search (BFS) algorithm to find shortest path

  • Start from the source node and traverse the graph level by level

  • Keep track of visited nodes to avoid loops

  • Stop when the destination node is found

  • Return the path from source to destination using parent pointers

Add your answer

Q265. Convert a sorted array to balanced binary search tree

Ans.

Convert a sorted array to balanced binary search tree

  • Find the middle element of the array and make it the root of the tree

  • Recursively construct the left subtree using the left half of the array

  • Recursively construct the right subtree using the right half of the array

  • Repeat until all elements are added to the tree

Add your answer

Q266. Reverse a singly linked list in groups of k inĀ­place

Ans.

Reverse a singly linked list in groups of k inĀ­place

  • Divide the linked list into groups of k nodes

  • Reverse each group of k nodes

  • Connect the reversed groups to form the final linked list

Add your answer

Q267. Design the most optimal data structures for an LRU cache

Ans.

Design optimal data structures for LRU cache

  • Use a doubly linked list to keep track of recently used items

  • Use a hash table to store key-value pairs for quick access

  • When an item is accessed, move it to the front of the linked list

  • When the cache is full, remove the least recently used item from the back of the linked list and hash table

Add your answer

Q268. when will be the all the tomatoes be rotten in 2D grid

Ans.

The tomatoes will be rotten when all adjacent tomatoes are rotten as well.

  • Check each tomato in the grid and if it is rotten, check if all adjacent tomatoes are also rotten

  • Repeat this process until no more tomatoes can be marked as rotten

  • The process will continue until all tomatoes are rotten or no more tomatoes can be marked as rotten

Add your answer

Q269. What is the problem of identifying duplicates in an array?

Ans.

Identifying duplicates in an array involves finding and removing elements that appear more than once.

  • Iterate through the array and use a hash set to keep track of elements seen so far.

  • If an element is already in the hash set, it is a duplicate and can be removed.

  • Example: ['apple', 'banana', 'apple', 'orange'] - 'apple' is a duplicate.

  • Example: ['cat', 'dog', 'bird', 'cat'] - 'cat' is a duplicate.

Add your answer

Q270. Given integer n. Generate all possible paranthesis

Ans.

Generate all possible parentheses for a given integer n.

  • Use recursion to generate all possible combinations of parentheses.

  • Start with an empty string and keep adding opening and closing parentheses.

  • Keep track of the number of opening and closing parentheses used.

  • Stop recursion when the number of opening and closing parentheses reaches n.

  • Add the generated combination to the result array.

Add your answer

Q271. Advantages and disadvantages of amazon.com

Ans.

Amazon.com is an online retail giant with a vast selection of products and services.

  • Advantages: Wide selection of products, competitive pricing, fast shipping, convenient shopping experience

  • Disadvantages: Can put smaller retailers out of business, concerns over worker treatment and environmental impact

  • Example: Amazon Prime offers free two-day shipping and access to streaming services like Prime Video and Music

  • Example: Amazon's dominance in the e-book market has led to critici...read more

Add your answer

Q272. What do you mean by belady's anomaly??

Ans.

Belady's anomaly is a phenomenon in which increasing the number of frames in a page table may increase the number of page faults.

  • Belady's anomaly occurs when increasing the number of frames in a page table leads to more page faults.

  • It contradicts the common belief that more frames always lead to better performance.

  • This anomaly is more likely to occur in algorithms like FIFO (First In, First Out).

Add your answer

Q273. Write a recursive routine to calculate a ^ n

Ans.

A recursive routine to calculate a ^ n

  • The base case is when n is 0, in which case the result is 1

  • For any other value of n, the result is a multiplied by the result of a^(n-1)

  • The recursive function should call itself with a^(n-1) as the new input

Add your answer

Q274. Find next inorder predecessor in bst?

Ans.

The next inorder predecessor in a binary search tree (BST) is the node with the largest value smaller than the given node.

  • In a BST, the inorder predecessor of a node is the rightmost node in its left subtree.

  • If the left subtree of the given node is empty, then the inorder predecessor is the nearest ancestor whose right child is also an ancestor of the given node.

  • If there is no inorder predecessor (i.e., the given node is the smallest node in the BST), return null.

Add your answer

Q275. Kth largest element in an array.

Ans.

Find the Kth largest element in an array.

  • Sort the array in descending order and return the element at index K-1.

  • Use a max heap to find the Kth largest element efficiently.

  • Implement a quickselect algorithm to find the Kth largest element in linear time.

Add your answer

Q276. Preorder traversal without using recursion

Ans.

Preorder traversal without recursion is done using a stack to simulate the recursive function calls.

  • Create an empty stack and push the root node onto it

  • While the stack is not empty, pop a node from the stack and visit it

  • Push the right child of the popped node onto the stack

  • Push the left child of the popped node onto the stack

Add your answer

Q277. Explain caching, implement LRU caching

Ans.

Caching is the process of storing frequently used data in a temporary storage area for faster access. LRU caching removes the least recently used data when the cache is full.

  • Caching improves performance by reducing the time it takes to access data

  • LRU (Least Recently Used) caching algorithm removes the least recently used data when the cache is full

  • Implementing LRU caching involves using a doubly linked list and a hash map

  • When a cache hit occurs, the data is retrieved from the...read more

Add your answer

Q278. Explain working of virtual function

Ans.

Virtual functions are functions that can be overridden in derived classes and called through base class pointers.

  • Virtual functions are declared in base class with virtual keyword

  • Derived classes can override the virtual function with same signature

  • Virtual functions are called through base class pointers or references

  • Dynamic binding is used to determine which function to call at runtime

  • Virtual functions are used to achieve polymorphism

Add your answer

Q279. What is Dbms required??

Ans.

A Database Management System (DBMS) is required to manage and organize data efficiently in a structured manner.

  • DBMS is required to create, update, retrieve, and manage data in databases.

  • It provides a way to define, create, and manipulate databases.

  • DBMS ensures data integrity, security, and consistency.

  • Examples of popular DBMS include MySQL, Oracle, SQL Server, and PostgreSQL.

View 1 answer

Q280. Find median of an unsorted array. (code)

Ans.

Find median of an unsorted array.

  • Sort the array in ascending order

  • If the array has an odd length, the median is the middle element

  • If the array has an even length, the median is the average of the two middle elements

Add your answer

Q281. getMax() function for a stack in O(1)

Ans.

Use an auxiliary stack to keep track of the maximum element at each step.

  • Create an auxiliary stack to store the maximum element at each step.

  • When pushing an element onto the main stack, compare it with the top element of the auxiliary stack.

  • If the new element is greater, push it onto the auxiliary stack.

  • When popping an element from the main stack, also pop the top element from the auxiliary stack if they are equal.

  • To get the maximum element, simply return the top element of t...read more

Add your answer

Q282. Find path from one node to another in a binary tree

Ans.

Use depth-first search to find path from one node to another in a binary tree

  • Start from the root node and recursively search for the target node

  • Keep track of the path taken from the root to the current node

  • If the target node is found, return the path from the root to the target node

  • If the target node is not found, backtrack and continue searching in the other branches

Add your answer

Q283. Find loop in linked list. Proof of algo

Ans.

To find a loop in a linked list, we can use the Floyd's cycle-finding algorithm.

  • Initialize two pointers, slow and fast, both pointing to the head of the linked list.

  • Move slow pointer by one step and fast pointer by two steps at each iteration.

  • If there is a loop, the slow and fast pointers will eventually meet.

  • To prove the algorithm, we can use mathematical induction and the concept of tortoise and hare.

Add your answer

Q284. Implement AVL Tree.

Ans.

An AVL tree is a self-balancing binary search tree where the heights of the left and right subtrees differ by at most one.

  • AVL tree is a binary search tree with additional balance factor for each node.

  • The balance factor is the difference between the heights of the left and right subtrees.

  • Insertion and deletion operations in AVL tree maintain the balance factor to ensure the tree remains balanced.

  • Rotations are performed to balance the tree when necessary.

  • AVL trees provide effic...read more

Add your answer

Q285. getMax() function for a queue in O(1)

Ans.

Implement a getMax() function for a queue that returns the maximum element in O(1) time complexity.

  • Maintain a separate data structure (e.g., a max heap) to track the maximum element in the queue.

  • Whenever an element is enqueued, compare it with the current maximum and update if necessary.

  • When dequeuing, check if the dequeued element is the maximum and update the maximum if needed.

Add your answer
Q286. Design a URL shortening service.
Ans.

Design a URL shortening service

  • Generate a unique short code for each URL

  • Store the mapping of short code to original URL in a database

  • Redirect users from short URL to original URL

  • Consider implementing custom short domains for branding

  • Track analytics for shortened URLs

Add your answer

Q287. Difference between React class components and functional components?

Ans.

React class components are ES6 classes that extend React.Component, while functional components are simple functions that return JSX.

  • Class components use lifecycle methods like componentDidMount, componentDidUpdate, etc.

  • Functional components are simpler and easier to read/write.

  • Functional components can use React Hooks for state management and side effects.

  • Class components have a render method that returns JSX.

  • Functional components are stateless and do not have access to 'thi...read more

Add your answer

Q288. what type of problem needs dp to solve ?

Ans.

Dynamic programming is used to solve problems that can be broken down into overlapping subproblems and have optimal substructure.

  • DP is used for problems with optimal substructure, where the solution can be constructed from optimal solutions of its subproblems.

  • DP is used for problems with overlapping subproblems, where the same subproblems are solved multiple times.

  • Examples include Fibonacci sequence, shortest path problems, and knapsack problem.

Add your answer

Q289. Smallest path to reach from a to b point in matrix

Ans.

Use Dijkstra's algorithm to find the smallest path from point a to point b in a matrix.

  • Implement Dijkstra's algorithm to find the shortest path in a matrix

  • Create a matrix representation of the graph with weights on edges

  • Start from point a and explore all possible paths to reach point b

Add your answer

Q290. How would you solve?

Ans.

I would solve the problem by breaking it down into smaller tasks, analyzing requirements, designing a solution, coding, testing, and debugging.

  • Analyze requirements thoroughly before starting the development process

  • Break down the problem into smaller tasks to make it more manageable

  • Design a solution architecture that meets the requirements and is scalable

  • Code the solution using best practices and coding standards

  • Test the code thoroughly to ensure it works as expected

  • Debug any ...read more

Add your answer

Q291. Edit distance problem (DP)

Ans.

Edit distance problem is a dynamic programming problem to find the minimum number of operations required to transform one string into another.

  • The problem can be solved using dynamic programming approach

  • The solution involves filling up a matrix of size (m+1)x(n+1)

  • The matrix represents the minimum number of operations required to transform one string into another

  • The operations include insertion, deletion and substitution

  • The solution can be obtained from the bottom-right corner ...read more

Add your answer

Q292. lru cache using hashmap and doubly linked list

Ans.

LRU cache can be implemented using a hashmap to store key-value pairs and a doubly linked list to keep track of the most recently used items.

  • Use a hashmap to store key-value pairs for quick access to values

  • Use a doubly linked list to keep track of the order of items based on their usage

  • When a new item is accessed, move it to the front of the linked list and update the hashmap accordingly

  • When the cache is full, remove the least recently used item from the end of the linked lis...read more

Add your answer

Q293. Spiral order traversal of bt

Ans.

Spiral order traversal of a binary tree

  • Use a stack and a queue to traverse the binary tree in a spiral order

  • Start with the root node and add it to the stack

  • While the stack is not empty, pop a node from the stack and add its children to the queue

  • If the stack is empty, swap the stack and queue

  • Repeat until both stack and queue are empty

Add your answer

Q294. Median of two sorted array.

Ans.

Find the median of two sorted arrays.

  • Merge the two arrays into one sorted array and find the median.

  • Use binary search to find the median in O(log(min(m, n))) time complexity.

  • Handle edge cases like empty arrays or arrays of different lengths.

Add your answer

Q295. what is bfs and dfs ?

Ans.

BFS (Breadth First Search) and DFS (Depth First Search) are algorithms used for traversing or searching tree or graph data structures.

  • BFS explores all the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.

  • DFS explores as far as possible along each branch before backtracking.

  • BFS uses a queue data structure while DFS uses a stack or recursion.

  • Example: BFS can be used to find the shortest path in an unweighted graph, while DFS can be use...read more

Add your answer

Q296. Implement queue using stacks

Ans.

Queue can be implemented using two stacks by maintaining the order of elements.

  • Use two stacks, one for enqueue operation and one for dequeue operation

  • When enqueue is called, push the element onto the enqueue stack

  • When dequeue is called, if the dequeue stack is empty, transfer all elements from enqueue stack to dequeue stack

  • Pop the top element from the dequeue stack and return it as the dequeued element

Add your answer

Q297. Explain the approach for coding questions

Ans.

Approach for coding questions involves understanding the problem, designing a solution, coding, testing, and optimizing.

  • Understand the problem statement thoroughly before starting to code.

  • Design an algorithm or approach to solve the problem.

  • Write clean and efficient code to implement the solution.

  • Test the code with sample inputs to ensure correctness.

  • Optimize the code for better performance if needed.

Add your answer

Q298. High level DSA with pattern problem

Ans.

High level DSA with pattern problem involves solving complex data structures and algorithms with a focus on identifying patterns.

  • Identify the problem constraints and requirements

  • Analyze the problem to determine the appropriate data structures and algorithms to use

  • Implement the solution by following the identified pattern

  • Test and optimize the solution for efficiency

Add your answer

Q299. Why Os is required??

Ans.

Operating system (OS) is required to manage hardware resources, provide user interface, and run applications efficiently.

  • Manages hardware resources such as CPU, memory, and storage

  • Provides user interface for users to interact with the computer

  • Runs applications and manages processes efficiently

  • Ensures security and protection of data

  • Facilitates communication between hardware and software components

Add your answer

Q300. Least Common Ancestor of binary tree

Ans.

The least common ancestor of a binary tree is the node that is the lowest common ancestor of two given nodes in the tree.

  • Start from the root node and recursively search for the given nodes in the left and right subtrees.

  • If one node is found in the left subtree and the other in the right subtree, then the current node is the least common ancestor.

  • If both nodes are found in the left subtree, then the least common ancestor is in the left subtree, and vice versa.

  • If one of the nod...read more

Add your answer
1
2
3
4

More about working at Amazon

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

Interview Process at Mathatech

based on 119 interviews
5 Interview rounds
Coding Test Round - 1
Coding Test Round - 2
Video Call Round - 1
Video Call Round - 2
Video Call Round - 3
View more
Interview Tips & Stories
Ace your next interview with expert advice and inspiring stories

Top Software Developer Interview Questions from Similar Companies

3.7
Ā ā€¢Ā 107 Interview Questions
3.8
Ā ā€¢Ā 40 Interview Questions
4.0
Ā ā€¢Ā 35 Interview Questions
3.7
Ā ā€¢Ā 33 Interview Questions
3.6
Ā ā€¢Ā 14 Interview Questions
3.5
Ā ā€¢Ā 11 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
75 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