Q. Explain the difference between stack memory and heap memory.
asked 2xeasyOperating systemsManagerial, Technical2022-2024
Ans. Stack memory is used for function calls and local variables, while heap memory is used for dynamically allocated objects that may live beyond a single function call. Stack allocation is fast and automatically cleaned up when a function returns. Heap allocation is more flexible, but slower and needs garbage collection or manual deallocation.
Q. Decode a given encoded string
asked 1xmediumStringsOnline test2023
Ans. Use a stack to decode the string by scanning left to right, building the current number and current substring. When you see [, push the previous substring and repeat count. When you see ], pop them and expand. This handles nesting correctly. Time complexity is O(n + output size), space is O(n).
Q. Compare merge sort and quick sort
asked 1xmediumSortingTechnical2024
Ans. Merge sort guarantees O(n log n) time and is stable, while quick sort is usually faster in practice but has O(n²) worst-case time. Merge sort needs extra memory for merging, typically O(n). Quick sort sorts mostly in place, using O(log n) stack space on average with good pivot selection.
Q. Explain the Singleton design pattern
asked 1xmediumDesign patternsTechnical2024
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. Explain tries and their applications
asked 1xmediumTreesTechnical2023
Ans. A trie is a tree data structure used to store strings by sharing common prefixes. Each node represents a character, and paths from the root form words or keys. Tries support fast prefix search, insertion, and lookup in O(L) time, where L is string length. Common uses include autocomplete, spell checkers, dictionaries, and IP routing.
Q. Explain operating system fundamentals
asked 1xmediumOperating systemsTechnical2024
Ans. An operating system manages computer hardware and provides services for programs. Its fundamentals include process and thread management, memory management, file systems, device and I/O handling, scheduling, security, and networking. The key idea is abstraction: it hides hardware details and safely shares limited resources between many programs and users.
Q. Differentiate between hashing and encryption
asked 1xmediumSecurityTechnical2024
Ans. Hashing is a one-way transformation used to produce a fixed-size digest, while encryption is a reversible transformation used to protect data confidentiality. Encrypted data can be decrypted with the correct key. A hash cannot practically be reversed, so it is used for integrity checks, password storage, and fast lookups.
Q. What is hybrid sorting and where is it used?
asked 1xmediumSortingTechnical2024
Ans. Hybrid sorting combines two or more sorting algorithms to get better practical performance than using one alone. It is used in standard library sorts and real systems, for example introsort combines quicksort, heapsort and insertion sort. The key idea is switching algorithm based on input size, recursion depth, or data pattern.
Q. Merge K sorted arrays into a single sorted array
asked 1xmediumSortingTechnical2021
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. Find all roots of a tree that give minimum height
asked 1xmediumTreesTechnical2021
Ans. The roots are the tree centroids, found by repeatedly removing all current leaves until only one or two nodes remain. Build an adjacency list and degree array, push all degree one nodes into a queue, then trim layer by layer. The remaining nodes are the minimum height roots. This takes O(n) time and O(n) space.
Q. Explain HTTP response status codes and HTTP methods
asked 1xmediumNetworkingTechnical2024
Ans. HTTP methods describe the action a client wants to perform, while response status codes describe the result of that request. Common methods are GET to read, POST to create or submit, PUT or PATCH to update, and DELETE to remove. Status codes are grouped as 2xx success, 3xx redirect, 4xx client error, and 5xx server error.
Q. Generate all valid IP addresses from a given string
asked 1xmediumStringsTechnical2024
Ans. Use backtracking to split the string into four segments, each of length one to three, and keep only segments between 0 and 255 with no leading zero unless the segment is exactly "0". Store the current path in a small list. There are at most 3^4 splits, so time is effectively O(1), with O(1) extra space.
Q. Design a database schema for a restaurant and its menu
asked 1xmediumDBMSManagerial2021
Ans. Use tables for restaurants, menus, menu_sections, menu_items, item_prices, allergens, item_allergens, modifiers, modifier_options, and orders if ordering is in scope. Restaurants own menus, menus contain sections, sections contain items, and items have prices, availability, and dietary metadata. The key detail is versioning menus or prices so past orders keep correct historical values.
Q. UNIX-based command line and operating system questions
asked 1xmediumOperating systemsOnline test2024
Ans. I use the UNIX command line to inspect files, manage processes, control permissions, search text, and automate routine tasks with shell scripts. The most important concepts are the filesystem hierarchy, pipes and redirection, process management with ps, top, kill, permissions with chmod and chown, and debugging using logs and standard streams.
Q. Write SQL queries to retrieve required data from tables
asked 1xmediumSQLTechnical2024
Ans. Use SELECT to choose columns, FROM to name tables, WHERE to filter rows, JOIN to combine related tables, GROUP BY with aggregate functions to summarise, HAVING to filter groups, and ORDER BY to sort results. The key detail is matching join keys correctly so results are accurate and duplicates are controlled.
Q. Solve Data Structures and Algorithms problems (3 questions)
asked 1xmediumMixedOnline test2024
Ans. I would solve each problem by confirming inputs, outputs and constraints, then deriving a correct baseline before optimising. The key detail is choosing the right data structure, such as a hash map for fast lookup, a heap for priorities, or a stack for nested state, and stating the time and space complexity clearly.
Q. Write an SQL query to find the 10th highest score among students
asked 1xmediumSQLTechnical2024
Ans. Use distinct scores, sort them in descending order, then take one row after skipping the first nine scores. In SQL, this is typically done with DISTINCT, ORDER BY score DESC, LIMIT 1 and OFFSET 9. This returns the 10th highest unique score. Sorting dominates the cost, usually O(n log n).
Q. Answer multiple submatrix sum queries on a 2D matrix efficiently.
asked 1xmediumPrefix sumTechnical2019
Ans. Use a 2D prefix sum matrix to answer each submatrix sum query in constant time after preprocessing. Store prefix[i][j] as the sum from the top left to cell i, j. For query rectangle r1, c1 to r2, c2, use inclusion exclusion. Preprocessing is O(rows * cols), each query is O(1).
Q. What is indexing in databases and how does it improve performance?
asked 1xmediumDBMSTechnical2024
Ans. Indexing in databases is creating an additional data structure, commonly a B-tree or hash index, that lets the database find rows without scanning the whole table. It improves read performance by narrowing searches, joins, sorting, and filtering to relevant records. The trade-off is extra storage and slower writes because indexes must be maintained.
Q. Find the sum of minimum elements of all subarrays of a given array.
asked 1xmediumStackTechnical2022
Ans. Use a monotonic increasing stack and count each element’s contribution as the minimum of subarrays. For each index, find the distance to the previous strictly smaller element and the next smaller or equal element. Its contribution is value times left distance times right distance. Sum all contributions. This runs in O(n) time.
Q. Given 16 rats and 4 cakes, determine a strategy to find the faster rat.
asked 1xmediumLogical reasoningManagerial2022
Ans. Race the rats in four groups of four, using the four cakes as the four lanes or targets. Keep only the winner from each group. Then race those four winners against each other. The winner of that final race is the fastest rat overall, because every other rat has already lost to one of the finalists.
Q. Generate all valid combinations of parentheses for a given number of pairs.
asked 1xmediumBacktrackingTechnical2024
Ans. Use backtracking to build strings one character at a time, adding an opening bracket if fewer than n have been used, and a closing bracket only if it would not exceed the number of openings. Store the current string and counts in recursion. Time is proportional to the Catalan number times n.
Q. What measures should PhonePe use to detect and prevent such payment frauds?
asked 1xmediumSecurityManagerial2024
Ans. PhonePe should use layered, real-time fraud controls: device fingerprinting, velocity limits, behavioural anomaly detection, beneficiary risk scoring, graph analysis of linked accounts, and ML models trained on confirmed fraud. The most important detail is to stop risky payments before authorisation using step-up verification, transaction limits, cooling periods, and manual review for high-risk cases.
Q. Design a system for controlling a single lift in a building with 1000 floors.
asked 1xmediumDesignManagerial2022
Ans. Use a single lift controller with current floor, direction, door state and two ordered request sets: floors above and floors below. Serve requests in the current direction first, stopping at each requested floor, then reverse when none remain. A 1000-bit bitmap per direction is enough, giving fast lookup and small memory.
Q. Generate all combinations of balanced parentheses for a given number of pairs.
asked 1xmediumBacktrackingTechnical2022
Ans. Use backtracking to build each string, adding an opening bracket if fewer than n have been used, and adding a closing bracket only if it would not exceed the number of openings. Store the current sequence in a list or string builder. The time complexity is proportional to the nth Catalan number.
Q. What are virtual functions and virtual classes in C++ and where are they used?
asked 1xmediumOOPManagerial2022
Ans. Virtual functions are member functions resolved at runtime through a base pointer or reference, enabling polymorphism. A virtual class usually means a virtual base class, used in multiple inheritance to ensure only one shared base subobject exists. They are used in interfaces, inheritance hierarchies, callbacks, and avoiding diamond inheritance duplication.
Q. Compare SQL and NoSQL databases and explain when you would choose one over the other.
asked 1xmediumDBMSManagerial2024
Ans. SQL databases are best for structured data, strong consistency and complex queries, while NoSQL databases are best for flexible schemas, high scale and varied data models. I would choose SQL for transactions, reporting and relational data, such as banking. I would choose NoSQL for large, fast-changing or distributed data, such as logs, feeds or document storage.
Q. Find the minimum speed required to arrive on time given distances and time constraints
asked 1xmediumBinary searchTechnical2021
Ans. Use binary search on the speed and return the smallest speed whose simulated journey time is at most the given hour. For a candidate speed, add ceil(distance / speed) for every leg except the last, because departures are hourly, then add the exact final leg time. If none works, return -1. Complexity is O(n log M).
Q. Solve advanced Data Structures and Algorithms problems with detailed approach explanation
asked 1xmediumMixedTechnical2023
Ans. I solve advanced DSA problems by first identifying the pattern, then choosing the right data structure and proving the complexity. For example, graph problems often need BFS, DFS, Dijkstra, or union find, while range queries may need segment trees or Fenwick trees. I explain invariants, edge cases, and time and space complexity.
Q. Given an array, find the frequency of the most frequent element after at most k increments
asked 1xmediumArraysOnline test2021
Ans. Sort the array, then use a sliding window to find the largest group that can be made equal to the rightmost value using at most k increments. Maintain the window sum and shrink from the left while nums[right] times window size minus sum exceeds k. The answer is the maximum window size. Time complexity is O(n log n).
Q. How do you manage branching and handle merge conflicts in Git during collaborative development?
asked 1xmediumToolsTechnical2024
Ans. I manage branching by keeping main stable, creating short-lived feature branches, and regularly pulling or rebasing from the target branch. For merge conflicts, I inspect the conflicting files, understand both changes, keep the correct combined version, run tests, and commit the resolution. Clear commits and early communication reduce painful conflicts.
Q. What is a deadlock? What are the necessary conditions for deadlock and give a general scenario.
asked 1xmediumOperating systemsManagerial2022
Ans. A deadlock is a state where two or more processes are permanently blocked because each is waiting for a resource held by another. The necessary conditions are mutual exclusion, hold and wait, no preemption, and circular wait. For example, process A holds a file lock and waits for a database lock, while process B holds the database lock and waits for the file lock.
Q. You have 12 rats, one eats faster than the others, and 4 cakes. How do you identify the faster rat?
asked 1xmediumLogical reasoningManagerial2022
Ans. Give each cake to a group of three rats for the same short time. The cake with the most eaten must be the group containing the faster rat, because all other rats eat at the same speed. Then give the three suspects equal pieces of remaining cake and watch which piece is eaten first. That rat is faster.
Q. Design a Tiny URL service and estimate the time required to build a production-ready implementation.
asked 1xmediumScalable systemsManagerial2019
Ans. A production-ready Tiny URL service would take about 8 to 12 weeks for a small team. Use an API to create links, generate a unique base62 code from an ID or random token, store mappings in a durable database, cache hot redirects, and add expiry, rate limits, monitoring, analytics, abuse controls, backups, and multi-zone deployment.
Q. Given numCourses and a list of prerequisite pairs, determine if it is possible to finish all courses.
asked 1xmediumGraphsTechnical2024
Ans. It is possible to finish all courses if the prerequisite graph has no directed cycle. Model courses as nodes and prerequisites as edges, then use topological sorting with an adjacency list and indegree array. Repeatedly process zero-indegree courses. If you process numCourses courses, return true; otherwise false. Time and space are O(V + E).
Q. Given a binary tree, find the k-th ancestor of a given node. If the ancestor does not exist, return -1.
asked 1xmediumTreesTechnical2024
Ans. Find the path from the root to the target node, then return the element k positions before the target in that path, or -1 if it does not exist. A DFS with a list or recursion stack is enough. The time complexity is O(n), and the extra space is O(h) to O(n).
Q. How do you avoid race conditions when multiple processes or threads are sending data to a shared system?
asked 1xmediumOperating systemsTechnical2024
Ans. Use a synchronisation mechanism so only one thread or process updates shared state at a time, or route all writes through a thread-safe queue. The key detail is to make the shared operation atomic, using locks, mutexes, semaphores, transactions, or message passing, and to keep the critical section small.
Q. If the backend API sends {x, y} but the frontend requires {x, y, z}, how would you handle this situation?
asked 1xmediumSystem designHR2023
Ans. I would first clarify whether z should be supplied by the backend, derived by the frontend, or optional. If z is required business data, update the API contract and backend response. Until then, the frontend should handle the missing field safely with validation, defaults, or an error state.
Q. Given a set of points on a 2D plane, find the maximum slope between any two points and connect those points.
asked 1xmediumGeometryTechnical2024
Ans. Check every pair of points, compute the slope, and keep the pair with the largest value, then draw or return the line segment between them. If two points have the same x-coordinate, the slope is vertical and effectively infinite, so that pair is the maximum. This uses the input array and takes O(n²) time.
Q. Given a binary tree and a target node, find the time required to burn the entire tree starting from the target node.
asked 1xmediumTreesTechnical2022
Ans. Use BFS from the target, treating the tree as an undirected graph. First traverse the tree to store each node’s parent in a map. Then run BFS using left child, right child and parent as neighbours, marking visited nodes. Each BFS level is one unit of time. Time complexity is O(n), space is O(n).
Q. Given an array, find indices i < j < k such that A[i] ≤ A[j] ≤ A[k] and the product A[i] * A[j] * A[k] is maximized.
asked 1xmediumArraysTechnical2019
Ans. Scan each element as the middle index and query the best valid value on its left and right. Coordinate compress values, use segment trees or Fenwick trees storing minimum and maximum candidates for indices before and after j. For each j, test the four left/right extremes, keep the largest product and indices. Time is O(n log n).
Q. A company grows for one year and then faces continuous decline—what could be the reasons and how would you address them?
asked 1xmediumBusiness analysisManagerial2024
Ans. Growth followed by decline usually means early product market fit weakened, acquisition quality dropped, competition caught up, retention was poor, or operations failed to scale. I would diagnose cohort retention, unit economics, churn reasons, funnel conversion, and market changes, then prioritise fixes such as product improvements, pricing changes, stronger onboarding, cost control, or repositioning.
Q. Why might a ride-hailing incentive policy (extra benefits after X rides per day) be overexploited in a specific location?
asked 1xmediumLogical reasoningManagerial2024
Ans. Because that location enables unusually many very short rides, drivers can hit X rides cheaply and quickly, then collect benefits disproportionate to real work. Check ride counts, trip distances, fares, repeat rider-driver pairs, and timing by area. If one spot has clustered short trips around the threshold, the incentive is being gamed there.
Q. Write SQL queries using aggregate functions, GROUP BY, ORDER BY, and window functions like ROWNUM with practical examples
asked 1xmediumSQLManagerial2024
Ans. Use aggregate functions to summarise rows, GROUP BY to summarise per category, ORDER BY to sort results, and window functions to rank or number rows without collapsing them. For example, calculate total sales per customer, sort by highest total, and use ROW_NUMBER or ROWNUM to return the top N customers.
Q. Design and implement a low-level design solution for a given problem, followed by a discussion on trade-offs and design decisions.
asked 1xmediumLow level designSystem design2024
Ans. Start with core entities, their responsibilities, and relationships, then define interfaces before implementation details. Use simple classes, clear ownership, and patterns only when they reduce coupling, such as strategy for variable behaviour or factory for creation. Discuss trade-offs around extensibility, complexity, concurrency, storage, and failure handling. State time and space costs for key operations.
Q. Explain what happens in the backend when a fraudster sends money back to build trust after asking for an initial small transaction
asked 1xmediumSecurityManagerial2024
Ans. The backend treats the return as another payment or refund, updating ledgers by debiting the sender and crediting the recipient. The key detail is that both transfers remain linked in audit, risk and AML systems, so the pattern can still be flagged even if the user’s visible balance looks restored.
Q. Given an array of integers, determine whether there exists any triplet that can form a triangle (i.e., for some a, b, c: a + b > c).
asked 1xmediumArraysOnline test2021
Ans. Yes: sort the array in ascending order, then check each consecutive triple to see if the two smaller values sum to more than the largest. For sorted values, this single inequality is enough. Ignore non-positive values if side lengths must be valid. Time complexity is O(n log n).
Q. Given height relations like "A > B" and "B < C" among people, determine whether the relations are sufficient to sort all persons by height
asked 1xmediumGraphsTechnical2021
Ans. Use the relations as a directed graph and check whether they imply a unique topological order. Convert each comparison to one direction, such as taller to shorter. The information is sufficient only if topological sorting always has exactly one available zero indegree node at each step, and no cycle exists. Time complexity is O(V + E).
Q. Given an array of integers and a number X, count the number of ordered pairs (i, j) such that concatenating arr[i] and arr[j] results in X.
asked 1xmediumStringsOnline test2021
Ans. Convert the numbers to strings, build a frequency map, then try every split of X’s string into a non-empty prefix and suffix. For each split, add frequency[prefix] multiplied by frequency[suffix], because pairs are ordered. If i and j must be distinct, subtract frequency[prefix] when prefix equals suffix. Time is linear in input digits.
Q. Given two sequences representing north and south bank cities with positions, find the maximum number of non-crossing bridges that can be built.
asked 1xmediumDynamic programmingTechnical2019
Ans. Sort the city pairs by their north bank position, then find the longest increasing subsequence of their south bank positions. That LIS length is the maximum number of non-crossing bridges. Sorting fixes one side’s order, and the increasing subsequence keeps the other side in the same order. Time complexity is O(n log n).
Q. Design a parking lot system with all required classes and draw the class diagram. Also explain an algorithm to guide a car to its assigned parking spot.
asked 1xmediumLow level designSystem design2019
Ans. Use classes ParkingLot, Level, ParkingSpot, Vehicle, Ticket, Gate, DisplayBoard and ParkingAssignmentService. ParkingLot has Levels, Level has Spots, Ticket links Vehicle to Spot. Keep available spots in priority queues by vehicle type, ordered by nearest distance to entry gate. On entry, pop the best spot, issue ticket, update displays and guide by level, row and spot signs.
Q. Design a data structure to support adding an element, removing an element, finding the minimum frequency element, and finding the maximum frequency element.
asked 1xmediumHashingTechnical2023
Ans. Use a hash map from element to frequency and another hash map from frequency to a set of elements, while maintaining current minFreq and maxFreq. On add or remove, move the element between frequency buckets and delete empty buckets. This gives O(1) average add, remove, find minimum frequency, and find maximum frequency.
Q. Given an array, perform either +k or -k exactly once on each element such that the difference between the maximum and minimum elements after the operations is minimized.
asked 1xmediumGreedyTechnical2023
Ans. Sort the array, then try every split where smaller elements get +k and larger elements get -k, keeping the minimum possible range. For split i, the new minimum is min(a[0] + k, a[i+1] - k) and maximum is max(a[i] + k, a[n-1] - k). Time complexity is O(n log n).
Q. Given costs of m breads and n sauces and a budget B, choose exactly one bread and any number of sauces (each at most once) such that the total cost is as close as possible to B.
asked 1xmediumDynamic programmingTechnical2023
Ans. Compute all possible sauce subset costs with a bitset, then for each bread cost b, look for the sauce sum closest to B minus b and update the best total. The key detail is that each sauce is used once by shifting the bitset once per sauce. Time is O(nS + mS) conceptually, where S is total sauce cost.
Q. There are seats numbered from 1 to N with some occupied and some empty. For each of M queries, allocate a seat to a new person such that the distance to the closest occupied seat is maximized.
asked 1xmediumGreedyTechnical2019
Ans. Use a max heap of empty intervals, keyed by the best distance achievable in that interval. For a middle interval choose its midpoint; for an edge interval choose seat 1 or N. After allocating, split the interval and push remaining parts back. Initial sorting costs O(K log K); each query costs O(log K).
Q. Design and implement a Snake and Ladder game with modular, extensible code that can support adding new obstacles, multiple snakes/ladders, and any number of players. The solution should be demoable.
asked 1xmediumObject oriented designTechnical2019
Ans. Model the game with Board, Player, Dice, GameEngine and a SquareEffect interface implemented by Snake, Ladder or future obstacles. Store effects in a map from start square to effect, and players in a queue. Each turn rolls dice, moves, applies any effect, checks win. Turn time is constant, setup is linear.
Q. Given ratings of N children, distribute candies such that each child gets at least one candy and children with a higher rating than their neighbors get more candies. Find the minimum candies required.
asked 1xmediumGreedyTechnical2024
Ans. Use a two-pass greedy approach to assign the minimum candies. Give every child one candy, scan left to right and increase candies when a rating is higher than the left neighbour, then scan right to left and fix higher-than-right cases using the maximum. Sum the array. Time is O(N), space is O(N).
Q. Discuss the importance of technology in the finance industry
asked 1xunknownCommunicationGroup discussion2024
Ans. A strong answer should pick a finance setting where technology clearly improved speed, control, access or decision making, such as payments, fraud detection, trading, reporting or customer service. Emphasise risk management, data quality, regulation, cyber security and customer trust. Interviewers listen for balanced thinking, not blind enthusiasm, and awareness that technology supports judgement.
Q. What real-world problems have you solved other than programming-related ones?
asked 1xunknownProblem solvingHR2023
Ans. Pick a practical problem where you took responsibility, understood constraints, involved others, and produced a clear result. It could be improving a team process, resolving a customer issue, organising an event, or handling a logistical challenge. Emphasise your judgement, communication, initiative, and measurable impact. Interviewers listen for ownership and transferable problem-solving skills.
Q. Describe a recent disagreement you had with someone and explain how you handled it.
asked 1xunknownConflict resolutionHR2023
Ans. Pick a real, low-drama work disagreement where the stakes mattered and you behaved constructively. Emphasise listening, clarifying facts, staying calm, and finding a practical compromise or agreed decision. Interviewers listen for self-awareness, respect, ownership, and the ability to disagree without damaging relationships or slowing delivery.
Showing 60 of 92 questions. Ranked by how often the same question came back across interviews.