

























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


























250 Questions with Interview-Level Answers — DSA · OOPs · DBMS · Computer Networks · System Design Each answer is written the way a strong candidate would actually explain it out loud: the core idea first, then complexity/trade-offs, then a concise implementation or example where it adds value. Use this as your final-revision reference, not your first-learning resource — work the DSA
Q1. [E] Find the second largest element in an array without sorting. Track two variables, largest and second, in a single pass. For each element x: if x > largest, set second = largest, largest = x; else if x > second and x != largest, set second = x. This is O(n) time, O(1) space — strictly better than sorting (O(n log n)). Edge cases: array with duplicates only, or fewer than 2 distinct elements — handle by initializing both to -infinity and checking at the end. Q2. [E] Reverse a string/array in place. Two-pointer swap: left = 0, right = n-1, swap arr[left] and arr[right], move pointers inward until they cross. O(n) time, O(1) extra space. For immutable strings (Java/Python str), convert to a mutable list/char array first — mention this distinction, interviewers often probe it. Q3. [E] Check if a string is a palindrome (with and without extra space). With extra space: compare the string to its reverse (s == s[::-1]). Without extra space: two-pointer from both ends comparing characters, O(1) space. For “palindrome ignoring non-alphanumeric” variants (common follow-up), skip non-alphanumeric chars while moving pointers and compare case-insensitively. Q4. [E] Move all zeros in an array to the end while maintaining order of other elements. Two-pointer: writePtr = 0. Iterate readPtr over the array; whenever arr[readPtr] != 0, swap it into arr[writePtr] and increment writePtr. After the loop, everything from writePtr to end is 0. O(n) time, O(1) space, single pass, preserves relative order — this is the key insight interviewers want, not just “sort with a comparator.” Q5. [M] Find the maximum subarray sum (Kadane’s Algorithm) and explain why it works. Maintain currentSum and maxSum. At each element: currentSum = max(arr[i], cur- rentSum + arr[i]); maxSum = max(maxSum, currentSum). The insight: if the running sum ever goes negative, it can only hurt any future subarray, so it’s optimal to “restart” from the current element. O(n) time, O(1) space. Follow-up: to also return the subarray indices, track the start index whenever you reset currentSum = arr[i]. Q6. [M] Given an array, find all pairs with a given sum (two-pointer vs hashmap trade- offs). Hashmap approach: iterate once, for each x check if target - x is already seen; O(n) time, O(n) space, works on unsorted arrays, naturally handles duplicates if you track counts. Two-pointer approach: requires a sorted array first (O(n log n) to sort if not already), then O(n) with O(1) extra space using two pointers from both ends. State the trade-off clearly: hashmap is faster if array is unsorted and space isn’t constrained; two-pointer wins when the array is already sorted or space is tight. Q7. [M] Find the missing and repeating number in an array of 1 to n. Best approach: use the mathematical sum and sum-of-squares equations. Let S = n(n+1)/2 and S2 = n(n+1)(2n+1)/6. Compute actualSum and actualSumSq from the array. missing - repeating = S - actualSum and missing² - repeating² = S2 - actualSumSq. Solve the two equations for missing and repeating. O(n) time, O(1) space. Alternative: XOR-based approach avoids overflow issues with large n. Q8. [M] Rotate an array by k positions in O(n) time and O(1) space. The “reversal algo- rithm”: reverse the whole array, then reverse the first k elements, then reverse the remaining n-k elements (for a right rotation). This achieves the rotation in exactly 3 passes with O(1) extra space, better than using a temp array (O(n) space) or rotating one step at a time (O(n·k) time). Always normalize k = k % n first to handle k > n. Q9. [M] Find the longest substring without repeating characters. Sliding window with a hashmap storing the last seen index of each character. Expand right pointer; if the character is already in the window (its last index ≥ left), move left to lastIndex + 1. Track maxLen = max(maxLen, right - left + 1) at each step. O(n) time (each char visited at most twice), O(min(n, charset size)) space.
the cycle start and the cycle length in Floyd’s algorithm — be ready to derive it on a whiteboard if asked.
Q19. [M] Merge two sorted linked lists. Use a dummy head node; compare the two lists’ current nodes, attach the smaller, advance that list’s pointer. Continue until one list is exhausted, then attach the remainder of the other. O(n+m) time, O(1) extra space (just re-linking pointers).
Q20. [M] Find the middle of a linked list in one pass. Slow/fast pointers: slow moves 1 step, fast moves 2. When fast reaches the end, slow is at the middle. O(n) time, O(1) space, single pass — avoids the two-pass “count then traverse n/2” approach.
Q21. [M] Remove the Nth node from the end of a linked list. Two pointers with a gap of N: advance a fast pointer N steps first, then move slow and fast together until fast hits the end; slow is now just before the node to remove. Use a dummy head to cleanly handle removing the head node itself. O(n) time, O(1) space, single pass.
Q22. [H] Merge k sorted linked lists efficiently. Best approach: a min-heap of size k holding the current head of each list; repeatedly pop the minimum, push its next. O(N log k) time where N is total nodes, O(k) space. Alternative: pairwise merge using divide-and-conquer, also O(N log k). Explicitly reject the naive O(N·k) “merge one at a time” approach and explain why the heap/D&C wins.
Q23. [H] Clone a linked list with random pointers. O(1)-extra-space trick: interleave cloned nodes into the original list (A -> A' -> B -> B'...), so A'.random = A.random.next. Then detach the interleaved list into original and clone. O(n) time, O(1) extra space — this beats the hashmap approach (O(n) space) and is the answer interviewers are fishing for on the follow-up “can you do it without a hashmap?”
Q24. [E] Implement a stack using two queues (and vice versa). Stack-via-queues: on push, enqueue the new element then rotate the queue (dequeue and re-enqueue) so the new element ends up at the front — makes pop O(1) but push O(n). Queue-via-stacks: use an “in” stack for enqueue and an “out” stack for dequeue, transferring elements only when “out” is empty — amortized O(1) per operation.
Q25. [E] Check for balanced parentheses using a stack. Push opening brackets; on a clos- ing bracket, check the stack top matches the corresponding opener, pop if so, else unbalanced. String is balanced iff the stack is empty at the end. O(n) time, O(n) space.
Q26. [M] Design a stack that supports getMin() in O(1) time. Maintain an auxiliary stack that tracks the minimum at each push: push min(newVal, currentMin) onto the aux stack alongside the main stack. Pop both together. O(1) for push/pop/getMin, O(n) space. Space- optimized variant: only push to the aux stack when a new minimum is found, storing (value, count) pairs.
Q27. [M] Evaluate a postfix/prefix expression using a stack. Postfix: scan left to right, push operands; on an operator, pop two operands, apply the operator, push the result back. Prefix: scan right to left with the same logic. O(n) time, O(n) space.
Q28. [M] Design a circular queue / LRU cache using a doubly linked list + hashmap. LRU cache: hashmap maps key → node for O(1) lookup; a doubly linked list maintains usage order (most-recently-used at head). On get, move the accessed node to the head. On put, if at capacity, evict the tail node and remove it from the map. Both operations are O(1) — this is one of the most frequently asked LLD+DS hybrid questions, be fluent in coding it end to end.
Q29. [H] Find the next greater element for every element in an array. Monotonic de- creasing stack: iterate right to left (or left to right with index storage), push indices; while the stack top’s value ≤ current value, pop it (it can’t be anyone’s “next greater” beyond this point);
the new stack top (if any) is the next greater element for the current one. O(n) time — each element pushed/popped at most once — O(n) space. Q30. [H] Largest rectangular area in a histogram using a stack. Monotonic increasing stack of indices. For each bar, while the stack top’s height ≥ current height, pop it and compute the area with that popped bar as the shortest bar (width = current index − new stack top index − 1). O(n) time, O(n) space — this is the same core technique reused in the “maximal rectangle in a binary matrix” problem (Q14).
Q31. [E] Traverse a binary tree — inorder, preorder, postorder (iterative and recursive). Recursive versions follow directly from the definitions (left-root-right, root-left-right, left-right- root). Iterative versions use an explicit stack: preorder is straightforward (push right then left after visiting root); inorder pushes all left children first then processes; postorder is trickiest — commonly done by reversing a modified preorder (root-right-left) traversal. Know all six variants — this is a very common warm-up question.
Q32. [E] Find the height/depth of a binary tree. Recursive: height(node) = 1 + max(height(node.left), height(node.right)), base case returns 0 for null. O(n) time, O(h) space for recursion stack (h = height). Q33. [E] Check if two trees are identical / check if a tree is symmetric. Identical: recur- sively check val equality and recurse on both left-left/right-right pairs. Symmetric: recursively compare left.left with right.right and left.right with right.right’s mirror — essentially “is this tree identical to its own mirror.”
Q34. [M] Find the lowest common ancestor (LCA) of two nodes in a BST and in a general binary tree. BST: exploit ordering — starting at root, if both target values are less than the current node, go left; if both greater, go right; otherwise the current node is the LCA. O(h) time. General binary tree: recursively search both subtrees; if a node finds both targets in different subtrees (or is one of the targets itself), it’s the LCA. O(n) time since no ordering to exploit. Q35. [M] Level-order traversal (BFS) and zig-zag level order traversal. Standard BFS using a queue, processing one level at a time (track level size before the inner loop). Zig-zag: same BFS but reverse the order of node values on alternating levels (using a flag or a deque appending left/right alternately). Q36. [M] Convert a binary tree to its mirror image. Recursively swap left and right children at every node, post-order (swap children before returning up) or pre-order both work. O(n) time, O(h) space. Q37. [M] Check if a binary tree is height-balanced. Naive: for each node compute heights of both subtrees and check the difference ≤ 1 — but this recomputes heights repeatedly, O(n²) worst case. Optimal: single post-order pass returning -1 as a sentinel the moment imbalance is detected, short-circuiting further computation — O(n) time. Q38. [M] Serialize and deserialize a binary tree. Use preorder traversal with explicit null markers (e.g., “#”), joined by a delimiter, to serialize. Deserialize by reconstructing recursively, consuming tokens in the same preorder sequence and creating null nodes when a “#” is encoun- tered. O(n) time and space for both operations — the key point to articulate is why null markers are necessary to make the tree structure unambiguous. Q39. [H] Find the diameter of a binary tree. Diameter = the longest path between any two nodes, which may not pass through the root. Compute via a single post-order DFS that, at each node, updates a global max with leftHeight + rightHeight, while returning 1 + max(leftHeight, rightHeight) upward. O(n) time — the key insight is combining the “height” computation and the “diameter” computation into one pass instead of two.
Q50. [H] Bellman-Ford algorithm — why is it needed over Dijkstra for negative weights? Relax all edges V-1 times: if dist[u] + weight < dist[v]: dist[v] = dist[u] + weight. After V-1 iterations, all shortest paths are found (since the longest possible shortest path has V-1 edges). A V-th iteration that still finds relaxations indicates a negative-weight cycle. O(V·E) time — slower than Dijkstra, but correctly handles negative weights and detects negative cycles, which Dijkstra cannot. Q51. [H] Find the minimum spanning tree using Kruskal’s and Prim’s algorithms. Kruskal’s: sort all edges by weight, greedily add each edge if it doesn’t form a cycle (checked via Union-Find). O(E log E). Best for sparse graphs / edge lists. Prim’s: grow the MST from an arbitrary start node, always adding the cheapest edge connecting the tree to a new node (via a min-heap). O(E log V). Best for dense graphs / adjacency lists. Both produce a valid MST — mention this equivalence and the complexity trade-off based on graph density. Q52. [H] Detect and print a cycle in a graph. Extend the cycle-detection DFS (Q44) to track the parent chain (a path/recursion stack array); when a back edge is found, backtrack through the parent pointers from the current node to the ancestor that closes the cycle to reconstruct and print the actual cycle nodes. Q53. [H] Word Ladder — shortest transformation sequence between two words. Model as an unweighted graph where each word is a node and an edge exists between words differing by one letter. BFS from the start word gives the shortest transformation length. To generate neighbors efficiently, try all single-character substitutions at each position and check member- ship in the word set (hashset) rather than comparing against every other word — O(L² × 26) per word instead of O(N×L) comparisons. Q54. [H] Find bridges and articulation points in a graph. Tarjan’s algorithm using DFS with discovery[] and low[] time arrays. A bridge exists on edge (u,v) if low[v] > discov- ery[u] (v’s subtree can’t reach back to u or above without this edge). An articulation point is a node whose removal increases the number of connected components — detected via similar low[]/discovery[] comparisons with special-casing the DFS root. O(V+E) time.
Q55. [E] Fibonacci number using memoization vs tabulation — explain time/space trade-offs. Naive recursion is O(2ⁿ) due to repeated subproblem recomputation. Memoiza- tion (top-down) caches results in a hashmap/array, reducing to O(n) time, O(n) space (cache + recursion stack). Tabulation (bottom-up) builds an array iteratively from base cases, O(n) time, O(n) space — can be further optimized to O(1) space since only the last two values are needed at any time. Q56. [E] Climbing stairs problem (count distinct ways). ways(n) = ways(n-1) + ways(n-2) — same recurrence as Fibonacci, since from step n you either came from n-1 (1 step) or n-2 ( steps). O(n) time, O(1) space with rolling variables. Q57. [M] 0/1 Knapsack problem. dp[i][w] = max value using the first i items with capacity w. Recurrence: dp[i][w] = max(dp[i-1][w], dp[i-1][w-wt[i]] + val[i]) if wt[i] <= w, else just dp[i-1][w]. O(n·W) time and space, reducible to O(W) space using a 1D array iterated right-to-left (to avoid reusing an item). Q58. [M] Longest common subsequence between two strings. dp[i][j] = LCS length of s1[0:i] and s2[0:j]. If s1[i-1] == s2[j-1], dp[i][j] = dp[i-1][j-1] + 1 ; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]). O(m·n) time and space, space reducible to O(min(m,n)) with rolling rows. Q59. [M] Longest increasing subsequence (O(n log n) approach). Naive DP is O(n²): dp[i] = LIS ending at i. Optimal: maintain a tails[] array where tails[k] is the smallest tail value of an increasing subsequence of length k+1; for each number, binary-search for its position in
tails and replace/append. The length of tails at the end is the LIS length. O(n log n) — note that tails doesn’t represent an actual valid subsequence, only its length is meaningful. Q60. [M] Coin change — minimum coins to make a sum / number of ways to make a sum. Min coins: dp[amt] = min(dp[amt - coin] + 1) over all coins, dp[0] = 0 , unreachable amounts stay infinity. O(amount × coins) time. Number of ways: iterate coins in the outer loop and amounts in the inner loop (dp[amt] += dp[amt - coin]) to avoid counting permutations as distinct — this ordering distinction is a classic interview trap, be ready to explain why it matters. Q61. [M] Edit distance between two strings. dp[i][j] = min operations to convert s1[0:i] to s2[0:j]. If characters match, dp[i][j] = dp[i-1][j-1]; else dp[i][j] = 1 + min(insert, delete, replace) = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]). O(m·n) time and space. Q62. [M] House robber problem (linear and circular variants). Linear: dp[i] = max(dp[i- 1], dp[i-2] + nums[i]) — either skip house i or rob it and add to the best up to i-2. O(n) time, O(1) space with rolling variables. Circular: since first and last houses are adjacent, run the linear solution twice — once excluding the first house, once excluding the last — and take the max. Q63. [M] Partition equal subset sum. Reduces to: does a subset exist summing to totalSum / 2? (If total is odd, immediately false.) This is a 0/1 knapsack variant — dp[s] = whether sum s is achievable, iterated over items with the sum dimension traversed right-to-left. O(n × sum) time and space. Q64. [M] Unique paths in a grid with obstacles. dp[i][j] = dp[i-1][j] + dp[i][j-1] if the cell isn’t an obstacle, else 0. Base case: dp[0][0] = 1 if not an obstacle. O(rows×cols) time, reducible to O(cols) space with a rolling 1D array. Q65. [H] Longest palindromic substring / subsequence. Substring: dp[i][j] = true if s[i:j] is a palindrome, using dp[i][j] = (s[i]==s[j]) and dp[i+1][j-1], filled by increasing substring length. O(n²) time and space — Manacher’s algorithm improves this to O(n) but is rarely required to code from scratch in interviews, mention it as a known optimization. Subse- quence: dp[i][j] = LPS length of s[i:j], same recurrence style as LCS between the string and its reverse. Q66. [H] Matrix chain multiplication. dp[i][j] = min multiplication cost to multiply matri- ces i through j, trying every split point k: dp[i][j] = min over k of dp[i][k] + dp[k+1][j] + cost(i,k,j). O(n³) time, O(n²) space — classic interval DP pattern, useful to mention it gener- alizes to “optimal BST” and “burst balloons” style problems. Q67. [H] Word break problem using a dictionary. dp[i] = true if s[0:i] can be segmented using dictionary words. For each i, check all j < i: dp[i] = dp[i] or (dp[j] and s[j:i] in dictionary). O(n² ) time (with O(1) dictionary lookups via a hashset), O(n) space. Follow-up “return all possible segmentations” needs backtracking + memoization instead of a boolean DP.
Q68. [H] Maximum profit in stock buy-sell with at most k transactions. dp[t][i] = max profit using at most t transactions up to day i. dp[t][i] = max(dp[t][i-1], max over j arr[mid]; then check if the target lies within that sorted half’s range to decide which half to recurse into. O(log n) time. Q81. [M] Search in a 2D matrix sorted row-wise and column-wise. Start from the top-right corner: if the current value equals the target, done; if greater, move left (eliminate the column); if smaller, move down (eliminate the row). O(rows + cols) time, O(1) space — much better than binary-searching each row individually (O(rows log cols)). Q82. [M] Find the kth largest/smallest element in an unsorted array. Quickselect: par- tition like quicksort but only recurse into the side containing the kth index, giving average O(n) time (worst O(n²), mitigated with random pivot selection). Alternative: a min-heap of size k gives O(n log k) time, O(k) space — preferred when you need it repeatedly or on a stream. Q83. [M] Merge intervals / insert an interval into a sorted list of intervals. Already- sorted insert: linear scan — append all intervals ending before the new one starts, merge all overlapping intervals into the new one, then append the rest. O(n) time since the list is already sorted, no need to re-sort. Q84. [H] Count inversions in an array using merge sort. Augment merge sort’s merge step: whenever an element from the right half is placed before remaining elements of the left half, add (mid - i + 1) to the inversion count (all remaining left elements form an inversion with it). O(n log n) time — much better than the naive O(n²) pairwise comparison.
Q85. [H] Median in a stream of running integers. Two heaps: a max-heap for the lower half, a min-heap for the upper half, kept balanced in size (differing by at most 1). Insert into the appropriate heap based on comparison with the max-heap’s top, then rebalance if sizes differ by more than 1. Median is either the max-heap’s top (odd total) or the average of both tops (even total). O(log n) per insertion, O(1) per median query.
Q86. [E] Activity selection problem — maximum non-overlapping intervals. Sort activ- ities by end time; greedily pick an activity if its start time is ≥ the end time of the last picked activity. O(n log n) — the proof relies on an exchange argument: picking the earliest-ending activity never does worse than any other choice. Q87. [M] Job sequencing problem with deadlines and profits. Sort jobs by profit descend- ing. For each job, try to schedule it in the latest available free slot at or before its deadline (using a Union-Find or simple array scan for slot availability). O(n log n + n·d) or O(n log n) with Union-Find optimization. Q88. [M] Fractional knapsack problem. Sort items by value/weight ratio descending; greed- ily take as much as possible of the highest-ratio item, taking a fraction of the last item if the capacity runs out. O(n log n) — works here (unlike 0/1 knapsack) because fractional items make the greedy exchange argument valid. Q89. [H] Minimum number of platforms needed for a railway station. Sort arrival and departure times separately. Use two pointers: increment a platform counter on an arrival, decre- ment on a departure, tracking the running maximum. O(n log n) — equivalent to the “max over- lapping intervals at any point” problem. Q90. [H] Huffman encoding — build the tree and explain use case. Use a min-heap of character frequencies; repeatedly pop the two smallest, merge them into a new node with combined frequency, push back, until one node remains (the tree root). O(n log n). Use case: lossless compression — more frequent characters get shorter bit codes, minimizing total encoded length; this is the classic real-world example of a greedy algorithm with a formal optimality proof.
Q91. [E] Count the number of set bits in an integer. Brian Kernighan’s trick: repeatedly do n = n & (n-1), which clears the lowest set bit each iteration; count iterations until n becomes
Q94. [M] Implement a Min-Heap / Max-Heap from scratch. Array-backed complete binary tree: for index i, children at 2i+1, 2i+2, parent at (i-1)//2. insert: append, then “bubble up” swapping with parent while heap property is violated. extractMin/Max: swap root with last element, remove last, then “bubble down” (sift down) swapping with the smaller/larger child. Both O(log n). Q95. [M] Find the k largest elements in a stream using a heap. Maintain a min-heap of size k. For each new element, push it; if heap size exceeds k, pop the minimum. The heap always contains the k largest elements seen so far, with the smallest of them at the root. O(log k) per insertion — efficient for unbounded/streaming input since you never store more than k elements. Q96. [M] Design a Trie (prefix tree) — insert, search, startsWith. Each node holds a map/array of children (indexed by character) and an isEndOfWord flag. Insert/search/startsWith all walk character by character from the root, creating nodes as needed (insert) or returning false on a missing path (search/startsWith). O(L) time per operation where L is the word/prefix length, independent of how many words are stored. Q97. [H] Find the top-k frequent elements in an array. Count frequencies with a hashmap, then use a min-heap of size k (or bucket sort by frequency, since frequency is bounded by n) to extract the top k. Heap approach: O(n log k). Bucket sort approach: O(n), since frequencies range from 1 to n, you can bucket elements by frequency and read off the top k directly. Q98. [H] Merge k sorted arrays using a heap. Same core pattern as Q22 (merge k sorted lists): a min-heap holding (value, arrayIndex, elementIndex) triples for the current head of each array; repeatedly pop the min, push the next element from that same array. O(N log k) time where N is total elements. Q99. [H] Implement autocomplete/word suggestion using a Trie. Build a Trie of all dic- tionary words (optionally storing frequency/popularity at each end-of-word node). For a given prefix, walk to the prefix’s node, then DFS the subtree to collect all words with that prefix, sorted by frequency/popularity if ranking is required. O(prefix length + number of matches) for traversal. Q100. [H] Find the maximum XOR of two numbers in an array using a bitwise Trie. Insert every number into a Trie represented in binary (MSB to LSB, fixed width e.g. 32 bits). For each number, greedily walk the Trie trying to go the opposite bit at each level (to maximize XOR), falling back to the same bit if the opposite path doesn’t exist. Track the best XOR found. O(n · bits) time — much better than the naive O(n²) pairwise XOR comparison.
heritance” a common principle? Inheritance creates a tight “is-a” coupling to a parent’s implementation, which can break encapsulation (fragile base class problem) and lead to rigid hierarchies. Composition builds objects by holding references to other objects (“has-a”) and delegating behavior — more flexible, easier to change behavior at runtime, avoids deep frag- ile hierarchies. Modern design (e.g., Strategy pattern) generally favors composition, reserving inheritance for genuine, stable “is-a” relationships. Q110. [M] What is the difference between static binding and dynamic binding? Covered in binding terms: static binding resolves method calls at compile time based on the declared type (used for overloaded methods, private/static/final methods). Dynamic binding resolves at runtime based on the actual object type (used for overridden virtual methods), implemented via a vtable lookup. Q111. [M] What is operator overloading? Give an example and its limitations. Re- defining how an operator behaves for user-defined types (e.g., overloading + for a Vector class to add components). Limitation: it can reduce code readability/predictability if overloaded in non-intuitive ways (e.g., overloading + to perform subtraction); languages like Java deliberately disallow it to avoid this ambiguity, while C++/Python allow it with the expectation of intuitive semantics. Q112. [M] What is the difference between deep copy and shallow copy? How do you implement each? Shallow copy duplicates the top-level object but copies references to nested objects, so both copies share the same nested objects (mutating one affects the other). Deep copy recursively duplicates all nested objects too, so the two copies are fully independent. Implement shallow copy via a default copy constructor/clone(); implement deep copy by explicitly cloning each mutable field recursively (or using serialization-based deep copy as a generic fallback). Q113. [H] Explain object slicing in C++ and how to avoid it. Object slicing occurs when a derived class object is assigned to a base class object by value — the derived-specific members are “sliced off,” leaving only the base part. This silently loses polymorphic behavior. Avoid it by always passing/storing polymorphic objects through pointers or references, never by value, when polymorphism is required.
Q114. [H] What is the difference between static binding and dynamic binding? (in- ternal mechanics) Beyond the conceptual definition (Q110), dynamic binding is implemented via a vtable (virtual method table) — each object with virtual methods holds a hidden pointer to its class’s vtable, and a virtual call is resolved by looking up the method’s slot in that table at runtime, adding a small indirection overhead compared to static binding’s direct compile-time resolved call. Q115. [H] How does garbage collection interact with object lifecycle in OOP languages like Java? Objects are allocated on the heap; the GC periodically identifies unreachable objects (no live references pointing to them, traced from GC roots like stack variables/static fields) and reclaims their memory, typically via generational collection (young/old generation, since most ob- jects die young). This removes manual delete/free responsibility from the programmer but intro- duces non-deterministic collection pauses — relevant when discussing finalize()/destructors and why explicit resource cleanup (try-with-resources, Closeable) is still needed for non-memory resources like file handles.
Q116. [E] Explain the Single Responsibility Principle with an example violation and fix. A class should have exactly one reason to change. Violation: a User class that also handles saving itself to a database and sending emails — now database schema changes, email logic changes, and user field changes all force edits to the same class. Fix: split into User, UserRepository (persistence), and EmailService (notifications), each with a single responsibility.
Q117. [M] Explain the Open/Closed Principle — how do you design classes that are open
for extension but closed for modification? Classes should be extendable without modifying existing, tested code. Achieved via abstraction: define a PaymentMethod interface with a pay() method; adding a new payment type (CryptoPayment) means creating a new class implementing the interface, not editing existing PaymentProcessor logic (which would risk breaking already- working code paths). Q118. [M] Explain the Liskov Substitution Principle with a classic example (e.g., Square/Rectangle problem). Subtypes must be substitutable for their base types with- out breaking correctness. Classic violation: Square extends Rectangle and overrides setWidth/setHeight to keep both sides equal — this breaks client code that assumes setting width doesn’t change height, violating the Rectangle’s expected contract. Fix: don’t force an inheritance relationship where behavior contracts genuinely differ; model both as separate shapes implementing a common Shape interface instead. Q119. [M] Explain the Interface Segregation Principle. Clients shouldn’t be forced to depend on methods they don’t use. Violation: a fat Worker interface with work() and eat() forces a RobotWorker to implement a meaningless eat(). Fix: split into smaller, role-specific interfaces (Workable, Eatable) so classes only implement what’s relevant to them. Q120. [M] Explain the Dependency Inversion Principle and how dependency injection relates to it. High-level modules shouldn’t depend on low-level modules directly — both should depend on abstractions. E.g., a NotificationService should depend on a MessageSender inter- face, not a concrete EmailSender class, so it can work with any implementation. Dependency injection is the mechanism that supplies these abstractions (typically via constructor injection) from outside the class, rather than the class instantiating its own dependencies — this is what actually enables DIP in practice. Q121. [M] Explain the Singleton design pattern — how do you make it thread-safe? Ensures a class has exactly one instance with a global access point (private constructor + static getInstance()). Thread-safety approaches: synchronized getInstance() (simple but adds over- head on every call), double-checked locking (checks null twice, synchronizing only on first cre- ation), or the cleanest approach in Java — an enum-based singleton or a static holder class (lazy-loaded, thread-safe by class-loading guarantees, no explicit synchronization needed). Q122. [M] Explain the Factory and Abstract Factory patterns — when would you use each? Factory Method: a single method that creates objects of one product family, deferring the exact subclass to be instantiated to subclasses/parameters (e.g., ShapeFac- tory.create("circle")). Abstract Factory: a factory of factories — creates families of related objects without specifying concrete classes (e.g., a UIFactory producing matching Button+Checkbox for either a Windows or Mac look-and-feel). Use Factory Method for a single product type with variants; use Abstract Factory when you need consistent families of multiple related products. Q123. [M] Explain the Observer design pattern with a real-world use case (e.g., pub-sub systems). Defines a one-to-many dependency: when a “subject” changes state, all registered “observers” are automatically notified. Real-world use: a stock price object notifying multiple display widgets, or a YouTube channel (“subject”) notifying subscribed users (“observers”) of new uploads. It decouples the subject from the specific observer implementations — the subject only knows about a generic Observer interface. Q124. [M] Explain the Strategy design pattern and how it helps avoid large if-else chains. Encapsulates a family of interchangeable algorithms behind a common interface, letting the algorithm vary independently of the client using it. Instead of a calculatePrice() method with a giant if-else on discount type, you define a DiscountStrategy interface with multiple im- plementations (FestiveDiscount, LoyaltyDiscount), and the client just holds a reference to the current strategy and calls strategy.apply() — new discount types are added without touching existing code (also demonstrates OCP in action). Q125. [H] Explain the Decorator pattern vs Inheritance for extending behavior. Dec-
King/Queen/Rook/etc., each implementing its own isValidMove()), Player, and a Game class orchestrating turns and check/checkmate detection. Polymorphism does the heavy lifting: Board.movePiece() just calls piece.isValidMove(from, to, board) without needing to know which specific piece type it’s dealing with — a strong example of applying OOP over a large hard-coded switch statement. Q133. [H] Design a ride-sharing system’s matching/booking module (classes only, not distributed system). Core classes: Rider, Driver, Trip (status: requested/matched/ongoing/completed), Location, and a MatchingService that finds nearby available drivers (conceptually — without diving into geospatial indexing, which belongs in the HLD version). Discuss the Trip as a state machine (similar to Q130’s State pattern) and how MatchingService should be decoupled from Trip/Driver internals via clean interfaces, so the matching algorithm can be swapped independently. Q134. [H] Design a notification system supporting Email, SMS, and Push using OOP patterns. Define a NotificationChannel interface (send(message, recipient)) with EmailChan- nel, SMSChannel, PushChannel implementations — Strategy pattern for channel selection. A No- tificationService (Facade) coordinates sending through one or more channels based on user preference, and can use the Observer pattern if notifications are triggered by domain events (e.g., OrderShipped event triggers a notification). Decorator pattern is a nice extra touch for adding cross-cutting features like retries or logging around any channel implementation. Q135. [H] Design an in-memory key-value cache class with an eviction policy (e.g., LRU) using OOP. Define a Cache interface (get, put) and an EvictionPolicy interface (recordAccess, evict) so the eviction strategy (LRU, LFU, FIFO) is pluggable via Strategy pattern rather than hardcoded — internally this is the same hashmap + doubly linked list structure from Q28, but the OOP framing emphasizes designing it so a LFUCache can be built by swapping the policy implementation without touching the core Cache class.
Q136. [E] What is the difference between DBMS and RDBMS? DBMS is general soft- ware for storing/managing data (may or may not enforce relations — e.g., file-based systems). RDBMS specifically organizes data into related tables with rows/columns, enforces constraints (primary/foreign keys), and supports relationships between tables via SQL — e.g., MySQL, Post- greSQL vs a plain file-based DBMS. Q137. [E] What is a primary key vs a candidate key vs a foreign key vs a composite key? Candidate key: any column (or set of columns) that could uniquely identify a row. Primary key: the candidate key actually chosen to uniquely identify rows in a table (only one per table, can’t be null). Foreign key: a column referencing another table’s primary key, enforcing referential integrity. Composite key: a primary/candidate key made of multiple columns together, where no single column is unique alone. Q138. [E] What is normalization? Explain 1NF, 2NF, 3NF with examples. Normaliza- tion reduces data redundancy and update anomalies by organizing tables around functional de- pendencies. 1NF: atomic values only, no repeating groups (e.g., no comma-separated phone numbers in one column). 2NF: 1NF + no partial dependency on part of a composite key (every non-key column depends on the whole key). 3NF: 2NF + no transitive dependency (non-key columns depend only on the key, not on other non-key columns). Q139. [E] What is denormalization, and when would you deliberately denormalize a schema? Denormalization intentionally introduces redundancy (e.g., duplicating a customer’s name in an orders table) to reduce expensive joins and improve read performance. Use it in
read-heavy systems (analytics dashboards, reporting tables) where join cost outweighs the stor- age/consistency cost of redundant data — a classic trade-off between normalization (write con- sistency) and denormalization (read speed). Q140. [E] What is the difference between DELETE, TRUNCATE, and DROP? DELETE removes specific rows (with a WHERE clause), is logged row-by-row, can be rolled back, and fires triggers. TRUNCATE removes all rows at once, minimally logged, faster, generally can’t be rolled back in some DBs, resets auto-increment counters, and doesn’t fire row-level triggers. DROP removes the entire table structure along with its data, indexes, and constraints. Q141. [M] Explain BCNF (Boyce-Codd Normal Form) and how it differs from 3NF. BCNF is a stricter version of 3NF: for every non-trivial functional dependency X → Y, X must be a superkey. 3NF allows a specific exception where a non-prime attribute determines a prime attribute; BCNF disallows this exception entirely. In practice, most 3NF schemas are already in BCNF — the difference only shows up in tables with multiple overlapping composite candidate keys. Q142. [M] What are ACID properties? Explain each with an example scenario where it matters. Atomicity : a transaction is all-or-nothing (a bank transfer either fully completes both debit and credit, or neither). Consistency : a transaction moves the database from one valid state to another, respecting all constraints. Isolation : concurrent transactions don’t interfere with each other’s intermediate states (two people booking the last seat shouldn’t both succeed). Durability : once committed, changes survive even a crash immediately after (achieved via write- ahead logging). Q143. [M] What is the difference between clustered and non-clustered indexes? Clus- tered index physically reorders the table’s rows to match the index order — there can be only one per table (usually the primary key), and it is the table’s storage structure. Non-clustered index is a separate structure holding pointers back to the actual row locations — a table can have many. Lookups via a non-clustered index require an extra “bookmark lookup” step compared to a clustered index. Q144. [M] How does a B+ Tree index work, and why is it preferred over a plain B- Tree for databases? A B+ Tree stores all actual data (or row pointers) only in leaf nodes, with internal nodes holding only keys for navigation; leaf nodes are also linked together, enabling efficient range scans. A plain B-Tree stores data in internal nodes too, which makes range queries less efficient (no direct leaf-to-leaf traversal) and wastes space in internal nodes. B+ Trees are preferred in databases because most queries involve range scans and the linked-leaf structure supports them directly. Q145. [M] What is a database transaction? Explain the transaction states. A transaction is a logical unit of work treated atomically. States: Active (executing), Partially Committed (last statement executed, not yet persisted), Committed (changes permanently saved), Failed (an error prevented normal execution), Aborted (rolled back after failure, database restored to its prior consistent state). Q146. [M] Explain the different isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and the anomalies each prevents. Read Uncommitted : allows dirty reads (seeing uncommitted changes from other transactions) — weakest, rarely used. Read Committed : prevents dirty reads but allows non-repeatable reads (a row’s value can change between two reads in the same transaction). Repeatable Read : prevents non-repeatable reads but allows phantom reads (new rows matching a query condition can appear between reads). Serializable : strictest — transactions behave as if executed one at a time sequentially, preventing all anomalies including phantoms, at the cost of concurrency/throughput. Q147. [M] What is a deadlock in DBMS? How can it be detected and prevented? A dead- lock occurs when two or more transactions each hold a lock the other needs, creating a circular wait with no progress possible. Detection: build a wait-for graph and periodically check for cy- cles; if found, abort one transaction (the “victim,” often the one with least work done) to break
Q156. [M] What are window functions (RANK, DENSE_RANK, ROW_NUMBER)? Give an example use case. Window functions compute a value across a set of rows related to the current row (a “window,” defined via OVER (PARTITION BY ... ORDER BY ...)) without collapsing rows like GROUP BY does. ROW_NUMBER assigns unique sequential numbers; RANK assigns the same rank to ties but skips subsequent numbers; DENSE_RANK assigns the same rank to ties without skipping. Use case: ranking employees by salary within each department: RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC). Q157. [M] What is a materialized view, and how does it differ from a regular view? A regular view is just a stored query — executed fresh every time it’s referenced, always reflecting current data. A materialized view physically stores the query’s result set, offering much faster reads at the cost of staleness (must be periodically refreshed) — useful for expensive aggrega- tions in reporting/analytics workloads where slightly stale data is acceptable. Q158. [H] Explain how query execution plans work and how you’d use EXPLAIN to optimize a slow query. The query optimizer generates multiple possible execution strategies (which indexes to use, join order, join algorithm) and estimates their cost based on table statistics, picking the cheapest. EXPLAIN/EXPLAIN ANALYZE reveals the chosen plan — look for full table scans where an index scan was expected, expensive nested-loop joins on large tables, or missing index usage, and address them by adding/adjusting indexes, rewriting the query, or updating stale statistics. Q159. [H] How would you design indexes for a table that is read-heavy vs write-heavy? Read-heavy: index aggressively on commonly filtered/sorted/joined columns, including compos- ite and covering indexes, since read speed benefits outweigh the write overhead. Write-heavy: minimize indexes since every insert/update/delete must also update every index — keep only essential indexes (e.g., the primary key and columns critical for lookups), and consider defer- ring/batching index maintenance where the database supports it. Q160. [H] Explain sharding vs partitioning in databases — horizontal vs vertical. Par- titioning splits a table’s data within a single database instance (e.g., by date range) to improve manageability/performance while all partitions remain co-located. Sharding is horizontal par- titioning taken further — distributing partitions (“shards”) across multiple separate database servers/instances to scale beyond a single machine’s capacity. Vertical partitioning/splitting divides a table by columns instead (e.g., separating frequently-accessed columns from rarely- accessed large text/blob columns) rather than by rows.
Q161. [E] Write a query to find the second-highest salary from an Employee table. SELECT MAX(salary) AS second_highest FROM Employee WHERE salary < ( SELECT MAX(salary) FROM Employee);
Alternative using LIMIT/OFFSET: SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET 1; — mention DISTINCT explicitly to handle duplicate top salaries correctly. Q162. [E] Write a query to find duplicate rows in a table. SELECT name, email, COUNT() FROM Users GROUP BY name, email HAVING COUNT() > 1; Q163. [M] Write a query to find employees who earn more than their manager. SELECT e.name FROM Employee e
JOIN Employee m ON e.manager_id = m. id WHERE e.salary > m.salary; Q164. [M] Write a query to find the Nth highest salary using window functions. SELECT salary FROM ( SELECT salary, DENSE_RANK() OVER ( ORDER BY salary DESC ) AS rnk FROM Employee ) t WHERE rnk = N; Use DENSE_RANK (not ROW_NUMBER) so ties for the same salary are correctly treated as occupying the same rank. Q165. [M] Write a query to get the department-wise count of employees along with the department name. SELECT d.name, COUNT(e. id ) AS emp_count FROM Department d LEFT JOIN Employee e ON d. id = e.dept_id GROUP BY d.name; Using LEFT JOIN (not INNER) ensures departments with zero employees still appear with a count of 0. Q166. [M] Write a query to find consecutive dates/records for a given user (gaps-and- islands problem). SELECT user_id, MIN(log_date) AS start_date, MAX(log_date) AS end_date FROM ( SELECT user_id, log_date, DATE_SUB(log_date, INTERVAL ROW_NUMBER() OVER ( PARTITION BY user_id ORDER BY log_date) D FROM UserLogs ) t GROUP BY user_id, grp; Key trick: subtracting a running row number from the date collapses consecutive dates into the same “group” value, since the offset stays constant only across a consecutive run. Q167. [M] Write a query to pivot rows into columns (e.g., monthly sales per product). SELECT product_id, SUM( CASE WHEN month = 'Jan' THEN sales ELSE 0 END ) AS Jan, SUM( CASE WHEN month = 'Feb' THEN sales ELSE 0 END ) AS Feb FROM Sales GROUP BY product_id;
This conditional-aggregation pattern is portable across most SQL dialects; some (SQL Server, Oracle) also offer a native PIVOT operator as a shorthand. Q168. [H] Write a query to find the running total (cumulative sum) of sales per day. SELECT sale_date, sales, SUM(sales) OVER ( ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS runnin FROM DailySales; Q169. [H] Write a query to delete duplicate rows while keeping only one copy, without using a temp table. DELETE FROM Users WHERE id NOT IN ( SELECT MIN( id ) FROM Users GROUP BY name, email );