Q. Find the median of a stream of integers (running median).
asked 5xmediumHeapsTechnical2018-2021
Ans. Use two heaps: a max heap for the lower half of numbers and a min heap for the upper half. Insert each new 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. Insert is O(log n), median is O(1).
Q. Find the longest increasing subsequence in an array
asked 4xmediumDynamic programmingOnline test2019-2020
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. What is the difference between a process and a thread?
asked 4xeasyOperating systemsTechnical2017-2019
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. Boundary traversal of a binary tree
asked 3xmediumTreesOnline test, Technical2019-2021
Ans. Boundary traversal is usually root, left boundary, all leaves, then right boundary in reverse order. Add the root if it is not null, collect left boundary excluding leaves, collect leaves by DFS left to right, then collect right boundary excluding leaves and append it reversed. This avoids duplicates. Time complexity is O(n).
Q. Find the diameter of a binary tree.
asked 3xmediumTreesTechnical2017-2019
Ans. Use a postorder DFS that returns the height of each subtree and updates a global maximum diameter at every node. For each node, the longest path through it is left height plus right height, measured in edges. Visit each node once, so the time complexity is O(n), with O(h) recursion stack space.
Q. Print the left view of a binary tree
asked 3xmediumTreesTechnical2017-2020
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. Connect nodes at the same level in a binary tree
asked 3xmediumTreesTechnical2019
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. Count possible decodings of a given digit sequence
asked 3xmediumDynamic programmingOnline test, Technical2019-2020
Ans. Use dynamic programming where dp[i] is the number of ways to decode the prefix ending at position i. Add dp[i-1] if the current digit is 1 to 9, and add dp[i-2] if the last two digits form 10 to 26. Handle 0 only as part of 10 or 20. Time is O(n), space can be O(1).
Q. Find the longest palindromic substring in a string
asked 3xmediumStringsTechnical2019-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. What is the difference between a mutex and a semaphore?
asked 3xeasyOperating systemsTechnical2019
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. Detect and remove loop in a linked list
asked 2xmediumLinked listsTechnical2019
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. Longest Consecutive Sequence in an array
asked 2xmediumArraysOnline test2019
Ans. Use a hash set to find the longest run of consecutive values in linear time. Insert all numbers, then only start counting from a number if num minus 1 is not in the set. Walk upwards while the next value exists, update the maximum length. Duplicates are ignored. Time is O(n), space is O(n).
Q. Print all permutations of a given string
asked 2xmediumBacktrackingTechnical2019-2021
Ans. Use backtracking to build permutations by choosing each unused character in turn, recursing until the current string has the original length, then print it. Keep a character array, a boolean used array, and a temporary result buffer. The time complexity is O(n × n!) and the recursion depth is O(n).
Q. Find the largest subarray with equal number of 0s and 1s
asked 2xmediumArraysTechnical2019-2021
Ans. Convert each 0 to -1, then find the longest subarray with prefix sum zero. Keep a hash map from prefix sum to its first index. When the same prefix sum appears again, the elements between those indices have equal 0s and 1s. This takes O(n) time and O(n) space.
Q. Find the next greater number with the same set of digits
asked 2xmediumArraysTechnical2019-2020
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. Print all nodes at distance K from a given node in a binary tree
asked 2xmediumTreesTechnical2019-2021
Ans. Use BFS from the given target node after first building a parent map for every node. Treat the tree as an undirected graph where each node connects to its left child, right child and parent. BFS level by level until distance K, then print all nodes in the queue. Time is O(n), space is O(n).
Q. Find the maximum size square sub-matrix with all 1s in a given binary matrix.
asked 2xmediumDynamic programmingTechnical2020
Ans. Use dynamic programming where dp[i][j] is the side length of the largest all-1 square ending at cell i, j. If matrix[i][j] is 1, set it to 1 plus the minimum of top, left, and top-left dp values. Track the maximum value. Time is O(rows × cols), space can be O(cols).
Q. Design a chess game (Low Level Design)
asked 2xhardLldSystem design, Technical2019
Ans. Model it with Game, Board, Player, Move and Piece classes, with Piece subclasses implementing legal move generation. Board is an 8 by 8 grid of squares holding optional pieces. Game controls turns, move validation, capture, check, checkmate, stalemate and history. The key detail is separating piece movement rules from game-state rules like check.
Q. Clone a linked list with next and arbitrary (random) pointer
asked 2xhardLinked listsTechnical2019-2020
Ans. Create a deep copy by mapping each original node to its cloned node, then set cloned next and random pointers using that map. Use a hash map from original node to copy node. First pass creates all copies, second pass wires pointers. Time complexity is O(n), space complexity is O(n).
Q. Find the maximum of all subarrays of size K using a sliding window
asked 2xhardArraysOnline test, Technical2019-2020
Ans. Use a sliding window with a double ended queue storing indices of useful elements in decreasing value order. For each new element, remove smaller elements from the back, remove indices outside the window from the front, then the front is the maximum. This runs in O(n) time and O(k) space.
Q. Count the number of ways to travel a cyclic path in N steps in a triangular pyramid
asked 2xhardDynamic programmingOnline test2020-2021
Ans. The number of cyclic walks of N steps from a fixed vertex of a triangular pyramid is (3^N + 3(-1)^N) / 4. The key detail is that a triangular pyramid is K4, so each move goes to one of three other vertices. A DP with “at start” and “not at start” also works in O(N).
Q. Reverse a singly linked list
asked 2xeasyLinked listsTechnical2020-2021
Ans. Reverse it by walking through the list once and redirecting each node’s next pointer to the previous node. Keep three pointers: previous, current, and next, so you do not lose the remaining list. At the end, previous becomes the new head. Time is O(n), space is O(1).
Q. Explain ACID properties in DBMS
asked 2xeasyDBMSTechnical2019-2020
Ans. ACID properties are the guarantees that make database transactions reliable: Atomicity, Consistency, Isolation and Durability. Atomicity means all or nothing, Consistency keeps valid rules, Isolation prevents concurrent transactions interfering, and Durability ensures committed changes survive crashes. They are essential for correctness in systems handling critical data.
Q. Explain the differences between TCP and UDP.
asked 2xeasyNetworkingTechnical2017-2021
Ans. TCP is connection-oriented and reliable, while UDP is connectionless and does not guarantee delivery, order, or duplicate protection. TCP uses handshakes, acknowledgements, retransmission, flow control, and congestion control, so it is slower but safer. UDP has lower overhead and latency, so it suits streaming, gaming, VoIP, DNS, and cases where speed matters more than perfect delivery.
Q. Check if a binary tree is a Binary Search Tree (BST)
asked 2xeasyTreesTechnical2019-2020
Ans. Check it by recursively validating each node against an allowed value range. For a BST, every node in the left subtree must be less than the current node, and every node in the right subtree greater, with bounds carried down from ancestors. This takes O(n) time and O(h) recursion space.
Q. Find the missing number in an Arithmetic Progression
asked 2xeasyArraysTechnical2019
Ans. Use binary search to find the first position where the actual value differs from the expected arithmetic progression value. Compute the common difference from the first and last elements and the expected length. At index i, expected is first plus i times difference. The search takes O(log n) time and O(1) space.
Q. Generate Gray code sequence for a given number of bits
asked 2xeasyBit manipulationOnline test2019
Ans. Generate the n-bit Gray code sequence by producing numbers from 0 to 2^n minus 1 and converting each i to i XOR i shifted right by one. Store the results in a list. This works because consecutive values differ by exactly one bit. Time complexity is O(2^n), with O(2^n) output space.
Q. Given an array where each element represents the maximum number of steps that can be jumped forward from that element, find the minimum number of jumps to reach the end
asked 2xeasyGreedyOnline test2019
Ans. Use a greedy linear scan: keep the farthest index reachable within the current jump range, and when you reach the end of that range, take one jump and extend the range to that farthest index. This gives the minimum jumps because each jump covers the widest possible next interval. Time is O(n), space is O(1).
Q. Coin Change problem
asked 1xmediumDynamic programmingTechnical2021
Ans. Use dynamic programming to find the minimum number of coins needed for each amount up to the target. Create an array dp where dp[i] is the fewest coins for amount i, initialise dp[0] to 0, and update using each coin. Time complexity is O(amount × number of coins).
Q. Design a database schema.
asked 1xmediumDb designTechnical2016
Ans. Start from the product’s core entities and queries, then model tables with clear primary keys, foreign keys, constraints and indexes. Keep transactional data normalised to avoid duplication, but denormalise where read performance needs it. The most important detail is designing around access patterns, because schema quality depends on how data is written, read and joined.
Q. Design a vending machine.
asked 1xmediumLldTechnical2018
Ans. Design it as a state machine with states like idle, accepting money, item selected, dispensing, and refunding. Keep inventory and prices in a product catalogue, track inserted balance, validate selection and stock, dispense atomically, then return change. The key detail is handling failures safely, especially payment reversal and inventory consistency.
Q. Explain Peterson’s Algorithm
asked 1xmediumOperating systemsTechnical2020
Ans. Peterson’s Algorithm is a software mutual exclusion algorithm for two processes sharing a critical section. Each process sets a flag saying it wants to enter, then gives priority to the other using a turn variable. It waits while the other wants entry and has priority, ensuring mutual exclusion, progress, and bounded waiting.
Q. Minimum cost path in a matrix
asked 1xmediumDynamic programmingTechnical2019
Ans. Use dynamic programming where each cell stores the minimum cost needed to reach it from the start. Initialise the first row and column from their only possible predecessor, then fill each cell as its cost plus the minimum of allowed previous cells, usually top and left. Use a 2D table. Time is O(mn).
Q. Explain database normal forms.
asked 1xmediumDBMSTechnical2017
Ans. Database normal forms are rules for structuring relational tables to reduce duplication and avoid update, insert and delete anomalies. 1NF requires atomic values, 2NF removes partial dependency on part of a composite key, 3NF removes transitive dependency on non-key fields. Higher forms, such as BCNF, handle stricter dependency cases.
Q. Explain how a DNS lookup works
asked 1xmediumNetworkingTechnical2017
Ans. DNS lookup translates a domain name into an IP address by querying DNS servers, usually starting with a local cache or resolver. If not cached, the resolver asks root servers, then the relevant top-level domain server, then the authoritative server for the domain. The result is returned and cached for its TTL.
Q. Next Greater Frequency Element
asked 1xmediumStackOnline test2020
Ans. Use a frequency map and a monotonic stack to find, for each element, the next element to its right with a higher frequency. First count all values, then scan from right to left, popping stack elements whose frequency is less than or equal to the current one. The answer is stack top or -1. Time is O(n), space is O(n).
Q. Puzzle: Rat and poison problem
asked 1xmediumLogical reasoningTechnical2019
Ans. Use binary coding. Number the 1000 bottles from 0 to 999. Give each rat all bottles where its corresponding binary bit is 1. After the poison acts, record which rats died. That dead or alive pattern is a binary number identifying the poisoned bottle. Since 2^10 is 1024, 10 rats are enough.
Q. Explain design patterns in Java
asked 1xmediumOOPTechnical2021
Ans. Design patterns in Java are reusable solutions to common software design problems, expressed as class and object structures rather than fixed code. They help make code easier to extend, test and maintain. Common groups are creational, such as Factory and Singleton, structural, such as Adapter, and behavioural, such as Observer.
Q. Reverse a stack using recursion
asked 1xmediumStackTechnical2019
Ans. Reverse the stack by recursively popping the top element until the stack is empty, then inserting each popped element at the bottom while the calls return. The key helper is “insert at bottom”, which also uses recursion. This uses the recursion call stack, takes O(n²) time, and O(n) extra space.
Q. Remove BST keys in a given range
asked 1xmediumTreesTechnical2020
Ans. Recursively traverse the BST and delete every node whose key lies in the given range, reconnecting subtrees to preserve BST order. If a key is below the range, only process its right subtree; if above, only process its left. For deleted nodes, merge valid left and right subtrees. Time is O(n), space is O(h).
Q. Explain fork vs exec system calls
asked 1xmediumOperating systemsTechnical2019
Ans. fork creates a new child process by duplicating the calling process, while exec replaces the current process image with a new program. After fork, both parent and child continue execution with different return values. After a successful exec, the old code, stack and heap are gone, but the process ID usually stays the same.
Q. Implement merge sort for an array
asked 1xmediumSortingTechnical2019
Ans. Use divide and conquer: recursively split the array into two halves until each part has one element, then merge sorted halves back together by comparing front elements. The key data structure is a temporary array used during merging. Merge Sort runs in O(n log n) time and uses O(n) extra space.
Q. Rotate a binary tree to the right
asked 1xmediumTreesTechnical2017
Ans. To rotate a binary tree to the right at a node, promote its left child, make the promoted node’s right subtree become the original node’s left subtree, then make the original node the right child. Return the promoted node as the new subtree root. This preserves inorder order in a BST and takes O(1) time.
Q. Design and implement an LRU Cache.
asked 1xmediumDesignTechnical2017
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. Explain CPU scheduling algorithms.
asked 1xmediumOperating systemsTechnical2019
Ans. CPU scheduling algorithms decide which ready process gets the CPU next. Common algorithms include First Come First Served, Shortest Job First, Round Robin, Priority Scheduling and Multilevel Queue. The key trade-off is between throughput, response time, waiting time and fairness, with pre-emptive algorithms allowing the OS to interrupt a running process.
Q. Explain paging in operating systems
asked 1xmediumOperating systemsTechnical2019
Ans. Paging is a memory management technique where a process’s virtual address space is split into fixed-size pages, and physical memory is split into same-size frames. The OS maps pages to frames using a page table, allowing non-contiguous allocation. The key benefit is avoiding external fragmentation while supporting virtual memory.
Q. Convert a string into zigzag pattern
asked 1xmediumStringsTechnical2021
Ans. Use an array of strings, one for each row, and scan the input while moving a row pointer down then up in zigzag order. Append each character to the current row, reversing direction at the first and last rows. Finally concatenate all rows. Time complexity is O(n), with O(n) extra space.
Q. Explain database indexing techniques
asked 1xmediumDBMSTechnical2019
Ans. Database indexing techniques store extra data structures that let the database find rows without scanning the whole table. Common indexes include B-tree indexes for ranges and ordering, hash indexes for exact matches, bitmap indexes for low-cardinality columns, and full-text indexes for text search. Indexes speed reads but add storage and slow inserts, updates, and deletes.
Q. Print the top view of a binary tree.
asked 1xmediumTreesTechnical2020
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. Connect ropes with minimum total cost
asked 1xmediumGreedyTechnical2019
Ans. Use a greedy approach with a min-heap: always connect the two shortest ropes first, add their combined length to the total cost, then insert the combined rope back into the heap. Repeat until one rope remains. This minimises cost because shorter ropes are reused more often. Time complexity is O(n log n).
Q. Design a Ludo or Snake & Ladders game
asked 1xmediumObject oriented designTechnical2017
Ans. Model it as a turn-based game engine with players, pieces, dice, board, and rules. The key detail is separating board topology from game flow: Snake and Ladders uses a square-to-square jump map, while Ludo uses paths, home lanes, captures, and safe squares. Persist game state after every valid move.
Q. Implement merge sort on a linked list
asked 1xmediumLinked listsTechnical2019
Ans. Use merge sort by splitting the linked list into halves with slow and fast pointers, recursively sorting each half, then merging the two sorted lists by relinking nodes. The key detail is to cut the list at the middle before recursing. Time complexity is O(n log n), with O(log n) recursion stack space.
Q. Print the right view of a binary tree
asked 1xmediumTreesTechnical2019
Ans. Use level order traversal and print the last node seen at each level. Keep a queue of nodes, process one level at a time using the current queue size, and record or print the node when it is the last in that level. Time complexity is O(n), and space complexity is O(w).
Q. Design classes for a game of billiards
asked 1xmediumOOPTechnical2019
Ans. Model billiards with Game, Table, Ball, Cue, Player, Turn, Shot, Rules and Scoreboard classes. Game coordinates players, turns and rule validation; Table owns pockets, cushions and balls; Ball stores position, velocity, type and state. The most important detail is separating physics simulation from rules, so collisions and scoring remain independently testable.
Q. Explain how indexing works in an RDBMS.
asked 1xmediumDBMSTechnical2019
Ans. Indexing in an RDBMS creates a separate data structure, usually a B-tree, that stores column values with pointers to the matching rows. Instead of scanning the whole table, the database can search the index quickly and fetch only relevant rows. Indexes speed reads but add storage cost and slow inserts, updates, and deletes.
Q. 100 doors puzzle: determine which doors remain open after 100 passes
asked 1xmediumLogical reasoningTechnical2019
Ans. The doors left open are the perfect squares: 1, 4, 9, 16, 25, 36, 49, 64, 81 and 100. A door is toggled once for each divisor of its number. Most numbers have divisors in pairs, so they end closed. Perfect squares have one unpaired divisor, the square root, so they are toggled an odd number of times.
Q. How would you convince a lead engineer to switch from Oracle to MySQL for a new project?
asked 1xmediumCommunicationManagerial2019
Ans. Pick a situation where you influenced a senior technical stakeholder with evidence, not opinion. Emphasise understanding Oracle’s strengths, clarifying project needs, comparing cost, licensing, skills, performance, operational support and risk. Interviewers listen for collaboration, respect for expertise, data driven reasoning, a migration or proof of concept plan, and willingness to accept Oracle if justified.
Q. As a hotel owner, how would you decide the pricing for your hotel rooms? What factors would you consider?
asked 1xmediumDecision makingManagerial2019
Ans. A strong answer should describe a structured pricing approach, using a hotel or revenue management example if possible. Emphasise demand, seasonality, local events, competitor rates, room type, occupancy, customer segments, costs and profit margin. Interviewers listen for commercial judgement, data use, flexibility and awareness that pricing changes over time.
Q. If you are a lead engineer and a junior proposes using MySQL, how would you evaluate and handle the situation?
asked 1xmediumLeadershipManagerial2019
Ans. A strong answer uses a real example where you assessed the proposal fairly, not by seniority. Emphasise understanding requirements, asking the junior to justify trade-offs, comparing MySQL against alternatives, and considering operations, scale, cost, and team skills. Interviewers listen for mentoring, technical judgement, openness, and a clear decision-making process.
Q. There are three buckets with some balls in each. You can double the number of balls in one bucket by taking the required number of balls from another bucket. Determine whether it is possible to equalize all three buckets using only this operation.
asked 1xhardLogical reasoningTechnical2018
Ans. It cannot be decided without the starting counts. For counts a, b, c, the total must first be divisible by 3, since the operation preserves the total. Then try all legal moves, keeping seen states, until either (T/3, T/3, T/3) appears or no new state remains.
Showing 60 of 660 questions. Ranked by how often the same question came back across interviews.