Q. Permute the elements of an array following a given order
asked 3xmediumArraysOnline test2021
Ans. Apply the permutation by following each cycle in the order array and rotating the corresponding array values into their target positions. Use the order array itself to mark visited indices, for example by negating entries if valid, so no extra visited set is needed. This runs in O(n) time and O(1) extra space.
Q. Reverse a linked list
asked 3xeasyLinked listsManagerial, Technical2015-2020
Ans. Reverse a linked list by iterating through it and changing each node’s next pointer to point to the previous node. Keep three pointers: previous, current, and next, so you do not lose the rest of the list. At the end, previous is the new head. Time complexity is O(n), space complexity is O(1).
Q. Detect a loop in a linked list
asked 3xeasyLinked listsTechnical2017-2021
Ans. Use Floyd’s cycle detection with two pointers, slow and fast, starting at the head. Move slow one node at a time and fast two nodes at a time. If they ever meet, there is a loop. If fast reaches null, there is no loop. This runs in O(n) time and O(1) space.
Q. Explain ACID properties in DBMS
asked 3xeasyDBMSTechnical2020-2021
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. Print the top view of a binary tree.
asked 2xmediumTreesTechnical2017-2020
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. Find the lexicographic rank of a string
asked 2xmediumStringsOnline test2021
Ans. Compute a 1-based rank by scanning left to right and counting how many valid permutations would start with a smaller available character at each position, then add one. Use character frequency counts and factorials, dividing by duplicate factorials when characters repeat. This takes O(n alphabet) time with fixed alphabet.
Q. Reverse a linked list in groups of size k
asked 2xmediumLinked listsManagerial, Technical2016-2019
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. Search an element in a rotated sorted array
asked 2xmediumBinary searchTechnical2021
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 how garbage collection works in Java
asked 2xmediumOOPTechnical2020-2024
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. Explain the internal working of HashMap in Java.
asked 2xmediumOOPTechnical2020
Ans. A HashMap stores key value pairs in an internal array of buckets, using the key’s hashCode to choose a bucket index. If multiple keys land in the same bucket, it compares keys with equals and stores collisions in a linked list or, after enough collisions, a tree. Resizing happens when the load factor threshold is crossed.
Q. Find the Kth largest element in an unsorted array
asked 2xmediumArraysTechnical2017-2021
Ans. Use Quickselect to find the element that would be at index n minus k if the array were sorted ascending. Partition around a pivot, then recurse only into the side containing that index. It runs in average O(n) time and O(1) extra space, but worst case is O(n squared).
Q. Find the missing and repeating number in an array.
asked 2xmediumArraysTechnical2021-2022
Ans. Use the sum and sum of squares of numbers from 1 to n compared with the array’s sum and square sum to derive two equations for the missing and repeating values. Solve them to get both numbers. This uses no extra data structure, runs in O(n) time, and O(1) space.
Q. Find the longest palindromic substring in a given string.
asked 2xmediumStringsOnline test, Technical2020-2021
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. Design a stack that supports getMin() in O(1) time and O(1) extra space.
asked 2xmediumStackTechnical2021
Ans. Use one stack plus a variable currentMin. When pushing a value smaller than currentMin, store an encoded value such as 2*x - currentMin and update currentMin to x. When popping an encoded value, restore the previous minimum as 2*currentMin - encoded. Push, pop, top and getMin are all O(1).
Q. Design and implement an LRU Cache.
asked 2xhardDesignSystem design, Technical2017-2020
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. Sort an array of 0s, 1s and 2s
asked 2xeasyArraysTechnical2015-2021
Ans. Use the Dutch National Flag algorithm with three pointers: low, mid and high. Scan once: put 0s before low, leave 1s in the middle, and put 2s after high by swapping. This sorts in place with no extra data structure, taking O(n) time and O(1) space.
Q. Print the left view of a binary tree
asked 2xeasyTreesTechnical2020
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. Reverse a linked list using recursion
asked 2xeasyLinked listsTechnical2021
Ans. Reverse it by recursively reversing the rest of the list, then making the next node point back to the current node. The base case is an empty list or a single node, which becomes the new head. Set the current node’s next to null to avoid a cycle. It uses the call stack, takes O(n) time and O(n) space.
Q. What is the Singleton design pattern?
asked 2xeasyDesign patternsSystem design, Technical2017-2021
Ans. The Singleton pattern ensures a class has exactly one instance and provides a global access point to it. It is usually implemented with a private constructor and a static method or property returning the instance. The key detail is thread safety, especially if the instance is created lazily in a multi-threaded program.
Q. What features were introduced in Java 8?
asked 2xeasyOOPTechnical2020
Ans. Java 8 introduced lambda expressions, functional interfaces, the Stream API, default and static methods in interfaces, method references, Optional, the new Date and Time API, and Nashorn JavaScript engine. The most important change was adding functional-style programming, especially through lambdas and streams, making collection processing more concise and expressive.
Q. Find the largest sum contiguous subarray.
asked 2xeasyArraysOnline test, Technical2020-2021
Ans. Use Kadane’s algorithm: scan the array, keeping the best sum ending at the current index and the best sum seen overall. At each element, either extend the previous subarray or start a new one there. Initialise with the first element to handle all negative arrays. Time is O(n), space is O(1).
Q. Check whether a given string is a palindrome
asked 2xeasyStringsTechnical2017-2021
Ans. Use two pointers, one at the start of the string and one at the end, and compare characters while moving inward. If any pair differs, it is not a palindrome; if the pointers meet or cross, it is. This uses no extra data structure and runs in O(n) time with O(1) space.
Q. Check whether a number is a circular prime or not
asked 2xeasyMathOnline test2021
Ans. A number is a circular prime if every cyclic rotation of its digits is also prime. First test the number for primality, then rotate its decimal string one position at a time and test each rotation. Use simple variables or a string. With trial division, time is O(d sqrt n), where d is digit count.
Q. Perform zigzag (spiral) traversal of a binary tree.
asked 2xeasyTreesTechnical2019-2020
Ans. Use level order traversal with a queue, but alternate the order in which each level’s values are recorded. For each level, process all queued nodes, add children left then right, and write values either left to right or right to left. This takes O(n) time and O(w) space, where w is maximum width.
Q. What is polymorphism in object-oriented programming?
asked 2xeasyOOPTechnical2020-2021
Ans. Polymorphism is the ability to treat different object types through the same interface while each type provides its own behaviour. For example, different shapes can all have an area method, but each calculates it differently. The key benefit is writing flexible code that depends on common behaviour rather than specific concrete classes.
Q. Reverse tree path
asked 1xmediumTreesTechnical2021
Ans. Reverse the path by first finding the root-to-target path, then swapping the node values along that path from both ends. Use DFS with a stack or list to store the path, backtracking when a branch fails. The tree structure stays unchanged. Time complexity is O(n), with O(h) extra space.
Q. Clone a linked list
asked 1xmediumLinked listsTechnical2021
Ans. Create a deep copy by making a new node for every original node, then wiring the new next and random pointers to the corresponding copied nodes. The simplest approach uses a hash map from original nodes to cloned nodes. It takes O(n) time and O(n) extra space.
Q. Sort a linked list.
asked 1xmediumLinked listsSystem design2017
Ans. Use merge sort, because linked lists can be split and merged without random access. Find the middle with slow and fast pointers, recursively sort both halves, then merge two sorted lists by relinking nodes. This takes O(n log n) time and O(log n) stack space, or O(1) extra space if done bottom-up.
Q. Flatten a linked list.
asked 1xmediumLinked listsTechnical2016
Ans. Flatten it by repeatedly merging each child or bottom list into one main list, preserving the required order. For the common sorted bottom-pointer version, use the merge step from merge sort on two lists at a time, recursively or iteratively. This uses constant extra space apart from recursion and runs in O(N) total node processing per merge chain.
Q. Painting Fence Problem
asked 1xmediumDynamic programmingTechnical2021
Ans. Use dynamic programming to count valid colourings where no more than two adjacent posts have the same colour. For n posts and k colours, track ways ending with same colour as previous and different colour. Same becomes previous different, different becomes total previous times k minus 1. Time complexity is O(n), space can be O(1).
Q. Detect a cycle in a graph.
asked 1xmediumGraphsTechnical2020
Ans. Use DFS to detect a cycle. For a directed graph, keep a visited set and a recursion stack; reaching a node already in the stack means a cycle. For an undirected graph, track the parent and ignore the edge back to it. Use an adjacency list. Time is O(V + E).
Q. How is memory managed in Java?
asked 1xmediumOOPTechnical2021
Ans. Java memory is managed by the JVM, mainly through automatic allocation and garbage collection. Objects are created on the heap, while method calls and local variables live on the stack. The key point is that unreachable heap objects are reclaimed by the garbage collector, so programmers do not manually free memory.
Q. What are Python magic methods?
asked 1xmediumOOPTechnical2021
Ans. Python magic methods are special double-underscore methods, such as __init__, __str__, and __len__, that let objects work with Python’s built-in syntax and functions. They are called implicitly by the interpreter, so defining them customises behaviours like construction, printing, comparison, arithmetic, iteration, and container access.
Q. Convert a given number to words
asked 1xmediumStringsTechnical2021
Ans. Split the number into groups of three digits and convert each group using lookup arrays for ones, teens, tens, and scale names like thousand, million, and billion. Process from highest group to lowest, skipping zero groups, and join words carefully. The time complexity is O(d), where d is the number of digits.
Q. Explain join operations in SQL.
asked 1xmediumSQLTechnical2022
Ans. SQL join operations combine rows from two or more tables using a related column, usually a primary key and foreign key. Common joins are inner join, left join, right join and full outer join. The key detail is that the join type controls whether unmatched rows are excluded or kept with null values.
Q. Reverse a stack using recursion
asked 1xmediumStackTechnical2021
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. Explain isolation levels in SQL.
asked 1xmediumDBMSTechnical2021
Ans. Isolation levels define how much a transaction is protected from changes made by other concurrent transactions. Common levels are Read Uncommitted, Read Committed, Repeatable Read, and Serializable, increasing in strictness. The key trade-off is consistency versus concurrency: stricter levels prevent dirty reads, non-repeatable reads, and phantom reads, but can reduce performance.
Q. Explain multi-threading in Java.
asked 1xmediumOperating systemsTechnical2020
Ans. Multi-threading in Java means running multiple threads within one process so tasks can execute concurrently and share the same memory. Threads can be created with Thread, Runnable, Callable, or preferably managed through ExecutorService. The key detail is safe access to shared state using synchronisation, locks, or concurrent collections.
Q. Rotate a 2D matrix by 90 degrees
asked 1xmediumArraysTechnical2020
Ans. Rotate a square matrix 90 degrees clockwise by first transposing it, then reversing each row. Transposing swaps matrix[i][j] with matrix[j][i], converting rows to columns, and reversing rows puts them in the correct order. This works in place with O(n²) time and O(1) extra space.
Q. Explain garbage collection in C++
asked 1xmediumOOPTechnical2021
Ans. C++ does not have built-in garbage collection in the usual sense; memory is managed through object lifetimes, destructors, and explicit allocation and deallocation. The preferred approach is RAII, using stack objects and smart pointers such as unique_ptr and shared_ptr, so resources are released deterministically when ownership ends.
Q. Explain SQL joins and their types.
asked 1xmediumSQLTechnical2022
Ans. SQL joins combine rows from two tables using a related column or condition. An inner join returns only matching rows. A left join returns all rows from the left table plus matches from the right. A right join does the reverse. A full outer join returns all rows from both sides. A cross join returns every combination.
Q. Explain the diamond problem in C++.
asked 1xmediumOOPTechnical2021
Ans. The diamond problem in C++ happens when a class inherits from two classes that both inherit from the same base class. The final derived class can contain two separate copies of the base, causing ambiguity when accessing base members. The usual fix is virtual inheritance, which shares one common base subobject.
Q. Create a deadlock condition in Java.
asked 1xmediumOOPTechnical2020
Ans. Create a deadlock by making two Java threads acquire the same two locks in opposite order. For example, thread A locks object 1 then waits for object 2, while thread B locks object 2 then waits for object 1. Neither can continue because each holds the lock the other needs.
Q. Is static data serializable in Java?
asked 1xmediumOOPTechnical2020
Ans. No, static data is not serialised by Java’s default object serialisation. Serialisation saves the state of an object, and static fields belong to the class, not to any individual object. If needed, you must handle such values explicitly, for example with custom writeObject and readObject logic.
Q. Print the right view of a binary tree
asked 1xmediumTreesTechnical2017
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. Traverse a 2D matrix in spiral order.
asked 1xmediumArraysOnline test2017
Ans. Use four boundaries: top, bottom, left and right, and repeatedly walk right, down, left and up, shrinking the relevant boundary after each pass. Store visited values in a result list. Stop when boundaries cross. This visits each cell once, so time complexity is O(mn) and extra space is O(1) besides output.
Q. Compute the diameter of a binary tree.
asked 1xmediumTreesTechnical2020
Ans. Compute the diameter with one postorder DFS that returns each node’s height while updating a global maximum diameter. For each node, get left and right subtree heights; their sum is the longest path through that node. Track the largest such value. This runs in O(n) time and uses O(h) recursion stack space.
Q. Design test cases for given situations
asked 1xmediumTestingTechnical2020
Ans. Design test cases by covering normal flow, boundary values, invalid inputs, empty or null data, duplicate data, large data, error handling, and concurrency if relevant. The key detail is to derive cases from requirements and equivalence classes, then add edge cases around every limit and state transition.
Q. Design a URL shortener system like TinyURL.
asked 1xmediumScalable systemsSystem design2020
Ans. Build a service that maps a long URL to a short unique code, stores it, and redirects users by looking up the code. Use an API layer, database, cache, and analytics pipeline. The key detail is generating collision-free, compact IDs, commonly with a distributed sequence ID encoded in Base62, rather than random retries.
Q. What are the test cases for a television remote?
asked 1xmediumTestingTechnical2022
Ans. A strong answer groups cases by function, usability, and reliability. Cover power, volume, channel, mute, input, menu navigation, numeric keys, range, angle, battery low, pairing, and button debounce. Emphasise positive, negative, boundary, and compatibility tests. Interviewers listen for structure, practical coverage, and awareness of real user behaviour.
Q. Design a Logger class using Singleton design pattern.
asked 1xmediumDesign patternsSystem design2019
Ans. Create a Logger with a private constructor, a single static instance, and a public getInstance method that returns that instance. The key detail is thread safety: initialise eagerly or use locking so two threads cannot create different loggers. The logger writes messages to a file or stream, typically in constant time per call excluding I/O cost.
Q. How would you test a login page? List the test cases.
asked 1xmediumTestingTechnical2022
Ans. A strong answer groups cases by function, security, usability, compatibility and error handling. Include valid login, wrong password, unknown user, blank fields, password masking, remember me, forgot password, lockout or rate limiting, session creation and logout. Emphasise edge cases, clear expected results, and awareness of security risks like injection and brute force.
Q. Design database tables for a Splitwise-like application
asked 1xmediumDBMSTechnical2021
Ans. Use tables for users, groups, group_members, expenses, expense_splits, and settlements. Expenses store payer, group, amount, currency, description, and time. Expense_splits store each participant’s owed share. Settlements record payments between users. The key detail is to treat expenses and settlements as an append-only ledger, deriving balances transactionally to avoid inconsistencies.
Q. A variation of the Box of Defective Balls probability problem
asked 1xmediumProbabilityTechnical2015
Ans. Use conditional probability and count cases carefully. Define the boxes, number of defective and good balls, and the selection process. Find the probability of each route to the observed event, such as drawing a defective ball. Then use Bayes’ rule to update the chance that it came from a particular box.
Q. At 3:15 on a clock, find the angle between the hour hand and the minute hand
asked 1xmediumLogical reasoningTechnical2019
Ans. The angle is 7.5 degrees. To solve clock-angle problems, place 12 at 0 degrees. The minute hand moves 6 degrees per minute, so at 15 minutes it is at 90 degrees. The hour hand moves 30 degrees per hour plus 0.5 degrees per minute, so it is at 97.5 degrees.
Q. Solve the puzzle where 100 windows are toggled (open/close) in multiple passes.
asked 1xmediumLogical reasoningManagerial2020
Ans. The open windows are 1, 4, 9, 16, 25, 36, 49, 64, 81 and 100. A window is toggled once for each divisor of its number. Most numbers have divisor pairs, so they are toggled an even number of times. Perfect squares have one unpaired divisor, so they finish open.
Q. Describe a situation where you faced conflict within a team and how you resolved it.
asked 1xmediumConflict resolutionManagerial2020
Ans. Choose a real, low-drama conflict about priorities, responsibilities, or working style. Emphasise how you listened, stayed calm, clarified facts, and moved the team towards a shared goal. Interviewers look for maturity, ownership, communication, and a practical resolution, not blame or personal criticism. End with the outcome and what you learned.
Q. Given 8 balls where one ball is of different weight, find the odd ball using the minimum number of comparisons.
asked 1xmediumLogical reasoningTechnical2017
Ans. Minimum is 3 weighings if you do not know whether the odd ball is heavier or lighter. Weigh ABC against DEF. If equal, compare G with A; if equal H is odd, otherwise G is odd. If ABC is heavier, weigh AD against BE. Each result leaves two possibilities, separated by one final comparison with a known normal ball.
Q. If distance A to B is x at speed 40 km/hr and distance B to C is 2x at speed y, find y such that the average speed of the whole journey is 40 km/hr
asked 1xmediumProbabilityTechnical2019
Ans. y = 40 km/hr. Use average speed as total distance divided by total time, not the simple average of speeds. Total distance is 3x. Total time is x/40 + 2x/y. Set 3x ÷ (x/40 + 2x/y) = 40, cancel x, and solve to get y = 40.
Q. 25 horses puzzle (find the fastest 3 horses with minimum races)
asked 1xhardLogical reasoningTechnical2017
Ans. The minimum is 7 races. Split the 25 horses into five groups and race each group, giving 5 races. Race the five winners in race 6. The overall winner is fastest. Only horses that could still be second or third are the next two from the winner’s group, the second and third group winners, and the second horse from the second group. Race those five; top two complete the fastest three.
Showing 60 of 754 questions. Ranked by how often the same question came back across interviews.