Q. Find the Longest Increasing Subsequence in an array
asked 3xmediumDynamic programmingOnline test2019-2021
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. Find the Lowest Common Ancestor (LCA) of two nodes in a binary tree
asked 3xmediumTreesTechnical2019-2021
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. Print the Top View of a Binary Tree
asked 2xmediumTreesTechnical2017-2022
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. Print all permutations of a given string.
asked 2xmediumStringsTechnical2017
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. What is a gradient and how is it used in machine learning?
asked 2xmediumMachine learningManagerial2019
Ans. A gradient is a vector of partial derivatives that shows how a function changes with respect to each input or parameter. In machine learning, it is used to update model weights by moving in the direction that reduces the loss, most commonly with gradient descent and backpropagation in neural networks.
Q. Given an array of size n, find the majority element (element occurring more than n/2 times) without using extra space and in O(n) time.
asked 2xmediumArraysTechnical2019
Ans. Use Boyer-Moore voting: scan the array keeping a candidate and a count, increasing the count when the current element matches and decreasing it otherwise. When the count becomes zero, choose the current element as the new candidate. If a majority is guaranteed, the final candidate is the answer. Otherwise, verify it with one more scan.
Q. Given a binary tree and a target node, print all nodes at distance d from the target node.
asked 2xhardTreesTechnical2019
Ans. Build a parent map for every node, then run BFS from the target treating left child, right child and parent as neighbours. Keep a visited set to avoid going back. When BFS reaches distance d, print all nodes currently in the queue. This takes O(n) time and O(n) space.
Q. Explain ACID properties in DBMS.
asked 2xeasyDBMSTechnical2023-2024
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. Count distinct pairs with given sum
asked 2xeasyArraysOnline test2021-2022
Ans. Use a hash set to count each unique value pair whose sum equals the target, storing pairs in normalised order such as smaller then larger to avoid duplicates. For each number x, check target minus x. If it has been seen, record the pair. This takes O(n) time and O(n) space.
Q. Design an OR gate using only NAND gates.
asked 2xeasyDigital logicManagerial2019
Ans. Use three NAND gates: invert each input with a NAND gate, then NAND the two inverted signals together. Connect A to both inputs of the first NAND to get NOT A, and B to both inputs of the second to get NOT B. The third NAND gives NOT(NOT A AND NOT B), which equals A OR B.
Q. Explain the difference between BFS and DFS
asked 2xeasyGraphsTechnical2014-2021
Ans. DFS explores as far as possible along one path before backtracking, while BFS explores all neighbours level by level. DFS uses recursion or a stack; BFS uses a queue. Both mark visited nodes to avoid repeats. For a graph with V vertices and E edges, both run in O(V + E) time.
Q. Explain the Software Development Life Cycle (SDLC)
asked 2xeasySoftware engineeringTechnical2020
Ans. SDLC is a structured process for planning, building, testing, deploying, and maintaining software. It gives teams a clear path from requirements to release, reducing risk and improving quality. Common stages include requirement analysis, design, implementation, testing, deployment, and maintenance, often repeated in agile or iterative models.
Q. House Robber III
asked 1xmediumTreesTechnical2021
Ans. Use a depth first search on the binary tree where each node returns two values: the best money if this node is robbed, and the best money if it is not robbed. If robbed, children cannot be robbed. If not robbed, take each child’s best option. This runs in O(n) time with O(h) recursion space.
Q. Transpose a table in SQL.
asked 1xmediumSQLTechnical2021
Ans. Transpose a table in SQL using PIVOT for rows to columns, or UNPIVOT for columns to rows, depending on the direction needed. In databases without PIVOT, use conditional aggregation with CASE expressions and GROUP BY. The key detail is that SQL needs known output columns, so dynamic transposes usually require dynamic SQL.
Q. Generate n-bit Gray Code sequence.
asked 1xmediumRecursionTechnical2020
Ans. Generate the n-bit Gray code by starting with 0 for n equals 0, then for each bit position reflect the current sequence and prefix 1 to the reflected half while prefixing 0 to the original half. Store values in an array or list. This produces 2^n codes in O(2^n) time and space.
Q. Print the right view of a binary tree.
asked 1xmediumTreesTechnical2021
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 a Coffee Vending Machine system.
asked 1xmediumObject oriented designSystem design2019
Ans. Design it as a state-driven machine with services for menu, payment, inventory, recipe execution, dispensing, and monitoring. The key detail is transactional control: reserve ingredients, authorise payment, prepare drink, then commit stock and payment, with rollback or refund on failure. Hardware adapters should hide sensors, heaters, grinder, valves, and cup dispenser.
Q. Find a given element in a Bitonic Array
asked 1xmediumBinary searchTechnical2019
Ans. Find the peak using binary search, then binary search the increasing left half and the decreasing right half for the target. The key detail is that comparisons differ on each side: normal binary search on the left, reversed binary search on the right. This takes O(log n) time and O(1) space.
Q. Print all k-sum paths in a binary tree.
asked 1xmediumTreesTechnical2019
Ans. Use DFS and maintain the current path from the root to the current node. At each node, walk backwards through this path, accumulating a sum, and print every suffix whose sum equals k. Then recurse left and right, and backtrack by removing the node. Time is O(nh), worst case O(n²), space O(h).
Q. Explain and prove the Monty Hall problem
asked 1xmediumProbabilityManagerial2019
Ans. You should switch: it wins with probability 2/3, while staying wins 1/3. Initially your chosen door has a 1/3 chance of the car, and the other two doors together have 2/3. Monty, knowing the doors, always opens a goat door among those two, so their whole 2/3 chance transfers to the single unopened door.
Q. Find the kth largest element in an array
asked 1xmediumArraysTechnical2020
Ans. Use Quickselect to find the Kth largest element by partitioning the array around a pivot and only recursing into the side that can contain the answer. Convert it to the index n minus k in sorted ascending order. Average time is O(n), worst case O(n²), with O(1) extra space.
Q. Delete a linked list recursively from the end
asked 1xmediumLinked listsTechnical2014
Ans. Recursively delete a linked list from the end by calling the delete function on head.next until the last node is reached, then deleting nodes as the recursion unwinds. The key detail is to save or process the next pointer before freeing the current node. It takes O(n) time and O(n) call stack space.
Q. Generate all stepping numbers in a given range
asked 1xmediumGraphsTechnical2021
Ans. Use breadth first search starting from digits 1 to 9, and include 0 separately if it lies in the range. For each number, append last digit minus one and plus one when valid, stopping when values exceed the upper bound. A queue is the main data structure. Time is proportional to the number generated.
Q. Search a given word in a 2D grid of characters
asked 1xmediumMatrixTechnical2019
Ans. Use backtracking DFS from every cell that matches the first character, trying the next character in each allowed neighbouring direction. Keep a visited marker so the same cell is not reused in one path, then unmark on return. Time is O(rows × cols × 4^word length), or 8 directions if diagonals are allowed.
Q. Explain how Sudoku evaluation is done efficiently
asked 1xmediumBacktrackingSystem design2020
Ans. Sudoku evaluation is done efficiently by scanning the board once and tracking seen digits for each row, column, and 3 by 3 box. Use sets or bit masks, ignoring empty cells. If a digit already exists in the relevant row, column, or box, the board is invalid. Time and space are O(1).
Q. Check whether a binary tree is a balanced AVL tree
asked 1xmediumTreesTechnical2014
Ans. Check it with one postorder traversal that returns each subtree height and rejects any node whose left and right heights differ by more than one. Since an AVL tree is also a BST, also validate the inorder bounds while traversing. Use recursion with height and min/max bounds. Time is O(n), space is O(h).
Q. Perform vertical order traversal of an N-ary tree.
asked 1xmediumTreesTechnical2019
Ans. Use level order traversal with a queue storing each node and its column, and a map from column to list of values. Put the root at column 0, assign each child a column using the problem’s defined offset rule, then output columns from smallest to largest. Time is O(n) with tracked min and max columns.
Q. Build a Heap from a given array and explain Heapify
asked 1xmediumHeapTechnical2021
Ans. Build a heap by treating the array as a complete binary tree and running heapify from the last non-leaf node down to the root. Heapify fixes one subtree by comparing a node with its children and swapping until the heap property holds. Bottom-up building takes O(n) time and O(1) extra space.
Q. Design a system (high-level system design question)
asked 1xmediumHigh level designTechnical2020
Ans. Start with requirements, scale, and constraints, then design APIs, data model, services, storage, caching, queues, and deployment. The most important detail is identifying the bottleneck and choosing the right consistency and availability trade-off. Cover request flow, failure handling, observability, security, and how the system scales horizontally.
Q. Solve the coding problem from LintCode Problem 1915
asked 1xmediumUnknownOnline test2021
Ans. Use prefix parity bitmasks and a frequency map. Track a 10-bit mask where each bit shows whether a letter count is odd. For each character, update the mask, then add previous counts of the same mask and masks differing by one bit. Store the current mask count. Time is O(10n), space is O(1024).
Q. Sort a stack without using any other data structure
asked 1xmediumStackTechnical2019
Ans. Use recursion to sort the stack in place, relying only on the call stack. Pop the top item, recursively sort the remaining stack, then insert the popped item into its correct sorted position by recursively moving larger items aside. This takes O(n²) time and O(n) auxiliary space due to recursion.
Q. Find an element in a matrix where each row is sorted
asked 1xmediumBinary searchTechnical2020
Ans. Search each row independently using binary search. For each row, first check whether the target lies between the row’s first and last element, then binary search only that row if possible. This uses the matrix directly, no extra data structure, and takes O(m log n) time for m rows and n columns.
Q. Explain Sentiment Analysis and the PageRank algorithm
asked 1xmediumMlTechnical2020
Ans. Sentiment analysis classifies text by opinion or emotion, such as positive, negative or neutral, using rules, machine learning or deep learning. PageRank ranks web pages by modelling links as votes, where links from important pages count more. Its key idea is iterative scoring on a graph, often with a damping factor for random jumps.
Q. How does Google identify your location from an image?
asked 1xmediumComputer visionHR2021
Ans. Google usually identifies location from an image by reading GPS coordinates stored in its EXIF metadata. Phones often save latitude, longitude and time when a photo is taken. If metadata is missing, Google may infer location using visual recognition, such as landmarks, shop signs, street views, or matching the scene against known images.
Q. Explain page faults and deadlocks in Operating Systems
asked 1xmediumOperating systemsManagerial2019
Ans. A page fault occurs when a process accesses a virtual memory page that is not currently in physical RAM, while a deadlock occurs when processes wait forever for resources held by each other. Page faults are handled by loading the page from disk, but excessive faults hurt performance. Deadlocks require conditions like mutual exclusion, hold and wait, no pre-emption, and circular wait.
Q. Optimize Sieve of Eratosthenes to O(N) time complexity
asked 1xmediumMathTechnical2022
Ans. Use the linear, or Euler, sieve: keep a list of primes and an array marking the smallest prime factor or composite status. For each number i, iterate through primes p and mark i multiplied by p, stopping when p divides i. This ensures every composite is marked exactly once, giving O(N) time and O(N) space.
Q. How is large-scale data stored and managed in databases?
asked 1xmediumDBMSHR2019
Ans. Large-scale data is stored in structured files or distributed storage, managed by a database engine using schemas, indexes, partitions, transactions and replication. The most important detail is partitioning or sharding, which splits data across disks or machines so queries, writes, backups and failures can be handled without one system becoming the bottleneck.
Q. Implement a Trie to predict the next word (autocomplete)
asked 1xmediumTriesSystem design2020
Ans. Use a Trie where each node stores child links and whether a word ends there, optionally with frequency or top suggestions. Insert each dictionary word character by character. For autocomplete, traverse the prefix, then collect words below that node. Insert and prefix lookup take O(L); returning suggestions costs O(number of results).
Q. Find the next greater element for each element in an array
asked 1xmediumArraysTechnical2024
Ans. Use a monotonic decreasing stack to find the next greater element for each array value in O(n) time. Traverse from right to left, popping values less than or equal to the current element. The stack top is then the next greater element, or -1 if the stack is empty. Push the current element afterwards.
Q. Explain Java uncaught exceptions and the Exception hierarchy
asked 1xmediumOOPTechnical2020
Ans. An uncaught exception is an exception that is thrown but not handled by any matching catch block, so it propagates up the call stack and usually terminates the thread. Java’s hierarchy starts with Throwable, then Error and Exception. Exception includes checked exceptions, while RuntimeException and its subclasses are unchecked.
Q. Print the Next Greater Element for every element in an array
asked 1xmediumStackTechnical2019
Ans. Use a stack to find the first greater element to the right of each array element. Traverse the array from right to left, popping values smaller than or equal to the current element. The stack top is the next greater element, or -1 if empty. Push the current element. This runs in O(n) time.
Q. Design inheritance at the compiler level using OOP principles
asked 1xmediumOOPTechnical2019
Ans. Implement inheritance by representing each class in the symbol table with a parent pointer, field layout, method table and type metadata. During semantic analysis, validate cycles, visibility and overriding rules. During layout, reuse parent fields, append child fields, and replace overridden virtual method slots in the vtable. Dynamic dispatch is then O(1).
Q. Explain and solve the Three Door Puzzle (Monty Hall problem).
asked 1xmediumProbabilityTechnical2014
Ans. You should switch doors. Your first choice has a 1 in 3 chance of being the prize, so the other two doors together have a 2 in 3 chance. Monty knows where the prize is and opens a losing door, so that full 2 in 3 chance moves to the remaining unopened door.
Q. Explain how backtracking is used to solve the Sudoku problem.
asked 1xmediumBacktrackingTechnical2021
Ans. Backtracking solves Sudoku by filling empty cells one at a time, trying digits 1 to 9 that obey row, column and 3 by 3 box rules. If a choice later makes the grid impossible, it undoes that choice and tries the next digit. The key detail is efficient validity checking before each placement.
Q. Explain synchronization and its use in concurrent programming
asked 1xmediumOperating systemsManagerial2020
Ans. Synchronization is the coordination of concurrent threads or processes so they access shared data and resources safely. It prevents race conditions by enforcing ordering or mutual exclusion, using tools such as locks, mutexes, semaphores, monitors, or atomic operations. The key trade-off is correctness versus performance, because excessive synchronization can cause contention or deadlock.
Q. Write an SQL query using LEFT JOIN with additional conditions.
asked 1xmediumSQLTechnical2021
Ans. Use a LEFT JOIN and put the extra condition in the ON clause, not the WHERE clause, when you still want unmatched left-table rows returned. For example, join customers to orders while matching only completed orders by adding the status condition to the join condition. Filtering in WHERE can turn it into an inner join.
Q. Design a cinema hall using object-oriented programming concepts
asked 1xmediumOOPTechnical2019
Ans. Model it with classes such as Cinema, Hall, Screen, Seat, Show, Movie, Customer and Booking. A Hall has many Seats and Shows; a Show links a Movie, Hall, time and seat availability. The key detail is to keep booking state per Show, not per Seat, so the same seat can be reused across different showtimes.
Q. How do you cope with irritating or stressful situations at work?
asked 1xmediumConflict resolutionHR2020
Ans. Choose a real work example where you stayed calm, professional, and effective under pressure. Emphasise how you recognised stress, controlled your response, prioritised the work, and communicated constructively. Interviewers listen for emotional maturity, accountability, respect for colleagues, and evidence that irritation does not affect your judgement or performance.
Q. Print the subarray with the largest sum using Kadane’s Algorithm
asked 1xmediumArraysTechnical2024
Ans. Use Kadane’s Algorithm while tracking indices: keep a running sum, reset it when it becomes negative, and update the best sum with start and end positions whenever the running sum improves the answer. Store only a few integer variables, then print elements between the best indices. Time complexity is O(n), space is O(1).
Q. Count all non-repetitive palindromic substrings in a given string
asked 1xmediumStringsOnline test2019
Ans. Count distinct palindromic substrings by expanding around every possible centre and storing each palindrome found in a set. Consider both odd and even length centres. Each expansion stops when characters differ or bounds are crossed. The set removes repeats, and its final size is the answer. Time is O(n²), with O(n²) space.
Q. Design the database schema for an e-commerce website like Amazon.
asked 1xmediumDb designTechnical2021
Ans. Use a relational schema with core tables for users, addresses, products, categories, inventory, carts, orders, order_items, payments, shipments, reviews and sellers. Products need flexible attributes, so store common fields in products and category-specific data in an attributes table or JSON column. The most important detail is preserving order_items as immutable purchase snapshots.
Q. Find the longest palindromic substring using constant extra space
asked 1xmediumStringsTechnical2022
Ans. Use centre expansion: treat every character, and every gap between two characters, as a possible palindrome centre and expand while the ends match. Keep only the best start position and length found so far. This uses constant extra space, checks both odd and even lengths, and runs in O(n²) time.
Q. Subset Sum Problem: determine if a subset with a given sum exists
asked 1xmediumDynamic programmingTechnical2020
Ans. Use dynamic programming to track which sums can be formed from the processed numbers. Maintain a boolean array dp of size target + 1, set dp[0] true, and for each number update sums backwards. The answer is dp[target]. Time is O(n * target) and space is O(target).
Q. Create a deep copy of a linked list with next and random pointers.
asked 1xmediumLinked listsTechnical2021
Ans. Use a hash map from each original node to its copied node, then make two passes over the list. First create all copied nodes and store the mapping. Second, assign each copy’s next and random using the map. This runs in O(n) time and uses O(n) extra space.
Q. Given a number of chocolates and wrappers, find the maximum chocolates you can eat.
asked 1xmediumLogical reasoningTechnical2019
Ans. Eat the initial chocolates, then repeatedly exchange wrappers for more chocolates until you have fewer wrappers than the exchange rate. Track wrappers after each exchange, because each new chocolate also gives one wrapper. In code, while wrappers >= k, add wrappers / k to the total, then set wrappers to wrappers / k plus wrappers % k.
Q. How would you handle conflicts or issues with colleagues or your manager in a work scenario?
asked 1xmediumConflict resolutionHR2020
Ans. Choose a real, low-drama example where you stayed professional, listened first, and solved the issue. Emphasise facts, private conversation, understanding their view, agreeing actions, and following up. Interviewers listen for emotional control, accountability, respect for authority, willingness to escalate appropriately, and focus on team outcomes rather than blame.
Q. How would you convince a class of 60 students to attend a session when they already have sufficient attendance and punishment is not an option?
asked 1xmediumLeadershipManagerial2021
Ans. A strong answer should describe a real situation where influence mattered without authority. Pick an example involving peers, students, or volunteers. Emphasise understanding their motivation, showing clear value, using social proof, making attendance easy, and communicating respectfully. Interviewers listen for empathy, persuasion, planning, ownership, and ethical influence rather than pressure.
Q. Basic aptitude and logical reasoning questions
asked 1xeasyLogical reasoningOnline test2020
Ans. Identify the question type first, such as percentages, ratios, time and work, series, coding, directions, or syllogisms. Write down the given facts, convert words into simple equations or diagrams, and eliminate impossible options. Use estimation to check reasonableness, manage time carefully, and practise common patterns regularly.
Q. General aptitude and logical reasoning questions
asked 1xunknownLogical reasoningOnline test2017
Ans. Break the problem into given facts, required result, and constraints. Identify the question type, such as ratio, percentage, sequence, coding, direction, or arrangement. Use a standard formula or draw a simple table or diagram. Eliminate impossible options, check units, and verify the answer by substituting it back into the conditions.
Q. Logical reasoning aptitude questions involving basic analytical thinking
asked 1xunknownLogical reasoningOnline test2025
Ans. Identify the information given, separate facts from assumptions, and look for patterns, relationships, or contradictions. Translate the problem into a simple table, sequence, diagram, or set of conditions if useful. Eliminate impossible options step by step, then test the remaining answer against every condition before choosing it.
Showing 60 of 295 questions. Ranked by how often the same question came back across interviews.