Q. Find the median in a stream of integers.
asked 2xmediumHeapTechnical2014
Ans. Use two heaps: a max heap for the lower half of numbers and a min heap for the upper half. Keep their sizes equal, or let the max heap have one extra element. Insert into the correct heap, then rebalance. The median is the max heap top, or the average of both tops. Insert is O(log n), median is O(1).
Q. Count the number of inversions in an array
asked 2xmediumArraysTechnical2015-2021
Ans. Use a modified merge sort to count inversions in O(n log n) time. While merging two sorted halves, if an element from the right half is smaller than one from the left, it forms inversions with all remaining elements in the left half. Add that count, merge normally, and return the total.
Q. Find the maximum of all subarrays of size K in an array
asked 2xmediumArraysOnline test, Technical2015-2021
Ans. Use a deque to store indices of useful elements in decreasing value order as you scan the array. Remove indices outside the current window from the front, remove smaller elements from the back, then add the current index. Once the first window is formed, the front gives each maximum. Time is O(n), space is O(k).
Q. Design and implement an autocomplete feature for a text application.
asked 2xmediumDesignSystem design, Technical2022
Ans. Use a trie where each node represents a prefix and stores the top suggestions for that prefix, ranked by frequency, recency or relevance. On each keypress, traverse to the prefix node and return its cached top results. Lookup is O(p), where p is prefix length, with updates handled asynchronously to keep typing fast.
Q. How would you test a feature if production data is not available in the QA environment?
asked 2xmediumProblem solvingManagerial2015-2021
Ans. A strong answer should describe using realistic synthetic or anonymised data, built from production patterns and edge cases. Pick a situation where you clarified data needs, involved product or data owners, created test data deliberately, and documented gaps. Emphasise risk-based testing, privacy, traceability, and how you validated behaviour despite imperfect data.
Q. Print the left view of a binary tree.
asked 2xeasyTreesTechnical2014-2018
Ans. Print the first node visible at each depth when the tree is viewed from the left. Do a level order traversal using a queue, and for each level print the first node removed from the queue. This visits every node once, so the time complexity is O(n), with O(w) space for the queue.
Q. Perform and explain binary tree traversal.
asked 2xeasyTreesTechnical2022
Ans. Binary tree traversal visits every node in a defined order: preorder visits root, left, right; inorder visits left, root, right; postorder visits left, right, root; level order visits nodes breadth first. Depth-first traversals use recursion or a stack, while level order uses a queue. Time is O(n), space is O(h) or O(n).
Q. Explain cookies, access codes, and HTTP status codes.
asked 2xeasyNetworkingTechnical2015-2021
Ans. Cookies are small client-side values stored by a browser, access codes are credentials or tokens used to prove permission, and HTTP status codes are server responses describing request results. The key detail is separation of roles: cookies maintain state, access codes control authorisation, and status codes communicate success, redirects, client errors, or server errors.
Q. Given an array and an integer k, sort the first k elements in increasing order and the remaining elements in decreasing order.
asked 2xeasyArraysOnline test2020-2023
Ans. Sort the subarray from index 0 to k minus 1 in ascending order, then sort the subarray from index k to n minus 1 in descending order. Use the language’s built-in sort with reverse order for the second part. The time complexity is O(k log k plus (n-k) log(n-k)).
Q. Coin exchange problem.
asked 1xmediumDynamic programmingOnline test2021
Ans. Use dynamic programming to compute the minimum coins needed for each amount from 0 to the target. Keep a one-dimensional array dp where dp[0] is 0 and each dp[x] is updated using every coin value. The time complexity is O(amount times number of coins), with O(amount) space.
Q. Merge k sorted arrays.
asked 1xmediumSortingTechnical2014
Ans. Use a min heap to repeatedly take the smallest current element among the k arrays and append it to the result. Initially push the first element of each non-empty array with its array index and position. After popping one, push the next element from the same array. Time complexity is O(N log k), where N is total elements.
Q. Insert Delete GetRandom O(1)
asked 1xmediumDesignTechnical2024
Ans. Use a dynamic array plus a hash map from value to its index in the array. Insert appends the value and records its index. Delete swaps the value with the last array element, updates that element’s index, then pops. GetRandom picks a random array index. All operations are O(1) average time.
Q. Find a peak element in an array.
asked 1xmediumBinary searchTechnical2024
Ans. Use binary search to find any peak element by comparing the middle element with its right neighbour. If arr[mid] is less than arr[mid + 1], a peak must exist on the right; otherwise, it exists on the left including mid. This takes O(log n) time and O(1) space.
Q. Advanced string matching problem.
asked 1xmediumStringsOnline test2021
Ans. Use KMP to find all occurrences of a pattern in a text in linear time. Precompute the longest proper prefix which is also a suffix array for the pattern, then scan the text without moving backwards. The key data structure is the prefix table. Time complexity is O(n + m), with O(m) extra space.
Q. Nearest Exit from Entrance in Maze
asked 1xmediumGraphsTechnical2024
Ans. Use breadth first search from the entrance to find the nearest exit, because BFS explores cells in increasing distance. Put the entrance in a queue with distance zero, mark visited by changing the maze or using a visited set, and stop when a non-entrance boundary cell is reached. Time and space are O(mn).
Q. Print the top view of a binary tree.
asked 1xmediumTreesTechnical2015
Ans. Use level order traversal with a horizontal distance for each node, taking the first node seen at every distance. Store nodes in a queue with their distance, put the first value for each distance in an ordered map, then print map values from left to right. Time is O(n log n), or O(n) with hashing plus min and max distance.
Q. Group strings based on given criteria.
asked 1xmediumStringsTechnical2023
Ans. Group the strings by converting each string into a canonical key that represents the given criteria, then store strings with the same key together in a hash map. For anagrams, the key is usually the sorted string or character counts. This takes O(n k log k) with sorting, where k is maximum string length.
Q. Clone a stack without using extra space
asked 1xmediumStackTechnical2020
Ans. Use recursion to clone the stack, with no auxiliary data structure apart from the destination stack. Pop each element until the original is empty, then during recursion unwinding push the element back onto the original and also onto the clone. This preserves order. Time is O(n); recursion uses O(n) call stack space.
Q. Find the maximum width of a binary tree.
asked 1xmediumTreesTechnical2015
Ans. Use level order traversal with a queue storing each node and its positional index, as if the tree were a complete binary tree. For each level, the width is last index minus first index plus one. Normalise indices at each level to avoid overflow. Time complexity is O(n), space complexity is O(w).
Q. Implement the Producer-Consumer problem.
asked 1xmediumOperating systemsTechnical2016
Ans. Use a bounded blocking queue protected by a mutex, with two condition variables or semaphores for not full and not empty. Producers wait when the buffer is full, lock, enqueue an item, unlock, and signal consumers. Consumers wait when empty, lock, dequeue, unlock, and signal producers. Each produce or consume operation is O(1).
Q. Compare Redis Sentinel and Redis Cluster.
asked 1xmediumDatabasesManagerial2021
Ans. Redis Sentinel provides high availability for a single primary with replicas, while Redis Cluster provides both high availability and horizontal scaling by sharding data across multiple primaries. Sentinel monitors failures and promotes a replica. Cluster splits the key space into hash slots, so clients must understand cluster topology and redirections.
Q. What do you understand by the CAP theorem?
asked 1xmediumDistributed systemsManagerial2019
Ans. The CAP theorem says a distributed data system cannot simultaneously guarantee consistency, availability and partition tolerance. During a network partition, it must choose between returning only consistent, up-to-date data or staying available and possibly serving stale data. In practice, partition tolerance is necessary, so systems trade off consistency and availability.
Q. Design a system to manage a cricket series.
asked 1xmediumHigh level designSystem design2015
Ans. Design it around entities for Series, Teams, Players, Matches, Innings, Overs, Balls and Scorecards, with services for scheduling, live scoring, standings and notifications. The most important detail is making ball-by-ball events the source of truth, so scorecards, player stats, points tables and live feeds can be rebuilt consistently after corrections.
Q. Remove All Adjacent Duplicates in String II
asked 1xmediumStringsTechnical2024
Ans. Use a stack of character and count pairs, scanning the string from left to right. If the current character matches the stack top, increase its count; otherwise push a new pair. When a count reaches k, pop it, which naturally handles cascading removals. The time complexity is O(n) and space is O(n).
Q. Explain currying and hoisting in JavaScript.
asked 1xmediumJavaScriptTechnical2021
Ans. Currying is turning a function that takes several arguments into a chain of functions that each take one argument. It enables partial application and reusable specialised functions. Hoisting is JavaScript’s creation-phase binding of declarations before execution. Function declarations are usable early, var is undefined until assigned, and let and const are in the temporal dead zone.
Q. Given a k-sorted array, sort it efficiently.
asked 1xmediumSortingTechnical2019
Ans. Use a min heap of size k plus 1 to repeatedly output the smallest possible next element. Insert the first k plus 1 elements, then for each remaining element, extract the minimum to the array and insert the new element. Finally drain the heap. Time complexity is O(n log k), space is O(k).
Q. Explain Kafka architecture and its use cases.
asked 1xmediumDistributed systemsManagerial2024
Ans. Kafka is a distributed event streaming platform built around producers, brokers, topics, partitions, consumer groups and ZooKeeper or KRaft for metadata management. Producers write records to topic partitions, brokers store and replicate them, and consumers read independently by offset. It is used for logs, messaging, stream processing, event sourcing and real-time data pipelines.
Q. Implement an LRU (Least Recently Used) Cache.
asked 1xmediumDesignTechnical2018
Ans. Use a hash map plus a doubly linked list. The map gives O(1) access to cache nodes by key, and the list keeps usage order, with most recent at the front and least recent at the back. On get or put, move the node to the front. When capacity is exceeded, remove the back node.
Q. Find the largest basin size in a given matrix.
asked 1xmediumGraphsTechnical2014
Ans. Find each cell’s sink by repeatedly moving to the lowest adjacent cell, then count how many cells end at each sink and return the largest count. Use DFS with memoisation or union find to avoid recomputing paths. With four-directional neighbours, the time complexity is O(rows × cols), and space is O(rows × cols).
Q. Explain AVL trees and how they are implemented.
asked 1xmediumData structuresTechnical2014
Ans. An AVL tree is a self-balancing binary search tree where, for every node, the height difference between left and right subtrees is at most one. It is implemented by storing each node’s height or balance factor, updating it after insertions and deletions, and restoring balance using single or double rotations. Operations are O(log n).
Q. Group anagrams together from a list of strings.
asked 1xmediumStringsTechnical2024
Ans. Use a hash map where the key represents the letters of a word and the value is the list of words with that key. For each string, sort its characters to form the key, then append it to the matching group. This takes O(n k log k) time and O(n k) space.
Q. Print vertical order traversal of a binary tree.
asked 1xmediumTreesTechnical2014
Ans. Use level order traversal while assigning each node a horizontal distance, with root at 0, left child minus 1 and right child plus 1. Store values in a map from distance to list. BFS preserves top to bottom order within each column. Print columns from smallest to largest distance. Time is O(n).
Q. Merge k sorted arrays into a single sorted array.
asked 1xmediumHeapTechnical2022
Ans. Use a min-heap to repeatedly take the smallest current element from the k arrays and append it to the result. Store each heap entry as the value plus its array index and position, then push the next element from that array. For N total elements, time is O(N log k) and space is O(k).
Q. Perform CRUD operations on an employee hierarchy.
asked 1xmediumDesignTechnical2015
Ans. Use a tree where each employee node stores id, details, parent pointer and a list of direct reports, plus a hash map from employee id to node. Create adds a node under a manager, read uses the map, update changes stored details, and delete removes or reassigns subtrees. Lookup is O(1); hierarchy changes are O(number of affected reports).
Q. Clone a linked list with next and random pointers.
asked 1xmediumLinked listsTechnical2015
Ans. Create a new node for each original node and use a hash map from original node to cloned node. First pass copies all nodes and stores the mapping. Second pass sets each clone’s next and random using the map. This runs in O(n) time and uses O(n) extra space.
Q. Determine whether two given linked lists intersect
asked 1xmediumLinked listsTechnical2014
Ans. Use two pointers, one starting at each head. Move each pointer one node at a time; when it reaches the end, redirect it to the other list’s head. If the lists intersect, the pointers meet at the shared node. If not, both become null. Time is O(m+n), space is O(1).
Q. How do you handle disagreements with your manager?
asked 1xmediumConflict resolutionManagerial2019
Ans. Pick a real disagreement where the stakes were meaningful but professional. Emphasise listening first, checking your assumptions with data, explaining your reasoning calmly, and accepting the final decision once made. Interviewers listen for respect, judgement, emotional control, openness to feedback, and the ability to disagree without damaging the relationship.
Q. Why use NoSQL databases? Explain their advantages.
asked 1xmediumDBMSTechnical2021
Ans. Use NoSQL databases when data is large, fast changing, semi-structured, or needs to scale horizontally across many servers. Their main advantages are flexible schemas, high write and read throughput, easy sharding, high availability, and data models suited to documents, key-value access, wide columns, or graphs instead of fixed relational tables.
Q. Explain multithreading and give practical examples.
asked 1xmediumOperating systemsHR2013
Ans. Multithreading is running multiple threads within one process so work can happen concurrently while sharing the same memory space. It is useful for keeping user interfaces responsive, handling many web server requests, downloading files while processing data, or running background tasks. The key detail is managing shared data safely with locks or other synchronisation.
Q. Find the maximum XOR of any two numbers in an array
asked 1xmediumBit manipulationTechnical2015
Ans. Use a binary trie to store the numbers bit by bit, then for each number greedily choose the opposite bit at each position to maximise XOR. Insert all numbers, query each number against the trie, and keep the best result. For 32-bit integers, time is O(32n), effectively O(n), with O(32n) space.
Q. Maximize the sum of K corner elements from an array.
asked 1xmediumArraysTechnical2023
Ans. Take K elements split between the start and end, and maximise that total by trying every possible split efficiently. First sum the first K elements, then one by one remove an element from the left side of that selection and add an element from the right end, tracking the maximum. Time is O(K), space is O(1).
Q. Design a solution for the Snakes and Ladders problem.
asked 1xmediumGraphsTechnical2014
Ans. Use breadth first search over board squares to find the minimum dice throws from start to finish. Treat each square as a node, add up to six moves for dice outcomes, and if the target has a snake or ladder, move to its destination. Keep a queue, visited set, and distance. Time is O(n), space is O(n).
Q. Perform topological sort of a directed acyclic graph.
asked 1xmediumGraphsTechnical2016
Ans. Use Kahn’s algorithm: compute indegree for every vertex, push all zero indegree vertices into a queue, repeatedly remove one, append it to the ordering, and reduce indegree of its neighbours. Any neighbour reaching zero is queued. The result is a topological order. Time complexity is O(V + E), with O(V) extra space.
Q. Find the kth smallest element in a Binary Search Tree.
asked 1xmediumTreesTechnical2024
Ans. Use an in-order traversal, because it visits BST nodes in sorted order, and return the node reached at count k. Implement it iteratively with a stack: go left as far as possible, pop, increment the count, then go right. Time is O(h + k), worst case O(n), and space is O(h).
Q. Find the longest common substring between two strings.
asked 1xmediumStringsTechnical2021
Ans. Use dynamic programming to store the length of the common suffix ending at each pair of positions. If the characters match, set the cell to the diagonal value plus one, otherwise set it to zero. Track the maximum length and end index. Time is O(nm), space can be O(min(n,m)) with rolling rows.
Q. Solve the Word Wrap Problem using dynamic programming.
asked 1xmediumDynamic programmingTechnical2017
Ans. Use dynamic programming where dp[i] is the minimum penalty for wrapping words from index i to the end. For each i, try ending the current line at every valid j, add squared unused spaces to dp[j + 1], with zero cost for the last line. Store breaks to reconstruct lines. Time is O(n²), space O(n).
Q. Design a JukeBox / Spotify-like music streaming system.
asked 1xmediumScalable systemsSystem design2024
Ans. Build clients, an API gateway, user and catalogue services, playlist and recommendation services, streaming service, and object storage/CDN for audio files. Store metadata in a relational database, search index tracks, and keep play state in a fast key value store. The key detail is serving audio through CDN using adaptive bitrate streaming, not from application servers.
Q. Find the Lowest Common Ancestor (LCA) in a Binary Tree.
asked 1xmediumTreesTechnical2021
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. How do you handle ambiguity in product decision-making?
asked 1xmediumConflict resolution2023
Ans. Pick a real decision where goals, data, or ownership were unclear. Emphasise how you framed the problem, identified assumptions, gathered enough evidence, aligned stakeholders, made a reversible decision, and measured the result. Interviewers listen for structured thinking, comfort with uncertainty, collaboration, customer focus, and a bias to action without being reckless.
Q. Implement an LRU Cache using different data structures.
asked 1xmediumDesignTechnical2019
Ans. Use a hash map plus a doubly linked list to implement an LRU cache in O(1) time for get and put. The hash map stores key to node, and the list stores usage order. On access or update, move the node to the front. When capacity is exceeded, remove the tail.
Q. Design and implement an LRU (Least Recently Used) cache.
asked 1xmediumDesignOnline test2014
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 next greater number with the same set of digits
asked 1xmediumStringsTechnical2020
Ans. Scan digits from right to left to find the first digit smaller than the digit after it. Swap it with the smallest larger digit to its right, then sort or reverse the suffix into ascending order. If no such digit exists, no greater number is possible. This is the next permutation algorithm, O(n) time.
Q. Perform topological sorting of a directed acyclic graph.
asked 1xmediumGraphsTechnical2019
Ans. Use Kahn’s algorithm: compute the indegree of every vertex, put all zero-indegree vertices in a queue, repeatedly remove one, add it to the ordering, and reduce the indegree of its outgoing neighbours. When a neighbour reaches zero, enqueue it. The adjacency list and queue give O(V + E) time and O(V) extra space.
Q. Reorder an array according to the given index positions.
asked 1xmediumArraysTechnical2023
Ans. Place each element at the position specified by its corresponding index value. The simplest approach is to create a temporary array, set temp[index[i]] to arr[i] for each element, then copy it back. This uses an auxiliary array, runs in O(n) time, and needs O(n) extra space.
Q. Solve the 0/1 Knapsack Problem using Dynamic Programming
asked 1xmediumDynamic programmingTechnical2024
Ans. Use dynamic programming where dp[i][w] stores the maximum value using the first i items with capacity w. For each item, either skip it or take it if its weight fits, choosing the better value. The table size is n by capacity, so time is O(nW) and space is O(nW), reducible to O(W).
Q. Extend the cricket series design to support the Olympics.
asked 1xmediumHigh level designSystem design2015
Ans. Generalise the cricket series into a multi-sport competition model. Keep common entities such as tournament, venue, schedule, participant, team, match or event, result and standing, then add sport, discipline and event types. The key detail is to make scoring, qualification and ranking rules pluggable per sport, since cricket, athletics and gymnastics rank results differently.
Q. Without using multiplication, division, or modulo operators, compute the value of x divided by y up to two decimal places.
asked 1xmediumLogical reasoningManagerial2019
Ans. Use long division with repeated subtraction. First subtract |y| from |x| until the remainder is smaller, counting the integer part. For each decimal digit, make the remainder ten times larger by adding it to itself ten times, then repeat the subtraction. Do this twice. Apply the sign at the end.
Q. Given a normal die and a blank die, fill the blank die so that the probability distribution of the sum of both dice is uniform for sums from 1 to 12.
asked 1xmediumProbabilityTechnical2014
Ans. Put three 0s and three 6s on the blank die. There are 36 equally likely outcomes, so each of the 12 sums must occur 3 times. Sum 1 can only be made by 1 plus 0, so three faces must be 0. Then sums 1 to 6 are covered. Three 6s cover sums 7 to 12.
Q. Given two coordinates represented as Excel sheet cell numbers like (2, AA) and (1, AB), determine whether the straight line formed between the two points passes through the origin.
asked 1xmediumLogical reasoningOnline test2018
Ans. Convert the Excel column labels to numbers: A = 1, Z = 26, AA = 27, AB = 28. Treat the two points as numeric coordinates, then check whether x1 y2 equals x2 y1. For (2, 27) and (1, 28), 2 × 28 is not 1 × 27, so the line does not pass through the origin.
Q. You are blindfolded and have 100 coins on a table: 80 tails-up and 20 heads-up. You can divide them into two groups and flip any coins blindly. How do you divide them so both groups have an equal number of heads?
asked 1xmediumLogical reasoningManagerial2015
Ans. Take any 20 coins and put them in one group. Put the remaining 80 in the other group. Then flip every coin in the group of 20. If the 20-coin group originally had k heads, the other group had 20 minus k heads. After flipping, the 20-coin group also has 20 minus k heads.
Showing 60 of 795 questions. Ranked by how often the same question came back across interviews.