Q. Connect nodes at the same level in a binary tree
asked 8xmediumTreesGroup discussion, Online test, Technical2015-2019
Ans. Use level order traversal with a queue, linking each node to the next node removed from the same level. For each level, process exactly its current queue size, keep a previous pointer, set previous.next to current, and set the last node’s next to null. Time is O(n), space is O(width).
Q. What is the difference between a process and a thread?
asked 8xeasyOperating systemsTechnical2016-2021
Ans. A process is an independent running program with its own memory space, while a thread is a smaller unit of execution within a process that shares that process’s memory. Processes are more isolated and cost more to create or switch between. Threads are lighter, but shared memory makes synchronisation and race conditions important.
Q. Reverse a linked list in groups of size k.
asked 7xmediumLinked listsOnline test, Technical2015-2020
Ans. Reverse each block of k nodes by rewiring next pointers, then connect the previous block’s tail to the new head of the reversed block. Use three pointers to reverse a block in place, and first check that k nodes remain if partial groups should stay unchanged. Time complexity is O(n), space complexity is O(1).
Q. Find the longest palindromic substring in a given string
asked 5xmediumStringsOnline test, Technical2016-2020
Ans. Use expand around centres: for each index, expand once for an odd-length palindrome and once between indices for an even-length palindrome, tracking the best start and length. The key detail is handling both centre types. This uses only a few variables, runs in O(n squared) time, and uses O(1) extra space.
Q. Find the maximum subarray sum using Kadane’s Algorithm.
asked 5xeasyArraysOnline test, Technical2017-2023
Ans. Use Kadane’s Algorithm by scanning the array once, keeping the best sum ending at the current index and the best sum seen overall. At each element, either extend the current subarray or start a new one there. It uses only variables, runs in O(n) time, and O(1) space.
Q. Print a given matrix in spiral order.
asked 4xmediumArraysTechnical2017-2023
Ans. Traverse the matrix layer by layer using four boundaries: top, bottom, left, and right. Print the top row, right column, bottom row, and left column, then move the boundaries inward. No extra data structure is needed apart from the output. Time complexity is O(mn), and space is O(1).
Q. Find the maximum product subarray in a given array.
asked 4xmediumArraysOnline test, Technical2015-2017
Ans. Use a single pass dynamic approach, keeping the maximum and minimum product ending at each position. The key detail is that a negative number can turn the minimum product into the maximum, so update both values for every element. Track the best maximum seen overall. This runs in O(n) time and O(1) space.
Q. Find the majority element in an array
asked 3xmediumArraysTechnical2015-2019
Ans. Use the Boyer Moore voting algorithm to find the majority element in one pass. Keep a candidate and a count: set the candidate when count is zero, increment for matches, decrement otherwise. If a majority is not guaranteed, verify the candidate with a second pass. Time is O(n), space is O(1).
Q. Detect and remove a loop in a linked list.
asked 3xmediumLinked listsTechnical2015-2023
Ans. Use Floyd’s slow and fast pointer method to detect the loop, then remove it by finding the node where the cycle starts and setting the previous node’s next pointer to null. After slow and fast meet, move one pointer to head and advance both one step at a time. Time is O(n), space is O(1).
Q. Find the Lowest Common Ancestor (LCA) in a Binary Tree
asked 3xmediumTreesTechnical2016-2021
Ans. Use a recursive DFS: if the current node is null, p, or q, return it. Recurse into left and right. If both sides return non-null, the current node is the LCA. Otherwise return the non-null side. This uses the call stack and runs in O(n) time, with O(h) space.
Q. Find the Longest Increasing Subsequence (LIS) in an array.
asked 3xmediumDynamic programmingOnline test, Technical2017
Ans. Use the patience sorting approach: maintain an array where each position stores the smallest possible tail value for an increasing subsequence of that length. For each number, binary search the first tail greater than or equal to it and replace it. This gives the LIS length in O(n log n) time and O(n) space.
Q. Check whether a given binary tree is a Binary Search Tree (BST).
asked 3xmediumTreesTechnical2017-2020
Ans. Check it by traversing the tree recursively with an allowed value range for each node. The root can have an infinite range; the left child must be less than the node, and the right child greater. Use the call stack as the data structure. Time complexity is O(n), space is O(h).
Q. Find the Lowest Common Ancestor (LCA) of two nodes in a Binary Tree
asked 3xmediumTreesOnline test, Technical2017-2020
Ans. Use a recursive depth first search: if the current root is null or equals either target node, return it. Search left and right subtrees. If both return non-null, the current root is the LCA; otherwise return the non-null side. This uses the call stack, with linear time and tree-height space.
Q. Find the length of the longest substring without repeating characters.
asked 3xmediumStringsTechnical2015-2025
Ans. Use a sliding window and a hash map of each character’s most recent index to find the longest substring without repeats. Move the right pointer through the string; if a character was seen inside the current window, move the left pointer just after its previous index. Track the maximum window length. Time is O(n), space is O(k).
Q. Find the minimum number of adjacent swaps required to make a given string a palindrome.
asked 3xmediumStringsOnline test2019-2024
Ans. Use a greedy two pointer method after checking that at most one character has an odd frequency; otherwise it is impossible. Match the left character with the nearest same character from the right, then bubble it to the right position using adjacent swaps. If no match exists, move it one step towards the centre. Time is O(n²).
Q. Clone a linked list with next and random pointer
asked 3xhardLinked listsTechnical2015-2019
Ans. Clone it by first creating a copy node for every original node, storing original to copy in a hash map, then set each copy’s next and random using that map. The key detail is to create all nodes before wiring random pointers. This takes O(n) time and O(n) extra space.
Q. Add 1 to a number represented as a linked list
asked 3xeasyLinked listsTechnical2017-2023
Ans. Reverse the linked list, add 1 with carry from the least significant digit, then reverse it back. Traverse nodes, updating each digit and propagating carry while it is 1. If carry remains after the last node, append a new node with digit 1. This uses the list itself, runs in O(n) time and O(1) extra space.
Q. Perform level order traversal of a binary tree
asked 3xeasyTreesTechnical2019-2021
Ans. Use breadth first search with a queue. Put the root in the queue, then repeatedly remove the front node, visit it, and add its left and right children if they exist. This visits nodes level by level from left to right. The time complexity is O(n), and the space complexity is O(w), where w is the maximum width.
Q. Explain the difference between mutex and semaphore
asked 3xeasyOperating systemsTechnical2017-2021
Ans. A mutex is a lock for exclusive access by one thread, while a semaphore is a counter that allows a fixed number of threads to access a resource. The key difference is ownership: the thread that locks a mutex should unlock it, but a semaphore can be signalled by another thread.
Q. Perform inorder traversal of a binary tree without using recursion.
asked 3xeasyTreesTechnical2016-2019
Ans. Use an explicit stack to simulate the recursive calls. Start at the root, push nodes while moving left, then pop the top node, visit it, and move to its right child. Repeat until both the current node is null and the stack is empty. Time complexity is O(n), space is O(h).
Q. Design and implement an LRU cache
asked 2xmediumCacheTechnical2015-2017
Ans. Implement an LRU cache with a hash map from key to list node and a doubly linked list ordered by recent use. On get, return the value and move the node to the front. On put, update or insert at the front. If capacity is exceeded, remove the tail. Both operations are O(1).
Q. Why would you choose NoSQL over RDBMS?
asked 2xmediumDBMSManagerial, Technical2019
Ans. I would choose NoSQL over an RDBMS when the data is large scale, fast changing, semi-structured, or needs horizontal scaling. The key trade-off is that NoSQL often relaxes strict relational modelling and joins to gain flexibility, high write throughput, distributed storage, and easier schema evolution.
Q. Reverse every k nodes in a linked list.
asked 2xmediumLinked listsTechnical2017
Ans. Reverse the linked list in groups of k by first checking that k nodes exist, then reversing only that block. Use a dummy head and three pointers: previous group tail, current node, and next node. After each reversal, reconnect the reversed block to the list. Leave fewer than k remaining nodes unchanged. Time is O(n), space is O(1).
Q. Implement a thread-safe Singleton class.
asked 2xmediumOOPManagerial, Technical2016-2024
Ans. Use an eager static instance or a lazy holder pattern, where the class keeps one private static instance and exposes it through a public accessor. The constructor is private to stop external creation. Class loading gives thread safety without explicit locking. Access is constant time, and the only storage is one object reference.
Q. Longest Palindromic Subsequence in a string
asked 2xmediumDynamic programmingOnline test, Technical2018-2020
Ans. Use dynamic programming where dp[i][j] stores the length of the longest palindromic subsequence inside s[i..j]. If s[i] equals s[j], set it to 2 plus dp[i+1][j-1], otherwise take the maximum of excluding either end. Fill by increasing substring length. Time is O(n²), space is O(n²).
Q. Explain how Garbage Collection works in Java
asked 2xmediumOOPTechnical2017-2019
Ans. Garbage Collection in Java automatically reclaims heap memory used by objects that are no longer reachable from live references. The collector starts from GC roots such as stack variables, static fields and active threads, marks reachable objects, then frees or compacts the rest. Most collectors are generational, because short-lived objects are common.
Q. Reverse a linked list in groups of given size
asked 2xmediumLinked listsOnline test2015-2020
Ans. Reverse each group of k nodes by iterating through the list and reversing pointers within the current group, then connect the previous group’s tail to the new head. Use only node pointers, not an extra data structure. If fewer than k nodes remain, usually leave them unchanged. Time complexity is O(n), space is O(1).
Q. Find the median in a running stream of numbers
asked 2xmediumHeapsTechnical2017-2020
Ans. Use two heaps: a max heap for the lower half and a min heap for the upper half. Insert each number into the correct heap, then rebalance so their sizes differ by at most one. The median is the larger heap’s top, or the average of both tops. Insertion is O(log n), median lookup is O(1).
Q. Search an element in a sorted and rotated array
asked 2xmediumBinary searchTechnical2015-2019
Ans. Use a modified binary search: compare the middle element with the ends to decide which half is sorted, then check whether the target lies inside that sorted half. If it does, search there, otherwise search the other half. For distinct elements, this takes O(log n) time and O(1) space.
Q. Explain React virtualization and why it is needed
asked 2xmediumFrontendSystem design2024
Ans. React virtualization renders only the visible part of a large list or grid, plus a small buffer, instead of rendering every item in the DOM. It is needed because thousands of DOM nodes make rendering, scrolling, layout and memory usage slow. Libraries such as react-window calculate which items to show from scroll position.
Q. Find the longest increasing subsequence in an array
asked 2xmediumDynamic programmingOnline test, Technical2016-2017
Ans. Use a patience sorting approach: maintain an array tails, where tails[i] is the smallest possible tail value of an increasing subsequence of length i + 1. For each number, binary search its position in tails and replace or append it. The length of tails is the LIS length. Time complexity is O(n log n).
Q. Group all anagrams together from a list of strings.
asked 2xmediumStringsTechnical2020
Ans. Use a hash map where the key is a canonical form of each string and the value is the list of words matching that key. For each word, sort its characters to form the key, then append the word to that group. Time complexity is O(n k log k), where k is word length.
Q. Connect all nodes at the same level in a binary tree
asked 2xmediumTreesTechnical2017
Ans. Use level order traversal with a queue, and link each node to the next node removed from the same level. Track the number of nodes in the current level, keep a previous pointer, and set the last node’s next pointer to null. This takes O(n) time and O(w) space, where w is tree width.
Q. Convert an infix expression to a postfix expression.
asked 2xmediumStackOnline test2020
Ans. Use a stack to convert infix to postfix by scanning the expression left to right and outputting operands immediately. Push opening brackets, pop until an opening bracket on closing brackets, and for operators pop higher or equal precedence operators before pushing the current one. Finally pop remaining operators. This runs in O(n) time.
Q. Find the kth largest element in a Binary Search Tree.
asked 2xmediumTreesTechnical2018-2021
Ans. Use reverse inorder traversal, visiting right, node, then left, and count visited nodes until the count reaches k. The kth visited node is the kth largest because BST inorder order is sorted. Use recursion or an explicit stack. Time is O(h + k) on average, O(n) worst case, with O(h) space.
Q. Swap two nodes in a doubly linked list using a hashmap.
asked 2xmediumLinked listsTechnical2016
Ans. Build a hashmap from node value or id to node reference, find the two nodes in O(1), then swap the nodes by updating their prev and next links. Handle adjacent nodes and head or tail changes carefully. Building the map takes O(n) time and O(n) space; the swap is O(1).
Q. Design and implement an LRU (Least Recently Used) Cache.
asked 2xmediumDesignSystem design, Technical2017-2020
Ans. Use a hash map plus a doubly linked list to implement an LRU cache. The map gives O(1) access from key to node, and the list keeps usage order. On get or put, move the node to the front. When capacity is exceeded, remove the tail in O(1).
Q. Find the number of islands in a binary matrix using DFS.
asked 2xmediumGraphsTechnical2020-2021
Ans. Scan every cell, and when you find an unvisited 1, count one island and run DFS to mark all connected 1s. The DFS explores up, down, left and right using recursion or a stack, with a visited matrix or by changing 1 to 0. Time is O(rows × cols), space is O(rows × cols).
Q. How would you handle very large data in a single reducer?
asked 2xmediumDistributed systemsTechnical2016
Ans. I would avoid forcing very large data through one reducer by repartitioning the key space or using a two-stage aggregation. The key detail is to reduce data before the final reducer, using combiners or partial reducers, so the last step only merges compact intermediate results rather than processing all raw records.
Q. Explain the concept of Virtual Memory in Operating Systems
asked 2xmediumOperating systemsTechnical2023
Ans. Virtual memory is a memory management technique where the operating system gives each process the illusion of a large, continuous private address space. It maps virtual addresses to physical RAM using page tables, and can store inactive pages on disk. The key benefit is isolation, efficient RAM use, and support for programs larger than physical memory.
Q. Construct a Binary Search Tree from its preorder traversal.
asked 2xmediumTreesTechnical2017-2022
Ans. Build it by scanning preorder once and inserting each value into the valid BST range using recursion. Keep a shared index and pass lower and upper bounds for each subtree; if the next value is outside the range, return null. This uses the call stack as the data structure and runs in O(n) time.
Q. How would you implement an LRU (Least Recently Used) cache?
asked 2xmediumData structuresTechnical2016-2017
Ans. Implement it with a hash map plus a doubly linked list. The map stores keys to list nodes, and the list keeps usage order, with most recently used at the front and least recently used at the back. On get or put, move the node to the front. When full, remove the tail. All operations are O(1).
Q. Design and implement an LRU Cache with optimal time complexity.
asked 2xmediumDesignTechnical2016
Ans. Use a hash map plus a doubly linked list to implement an LRU cache in O(1) get and put time. The map stores key to node, and the list stores usage order. On get, move the node to the front. On put, update or insert, and evict the tail if capacity is exceeded.
Q. Given an array, find the maximum j - i such that arr[j] > arr[i]
asked 2xmediumArraysOnline test2015-2017
Ans. Use prefix minima and suffix maxima, then scan with two pointers to find the farthest valid pair. Build leftMin[i] as the minimum value up to i and rightMax[j] as the maximum value from j to the end. If rightMax[j] > leftMin[i], update the answer and move j; otherwise move i. Time is O(n), space is O(n).
Q. Rotate a square matrix (image) by 90 degrees clockwise in-place.
asked 2xmediumArraysTechnical2016
Ans. Transpose the matrix in-place, then reverse each row in-place. Transposing swaps matrix[i][j] with matrix[j][i] across the main diagonal, and reversing each row moves columns into their clockwise rotated positions. This uses the matrix itself as the data structure, takes O(n²) time, and uses O(1) extra space.
Q. Find the least common ancestor (LCA) of two nodes in a binary tree
asked 2xmediumTreesTechnical2016
Ans. Use a recursive DFS: if the current node is null, return null; if it is one of the target nodes, return it. Recurse into left and right subtrees. If both sides return non-null, the current node is the LCA; otherwise return the non-null side. Time is O(n), space is O(h).
Q. Find all nodes at distance K from a given leaf node in a binary tree
asked 2xmediumTreesOnline test, Technical2015-2021
Ans. Build parent pointers with one DFS, then run BFS from the given leaf treating left, right and parent as neighbours; print nodes reached at level K. Use a queue and a visited set to avoid going back and forth. This takes O(n) time and O(n) extra space.
Q. Print the boundary traversal of a binary tree in clockwise direction.
asked 2xmediumTreesTechnical2016
Ans. Print root, then the right boundary top down excluding leaves, then all leaf nodes from right to left, then the left boundary bottom up excluding leaves. Use simple tree traversals: prefer right child on the right boundary, left child on the left boundary. Time is O(n), with O(h) recursion space.
Q. Find the point of intersection of two line segments given their endpoints.
asked 2xmediumGeometryTechnical2016
Ans. Compute the intersection by solving the two parametric segment equations, then check that both parameters lie between 0 and 1. Write each segment as p + t r and q + u s. If cross(r, s) is zero, handle parallel or collinear overlap separately. Otherwise, the point is p + t r. Time is O(1).
Q. Rearrange characters in a string such that no two adjacent characters are the same
asked 2xmediumGreedyTechnical2020-2021
Ans. Use a greedy max heap of character frequencies: repeatedly take the two most frequent remaining characters, append both, decrement their counts, and push back any still left. This avoids placing equal characters together. The key feasibility check is that no character may appear more than (n + 1) / 2 times. Time is O(n log k).
Q. Design the newsfeed system of Facebook.
asked 2xhardScalabilityTechnical2017
Ans. Use a hybrid fanout design: precompute feeds for normal users, but fetch and rank posts from celebrities or high fanout accounts at read time. Store posts, friendships, and per-user feed entries separately. A ranking service scores candidates by relevance, freshness, and engagement. Use caches, queues, sharding, deduplication, and eventual consistency for scale.
Q. Given two numbers n and m, find the number closest to n that is divisible by m.
asked 2xeasyLogical reasoningOnline test2017
Ans. Find the two nearest multiples of m around n. Compute q = n divided by m, then take lower = m × floor(q) and upper = m × ceil(q). Compare n - lower with upper - n. The smaller difference gives the answer. If they are equal, use the rule stated in the question, often the larger multiple.
Q. How do you prioritize tasks and manage your time effectively?
asked 2xunknownTime managementHR2023-2024
Ans. Choose a real situation with competing deadlines, changing priorities, and clear consequences. Emphasise how you assessed urgency and impact, clarified expectations, planned focused work, communicated trade-offs, and adjusted when needed. Interviewers listen for structure, judgement, reliability, stakeholder awareness, and evidence that you deliver important work without becoming reactive.
Q. Tell me about a time when you faced a conflict within a team and how you resolved it.
asked 2xunknownConflict resolutionHR2023-2024
Ans. Pick a real conflict where you had a clear role in improving the outcome, not just blaming others. Emphasise listening, understanding each person’s priorities, staying calm, and moving the team towards a decision. Interviewers listen for maturity, accountability, communication, and evidence that the relationship and result both improved.
Q. Three Ants and Triangle Problem
asked 1xmediumProbabilityTechnical2017
Ans. Each ant has two choices, clockwise or anticlockwise, so there are 2³ = 8 equally likely direction combinations. They avoid collision only if all three choose the same direction, giving 2 safe cases. Therefore the probability of no collision is 2/8 = 1/4, and the probability of collision is 3/4.
Q. Can India go completely cashless?
asked 1xmediumVerbalGroup discussion2024
Ans. A strong answer should take a balanced view: India can become far more digital, but not completely cashless soon. Use examples like UPI growth, rural access, small merchants, trust, internet reliability and financial literacy. Emphasise inclusion, infrastructure and behaviour change. Interviewers listen for practicality, awareness of India’s diversity and avoidance of extreme claims.
Q. Prove that the number between twin primes is divisible by 6
asked 1xmediumLogical reasoningTechnical2017
Ans. For any twin primes greater than 3, write them as n − 1 and n + 1. Since both are odd primes, n is even. Among three consecutive numbers n − 1, n, n + 1, one is divisible by 3. It cannot be either prime, so n is divisible by 3. Hence n is divisible by 6. The pair 3 and 5 is the exception.
Q. Solve the puzzle: ABCD × 4 = DCBA. Find the 4-digit number.
asked 1xmediumLogical reasoningSystem design2020
Ans. ABCD is 2178. Since 4 × ABCD is still four digits, A is 1 or 2. The last digit gives 4D ending in A. Testing possible carry values, A must be 2 and D must be 8. Then column multiplication gives C = 7 and B = 1, so 2178 × 4 = 8712.
Q. Estimate a real-world metric using assumptions (guesstimate).
asked 1xmediumLogical reasoningManagerial2021
Ans. Break the estimate into simple drivers, state clear assumptions, calculate step by step, then sanity check the result. Use population, frequency, time, capacity, or price as needed. Round numbers to keep it manageable. The exact answer matters less than a logical structure, reasonable assumptions, and checking whether the final number feels plausible.
Q. Find the maximum number of 2×2 squares that can be fit inside a right isosceles triangle.
asked 1xmediumMathematicsTechnical2019
Ans. You cannot find a number unless the triangle’s leg length is given. If equal legs are L and squares are parallel to the legs, split it into horizontal strips of height 2. In each strip fit floor((L minus strip top height) / 2) squares, then add the row counts. For L = 2n, total is n(n−1)/2.
Showing 60 of 2,029 questions. Ranked by how often the same question came back across interviews.