🏠 Hub 🎯 Interview Q&A Tier 1, 2, 3 • Question Bank
Page 1 / 25

Interview Q&A Bank — Tier 1 → Tier 3

One notebook to revise from: real questions, model answers, follow-ups & traps — tagged by the companies that ask them.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
Chip legend: Tier 1 big-tech / top-pay product Tier 2 strong product & unicorns Tier 3 services, GCCs & enterprise 🔥 hot asked very often
1

Who sits in which tier? (by interview bar, not by "quality")

T1 hardest bar T2 product + unicorns T3 services, GCCs, enterprise Google · Meta · Amazon Microsoft · Apple · Netflix Uber · Stripe · LinkedIn Atlassian · Adobe · Salesforce Flipkart · Walmart · PayPal Intuit · Swiggy · Razorpay TCS · Infosys · Wipro · HCLTech · Accenture · Cognizant · Capgemini · bank/retail GCCs
Fig 1.1 — tiers describe how hard and how wide the loop is. Prepare for the tier you target + one above.
2

What each tier actually weighs

weight in the final decision → 🧩 DSA / coding 🏗️ Design (LLD + HLD) 🗣️ Behavioral / values 📚 CS fundamentals T1T2T3 rough sketch, not a formula
Fig 1.2 — T1 = DSA + design + behaviour all strong. T2 = design-heavy (machine coding!). T3 = fundamentals, your stack & project depth.
AreaTier 1Tier 2Tier 3
Coding2 LC medium/hard per 45 min, bug-free, optimal, dry-run1–2 medium; clean, modular, extensibleEasy–medium; OA must pass all tests
LLD / OOPSometimes (Microsoft, Uber, Amazon SDE2)Core round — 90-min machine coding (Flipkart, Swiggy, Uber IN)OOP pillars, SOLID, patterns by name
HLD1–2 rounds for senior; deep trade-offs, numbers1 round; sometimes your own projectYour project architecture, basics of scaling
BehavioralDedicated round + Bar Raiser / HC / valuesValues round (Atlassian) + HM roundManagerial + HR, client-facing skills
Stack depthLanguage-agnosticSome stack questionsHeavy: C#/.NET, Java, SQL, cloud, Docker/K8s
3

How to use this notebook

📖 Read mode (default)

  • Every answer is open — read like a book.
  • Yellow box = the one insight to remember.
  • Blue box = follow-up the interviewer asks next.
  • Pink box = trap / common mistake.

🧠 Quiz mode (press Q)

  • Hides all answers. Answer aloud in 60–90 s.
  • Click the question to check yourself.
  • Your choice is remembered next visit.

🔗 Deeper theory

  • Patterns & code → DSA notebook
  • Architectures → System Design
  • Pages 19–24 = Q&A Bank II (harder DSA, more designs, production scenarios).
  • Ctrl+K searches all notebooks at once.
4

Meta questions (about the interview itself)

Q1What are interviewers really scoring in a coding round?GoogleMetaAtlassian

Answer: Four signals, almost everywhere:

  1. Problem solving — did you find an efficient approach and can you justify it (complexity, why it is correct)?
  2. Coding — readable, idiomatic, well-named, decomposed into helpers.
  3. Verification — you test your own code: dry run, edge cases, fix bugs before the interviewer points them out.
  4. Communication — you think aloud, clarify, accept hints and explain trade-offs.
💡 A correct solution with silent coding and no testing often scores lower than a slightly slower solution that was communicated and verified well.
Q2I have 8+ years of experience. How is my loop different from a fresher's?All T1All T2
  • Fewer pure-DSA rounds, more design — usually 1–2 coding, 1–2 system design, 1 LLD/machine coding (India), 1 behavioral/leadership, 1 hiring-manager round.
  • Behavioral weight goes up — scope, influence without authority, mentoring, handling ambiguity, conflict with senior stakeholders.
  • Down-levelling risk — a strong coding round with a weak design round often turns a Senior (L5/E5/SDE3) loop into an L4/SDE2 offer.
  • Project deep dive — expect 30–45 min on "the most complex system you built": numbers, failure modes, what you would change.
⚠️ Trap: preparing only LeetCode. At senior level, design + behavioral decide the level; coding only clears the bar.
Q3How many problems should I solve, and which ones?🔥 hot

Answer: Patterns beat counts. ~150 well-understood problems (Blind 75 / NeetCode 150 style) across ~15 patterns is enough for most loops if you can re-solve them cold. Track for each: the pattern, the key insight in one line, and the bug you made.

💡 Rule: if you could not solve it in 25 min, read the solution, then re-solve from scratch after 1, 3 and 7 days (spaced repetition).
Q4What changed in 2025–26 interviews because of AI?MetaGoogleMicrosoft
  • Meta began piloting an AI-enabled coding round (Oct 2025, expanding through 2026): 60 min in CoderPad with a built-in assistant, a multi-file codebase where you build, extend or debug — instead of two puzzles.
  • Google brought back at least one in-person round for many roles (to counter AI cheating), and has reportedly been piloting an AI-assisted code-comprehension round for some junior/mid roles.
  • Microsoft candidates have reported an AI-assisted coding round for some AI teams.
  • Everywhere else: remote OAs are more proctored; follow-up "explain this line" questions are more common.
↪ Formats are pilots and vary by team/level — always ask your recruiter "what is the exact loop, and is any round AI-assisted?" See page 16 for how to perform in AI rounds.
🎯 The one-line strategy
Clear the coding bar with patterns (pages 3–6, 19–20), win the level with design (pages 10–13, 21–22), and win the offer with stories (pages 17–18, 24).

Company Interview Loops — 2025–26 Edition

Compiled from recent candidate reports & prep guides. Formats change by team and level — confirm with your recruiter.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

The shape of a loop, by tier

T1 recruiter OA / screen onsite 4–5 roundscode · design · behav. HC / debrief offer Bar Raiser (Amazon) · Hiring Committee + team match (Google) T2 machine coding DSA ×1–2 LLD / HLD HM + values offer machine coding is often an elimination round — fail it and the loop stops T3 OA (sometimes) tech ×1–2 (stack) managerial HR offer + client round at times
Fig 2.1 — T1 = breadth + committee. T2 = build-it-live first. T3 = your stack, your project, then managerial + HR.
2

Tier 1 — round by round

CompanyTypical senior loopWhat is unique
GoogleRecruiter → 1 technical screen → onsite: 2–3 coding, 1–2 system design (L5+), 1 Googleyness & Leadership → Hiring Committee → team matchScored on GCA, RRK, Leadership, Googleyness. At least one round back in person for many roles. G&L may include a design chat on your past work. Code often not executed — dry-run matters.
MetaRecruiter → screen (≈2 problems / 45 min) → onsite: 1 classic coding + 1 AI-enabled coding (pilot), 1–2 system/product design, 1 behavioralSpeed: 2 mediums in 35–40 min. AI round = 60 min multi-file codebase (build / extend / debug) with a chosen model. Level set mostly by design + behavioral.
AmazonOA (coding + work-style) → phone screen → loop of 4–5 × 60 min → debriefEvery round has Leadership-Principle questions (≈ half the time). A Bar Raiser from another org can veto. SDE2+ gets system design; OOD/LLD common.
MicrosoftScreen → loop of 3–4 (DSA, LLD, HLD, behavioral mixed in) → AA round"As Appropriate" = senior leader, final call. India loops often: DSA → LLD → HLD → managerial. Some AI teams add an AI-assisted coding round.
UberScreen (1 medium, ~20 min, working code) → DSA (graphs/DP) → machine coding / LLD → system design → HMHM round weighs heavily for senior. LLD examples: cart system, parking lot — runnable, extensible code.
Apple / NetflixTeam-run loops, 5–8 interviews, very domain specificApple: deep on your area. Netflix: mostly senior hiring, culture memo (freedom & responsibility, candor) drives behavioral.
3

Tier 2 & Tier 3 — round by round

CompanyTypical loopWhat is unique
FlipkartMachine coding (≈30 min brief + 90 min build, proctored) → PSDS (2 LC mediums) → design (LLD/HLD) → HM / techno-managerialMachine coding is usually the gate. Graded on working code, SOLID, patterns, extensibility, tests. Seen: food ordering, BookMyShow, parking lot, property management.
AtlassianScreen (sometimes Karat) → code design → data structures → system design → management/leadership → values → hiring committeeCode design = build & extend a small real system (rate limiter, file-size report, snake game, feature flags). Values round can fail strong engineers.
Adobe · Salesforce · Walmart · PayPalOA → 2 DSA → LLD/HLD → HM → HRBalanced loops; DSA medium, LLD in Java/C#-style OOP, solid CS fundamentals.
IntuitOA/screen → Craft Demo (build something, then present + extend) → HM/behavioralYou are judged on code you wrote at home and how you defend and extend it live.
Swiggy · Zomato · Razorpay · PhonePeMachine coding → DSA → HLD → HMStartup pace: practical design (payments idempotency, order state machines, geo search).
TCS · Infosys · Wipro · HCLTechRecruiter → 1–2 technical (stack + project + SQL) → managerial → HRDeep stack questions (C#/.NET, Java, Spring, SQL, Azure/AWS, Docker), scenario questions, estimation & delivery.
Accenture · Cognizant · CapgeminiSometimes OA → tech → managerial/HR (combined) → sometimes client roundClient round: communication, ownership, how you handle production issues and changing requirements.
Bank / retail GCCsHackerRank OA → 2 technical → HMMedium DSA + strong design of your current system, code quality, testing & security practices.
4

Loop questions you should be able to answer

Q1What is a Bar Raiser and how do I "pass" one?Amazon

Answer: A trained interviewer from outside the hiring team whose job is to ensure every hire is better than 50% of current people at that level. They usually probe Leadership Principles deeply and can veto.

  • Expect 3–5 follow-ups per story: "What exactly did you do?", "What data?", "What would you do differently?"
  • Use real numbers (latency, cost, % improvement, team size, dates).
  • Have 2 stories per principle so you never repeat one in the same loop.
⚠️ "We decided…" without your own action = weak signal. Say "I".
Q2How does Google's hiring committee and team match work?Google

Answer: Interviewers write detailed feedback + a score. A hiring committee (people who did not interview you) reads the packet and decides hire/no-hire and level. Then you go through team matching (calls with managers) before the final offer and comp review.

💡 Because strangers read your packet, the interviewer must be able to write down your reasoning — think aloud, state complexity, name your test cases.
Q3What is a machine coding round and how is it graded?FlipkartUberSwiggyRazorpay

Answer: You get a problem statement (e.g. "Splitwise", "parking lot", "food ordering") and ~90–120 minutes to build a working, runnable program — usually in-memory, no DB/UI. Graded on:

  1. It runs and handles the main flows + edge cases (demo via a driver/main or tests).
  2. Modelling — right entities, clear responsibilities, no god class.
  3. Extensibility — new requirement (new pricing rule, new split type) added without rewriting: Strategy/Factory, interfaces.
  4. Code hygiene — naming, packages/folders, exceptions, no hard-coding.
  5. Concurrency awareness when relevant (double booking).
↪ Full walkthroughs on page 11.
Q4What are Atlassian's values, and how do I prepare for the values round?Atlassian

Answer: Five values:

  1. Open company, no bullshit — transparency, candid feedback (e.g. "feedback to a senior stakeholder").
  2. Build with heart and balance — quality vs speed trade-offs, sustainable pace.
  3. Don't #@!% the customer — customer impact first.
  4. Play, as a team — collaboration, helping others succeed.
  5. Be the change you seek — you fixed a broken process yourself.

Prepare 1–2 STAR stories per value; the interviewer is usually outside the team, so explain context simply.

Q5What do service companies ask experienced (lateral) candidates?TCSInfosysAccentureCognizant
  • Technical: your stack in depth (C#/.NET: DI, middleware, async, EF Core; SQL joins/indexes; REST; Azure/AWS; Docker), plus 1–2 easy/medium coding questions.
  • Project: architecture diagram of your current project, your role, a production incident you handled.
  • Scenario: "API is slow in production — what do you do?", "Client changes requirement mid-sprint?"
  • Managerial: estimation, team handling, conflict, Agile ceremonies, client communication.
  • HR: current/expected CTC, notice period, relocation, reason for change.
Q6What should I ask the recruiter before the loop?🔥 everyone
  • Exact rounds, order and duration; which ones are elimination rounds?
  • Language allowed? Code executed or not? Any AI-assisted round?
  • Which level am I being considered for? Is system design 1 or 2 rounds?
  • For machine coding: IDE allowed? Internet? Expected deliverable (main method / tests)?
  • Can I reschedule if I need one more week of prep? (Almost always yes.)
🎯 Takeaway
Prepare for the format, not just the topics: 2 problems in 40 min (Meta), 90-min build (Flipkart), LP story in every round (Amazon), values round (Atlassian), stack depth (services).

Arrays, Strings, Hashing & Sliding Window

The most-asked family across all three tiers — the warm-up in T1 and often the whole round in T3.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Hear the keyword → pick the pattern

if the problem says…reach for… "pair / complement / seen before" hash map (value → index) "subarray sum = k / count ranges" prefix sum + map {0:1} "longest / shortest substring with…" sliding window (grow R, shrink L) "sorted array / pair / triplet" two pointers from both ends "max contiguous sum" Kadane (extend or restart)
Fig 3.1 — say the pattern name out loud in the interview: "this smells like a sliding window because…"
2

Hashing & prefix sums

Q1Two Sum — return indices of two numbers that add to target.🔥AmazonGoogleAdobeTCSInfosys

Answer: Walk once; for each x check whether target - x was seen. Store value → index after the check (so an element is not paired with itself). O(n) time, O(n) space.

var seen = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++) {
    if (seen.TryGetValue(target - nums[i], out var j)) return new[] { j, i };
    seen[nums[i]] = i;
}
return Array.Empty<int>();
↪ Sorted input? → two pointers, O(1) space. All pairs / count pairs? → map of counts. Stream of numbers? → keep the map, answer per arrival.
Q2Subarray Sum Equals K (array has negatives).🔥MetaGoogleAtlassian

Answer: sum(i..j) = prefix[j] − prefix[i−1]. So at each position, the number of subarrays ending here with sum k = how many earlier prefixes equal prefix - k. Seed the map with {0: 1} (the empty prefix). O(n) / O(n).

var count = new Dictionary<int, int> { [0] = 1 };
int sum = 0, ans = 0;
foreach (var x in nums) {
    sum += x;
    ans += count.GetValueOrDefault(sum - k);
    count[sum] = count.GetValueOrDefault(sum) + 1;
}
⚠️ Sliding window does not work here — negatives break the "shrink when too big" rule. Say this explicitly; interviewers love it.
Q3Product of Array Except Self — without division, O(n).AmazonMetaMicrosoftAdobe

Answer: answer[i] = (product of everything left of i) × (product of everything right of i). Pass 1 fills left products into the output; pass 2 walks from the right with a running suffix product. O(n) time, O(1) extra (output array not counted).

var res = new int[n]; res[0] = 1;
for (int i = 1; i < n; i++) res[i] = res[i - 1] * nums[i - 1];
int right = 1;
for (int i = n - 1; i >= 0; i--) { res[i] *= right; right *= nums[i]; }
↪ "Why not divide?" — zeros (one zero / two zeros cases) and overflow. Mention both.
Q4Longest Consecutive Sequence in O(n).GoogleAmazonWalmart

Answer: Put all numbers in a HashSet. Only start counting from x when x - 1 is not in the set (x is a sequence start), then walk x+1, x+2… Each number is visited at most twice → O(n).

⚠️ Sorting gives O(n log n) — fine as a first answer, but the question says O(n).
Q5Group Anagrams.AmazonMetaSalesforceCognizant

Answer: Map a canonical key → list of words. Key = sorted letters (O(k log k) per word) or a 26-count signature like "1#0#2#…" (O(k)). Total O(n·k) with counts.

↪ Unicode input? → use Dictionary<char,int> signature or sorted string, not a 26-array.
3

Kadane, stock & two pointers

Q6Maximum Subarray (Kadane's algorithm).🔥MicrosoftAmazonTCSWipro

Answer: At each element decide: extend the previous subarray or restart here — cur = max(x, cur + x). Track the best. O(n) / O(1). Works for all-negative arrays (answer = largest element).

int best = nums[0], cur = 0;
foreach (var x in nums) {
    cur = Math.Max(x, cur + x);   // extend or restart
    best = Math.Max(best, cur);
}
↪ Return the indices too → remember start when you restart. Max product subarray → track both max and min (a negative flips them).
Q7Best Time to Buy and Sell Stock (one transaction).AmazonMetaFlipkartAccenture

Answer: Track the minimum price so far; profit if sold today = price − min. Keep the max. O(n) / O(1).

↪ Unlimited transactions → sum every positive day-to-day rise (greedy). At most k transactions / cooldown / fee → DP with states (holding, not holding).
Q83Sum — all unique triplets summing to 0.🔥MetaAmazonAdobe

Answer: Sort. For each i (skip if same as previous), run two pointers L = i+1, R = end: sum < 0 → L++, sum > 0 → R--, else record and move both, skipping duplicates. O(n²) time, O(1) extra (ignoring sort).

⚠️ The duplicate-skipping is the whole question — do it for i, L and R. Early exit when nums[i] > 0.
Q9Trapping Rain Water.🔥GoogleAmazonUberAdobe

Answer: Water above i = min(maxLeft, maxRight) − height[i]. Two pointers: move the side with the smaller max, because that side's water is already decided by its own max. O(n) / O(1).

int L = 0, R = h.Length - 1, lMax = 0, rMax = 0, water = 0;
while (L < R) {
    if (h[L] < h[R]) { lMax = Math.Max(lMax, h[L]); water += lMax - h[L]; L++; }
    else            { rMax = Math.Max(rMax, h[R]); water += rMax - h[R]; R--; }
}
↪ Alternatives to mention: prefix/suffix max arrays (O(n) space), monotonic stack (counts water layer by layer). Container With Most Water is the cousin: move the shorter wall.
Q10Sort Colors (0s, 1s, 2s) in one pass.MicrosoftTCSInfosysCapgemini

Answer: Dutch National Flag: pointers lo, mid, hi. 0 → swap with lo, lo++, mid++. 1 → mid++. 2 → swap with hi, hi-- (do not advance mid — the swapped-in value is unchecked). O(n) / O(1).

4

Sliding window

Q11Longest Substring Without Repeating Characters.🔥AmazonGoogleFlipkartInfosys

Answer: Window [L, R]. Remember last index of each char; when s[R] was seen inside the window, jump L past it. O(n) time, O(alphabet) space.

var last = new Dictionary<char, int>();
int L = 0, best = 0;
for (int R = 0; R < s.Length; R++) {
    if (last.TryGetValue(s[R], out var p) && p >= L) L = p + 1;  // p >= L: only if inside window
    last[s[R]] = R;
    best = Math.Max(best, R - L + 1);
}
Q12Minimum Window Substring (contains all chars of t).MetaGoogleUberAtlassian

Answer: Count what we need. Grow R; when a needed char arrives, missing--. While missing == 0 the window is valid → record, then shrink L; if removing s[L] makes it needed again, missing++. O(|s| + |t|).

var need = new int[128]; foreach (var c in t) need[c]++;
int missing = t.Length, L = 0, bestL = 0, bestLen = int.MaxValue;
for (int R = 0; R < s.Length; R++) {
    if (need[s[R]]-- > 0) missing--;
    while (missing == 0) {
        if (R - L + 1 < bestLen) { bestLen = R - L + 1; bestL = L; }
        if (++need[s[L++]] > 0) missing++;
    }
}
return bestLen == int.MaxValue ? "" : s.Substring(bestL, bestLen);
💡 Generic window template: grow R → while invalid (or valid, for "minimum") shrink L → update answer. Longest = update after shrinking; shortest = update while shrinking.
Q13Longest Repeating Character Replacement (at most k changes).GoogleUberAtlassian

Answer: Window is valid if windowLen - maxFreq ≤ k (chars we must change). Grow R, update counts and maxFreq; if invalid, move L by one. O(n). maxFreq never needs to decrease — the answer only grows when a bigger maxFreq appears.

Bugs interviewers see every day
  • Forgetting {0: 1} in prefix-sum counting.
  • Using sliding window when the array has negatives.
  • Not skipping duplicates in 3Sum (or skipping too early and losing answers).
  • Off-by-one in window length: it is R - L + 1.
  • int overflow on sums/products — mention long.
✅ Do these cold before any loop
  • Two Sum / Two Sum II E
  • Contains Duplicate / Valid Anagram E
  • Top K Frequent Elements M
  • Encode & Decode Strings M
  • Valid Sudoku M
  • Rotate Image / Spiral Matrix M
  • Next Permutation M
  • Permutation in String M
  • Sliding Window Maximum H
  • First Missing Positive H

Linked Lists, Stacks, Binary Search, Heaps & Intervals

Pointer surgery, "next greater", "search the answer", "top K" and "overlapping ranges".
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Linked lists

Q1Reverse a linked list — iteratively and recursively.🔥MicrosoftAmazonTCSInfosysWipro

Answer: Iterative: three pointers prev, cur, next; flip one arrow per step. O(n) / O(1). Recursive: reverse the rest, then make head.next.next = head, head.next = null. O(n) stack.

ListNode prev = null, cur = head;
while (cur != null) {
    var next = cur.next;   // 1. save
    cur.next = prev;       // 2. flip
    prev = cur;            // 3. advance prev
    cur = next;            // 4. advance cur
}
return prev;
↪ Reverse in groups of k, reverse between positions m..n, palindrome list (reverse 2nd half, compare, restore).
Q2Detect a cycle and return the node where it starts. Why does Floyd's trick work?AmazonMicrosoftAdobeCognizant
H S a steps M b steps c steps back to S slow: a + b fast: 2(a + b) ⇒ a + b = k·L ⇒ a = c (mod L)
Fig 4.1 — after they meet at M, walk one pointer from H and one from M at the same speed: they meet at S.

Answer: slow moves 1, fast moves 2. If they meet, there is a cycle. Slow walked a + b; fast walked twice that, i.e. a full number of extra loops: a + b = k·L. So a = k·L − b = c + (k−1)·L — walking a steps from the head lands on the start, same as walking c steps from M. O(n) / O(1).

Q3Merge K sorted lists.🔥AmazonGoogleMetaUber

Answer: Min-heap holding the current head of each list. Pop smallest, append, push its next. N total nodes, k lists → O(N log k) time, O(k) space. Alternative: divide & conquer pairwise merge — same complexity, no heap.

var pq = new PriorityQueue<ListNode, int>();
foreach (var l in lists) if (l != null) pq.Enqueue(l, l.val);
var dummy = new ListNode(); var tail = dummy;
while (pq.TryDequeue(out var node, out _)) {
    tail = tail.next = node;
    if (node.next != null) pq.Enqueue(node.next, node.next.val);
}
return dummy.next;
Q4Remove N-th node from end in one pass?MetaTCS
Dummy head; move fast n+1 steps, then move both until fast is null; slow.next = slow.next.next. Dummy handles removing the head.
Q5Intersection of two lists?AmazonAdobe
Two pointers; when one reaches the end, jump to the other list's head. Both travel a + b + c and meet at the intersection (or both null).
Q6Copy list with random pointer?MetaAmazon
Map old → new (O(n) space), or interleave clones A→A'→B→B', set A'.random = A.random.next, then unweave (O(1) extra).
Q7Design an LRU cache?🔥AmazonAtlassianSalesforce
HashMap key → node + doubly linked list with dummy head/tail; touch = move to head, evict = tail.prev. All O(1). Full C# in DSA notes p.5. Thread-safe? → lock around ops or striped locks.
2

Stacks & monotonic stacks

Q8Valid Parentheses.🔥AmazonMetaTCSAccenture

Answer: Push openers; on a closer, the top must be its matching opener, else false. At the end the stack must be empty. O(n). Quick reject: odd length.

↪ Min removals to make valid (Meta favourite): count unmatched ")" while scanning and unmatched "(" left over — remove those indices.
Q9Daily Temperatures / Next Greater Element.GoogleAmazonFlipkart

Answer: Keep a stack of indices with decreasing temperatures. For each day, pop while today is warmer — each popped day's answer is i - popped. Each index is pushed and popped once → O(n).

var st = new Stack<int>(); var ans = new int[t.Length];
for (int i = 0; i < t.Length; i++) {
    while (st.Count > 0 && t[i] > t[st.Peek()]) { int j = st.Pop(); ans[j] = i - j; }
    st.Push(i);
}
↪ Same pattern: Largest Rectangle in Histogram, Stock Span, Remove K Digits, Sum of Subarray Minimums.
Q10Design a Min Stack (getMin in O(1)).AmazonWalmartInfosys

Answer: Store pairs (value, minSoFar) on one stack, or keep a second stack that pushes when a value ≤ current min. All ops O(1).

3

Binary search

Q11Search in Rotated Sorted Array.🔥MetaMicrosoftAdobePayPal

Answer: One half around mid is always sorted. If nums[lo] ≤ nums[mid] the left half is sorted: target in [lo, mid) → go left, else right. Otherwise the right half is sorted — mirror it. O(log n).

⚠️ With duplicates, nums[lo] == nums[mid] is ambiguous → lo++; worst case becomes O(n). Say it.
Q12Koko Eating Bananas / Ship Packages in D Days — "binary search on the answer".GoogleAmazonFlipkart

Answer: The answer (speed / capacity) lives in a range [lo, hi], and feasible(x) is monotonic (if x works, x+1 works). Binary search for the smallest feasible x. Cost: O(n · log range).

int lo = 1, hi = piles.Max();
while (lo < hi) {
    int mid = lo + (hi - lo) / 2;
    if (Hours(mid) <= h) hi = mid;   // feasible → try smaller
    else lo = mid + 1;
}
return lo;
💡 Recognise it by "minimum maximum" / "smallest capacity such that…". Template details: DSA notes p.6.
Q13Median of Two Sorted Arrays in O(log(min(m,n))).GoogleAmazonApple

Answer: Binary search a cut i in the smaller array; the cut in the other is j = (m + n + 1)/2 − i. Valid when A[i−1] ≤ B[j] and B[j−1] ≤ A[i] (use ±∞ at the edges). Then median = max of left side (odd) or average of max-left and min-right (even).

↪ If you blank: say the O(m+n) merge first — partial credit beats silence — then derive the partition.
4

Heaps & intervals

Q14Kth Largest Element — heap or quickselect?🔥MetaAmazonWalmartTCS

Answer: Min-heap of size k: push each, pop when size > k; the top is the answer. O(n log k), O(k) — works on streams. Quickselect: partition around a random pivot, recurse into one side — O(n) average, O(n²) worst, in-place.

↪ Top K Frequent: count with a map, then heap of size k, or bucket sort by frequency (O(n)).
Q15Find Median from Data Stream.GoogleAmazonUber

Answer: Two heaps: a max-heap for the lower half, a min-heap for the upper half. Add to lower, move lower's top to upper, rebalance so lower has equal or one more. Median = lower.top or the average of both tops. add O(log n), median O(1).

↪ Values in 0..100 only → counting array, O(100) median. 99% in range → counts + two overflow heaps.
Q16Merge Intervals & Meeting Rooms II (min rooms needed).🔥GoogleMetaAmazonAtlassian

Answer — Merge: sort by start; if current start ≤ last merged end, extend end = max(end, cur.end), else append. O(n log n).

Answer — Rooms: sort by start; min-heap of end times. For each meeting, if heap top ≤ start, pop (room freed). Push its end. Answer = max heap size. Or sweep line: sorted starts and ends with two pointers.

⚠️ Clarify: is [1,3] and [3,5] overlapping? (Usually touching = not overlapping for rooms.)
✅ Practice set
  • Linked List Cycle II M
  • Reorder List M
  • Reverse Nodes in k-Group H
  • Largest Rectangle in Histogram H
  • Evaluate Reverse Polish Notation M
  • Find Peak Element M
  • Split Array Largest Sum H
  • Task Scheduler M
  • Insert Interval M
  • Non-overlapping Intervals M

Trees, Tries & Graphs

Meta and Google's favourite territory. Every tree answer starts with: "what does each node return to its parent?"
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Binary trees & BSTs

Q1Diameter of a Binary Tree.🔥MetaGoogleAtlassian

Answer: DFS returns the node's height to its parent; while there, update a global best with left + right (the longest path that bends at this node). O(n) time, O(h) stack.

int best = 0;
int Height(TreeNode n) {
    if (n == null) return 0;
    int l = Height(n.left), r = Height(n.right);
    best = Math.Max(best, l + r);      // path through n (edges)
    return 1 + Math.Max(l, r);         // what the parent needs
}
💡 Same "return one thing, record another" shape solves Max Path Sum (return max(0, gain)), Balanced Tree (return −1 if unbalanced) and Longest Univalue Path.
Q2Validate a Binary Search Tree.AmazonMicrosoftAdobeInfosys

Answer: Pass down an allowed range (min, max): left child gets (min, node.val), right gets (node.val, max). Or do an inorder walk and check strictly increasing. O(n).

⚠️ Classic wrong answer: only checking left.val < node.val < right.val. A grandchild can break the rule. Use long bounds (or nullable) for int.MinValue/MaxValue nodes.
Q3Lowest Common Ancestor — binary tree and BST.🔥MetaAmazonMicrosoftFlipkart

BST: walk from root — both smaller → go left, both bigger → go right, else this node is the LCA. O(h).

Binary tree: recurse; if node is p or q return it. If both left and right return non-null, this node is the LCA; else bubble up the non-null side. O(n).

↪ Nodes have parent pointers → it becomes "intersection of two linked lists". p or q may not exist → count found nodes.
Q4Level Order Traversal / Right Side View / Zigzag.MetaAmazonTCSCognizant

Answer: BFS with a queue; freeze int size = q.Count at the start of each level and process exactly that many. Right side view = last node of each level. Zigzag = reverse every other level (or insert at front).

Q5Serialize and Deserialize a Binary Tree.GoogleMetaAmazonUber

Answer: Preorder with null markers: "1,2,#,#,3,4,#,#,5,#,#". Deserialize by reading tokens with a shared index/queue: token "#" → null, else create node, build left, build right. O(n) both ways.

↪ BST only? → no null markers needed: preorder + (min, max) bounds rebuild it. Why not inorder alone? Not unique.
Q6Binary Tree Maximum Path Sum.GoogleMetaAmazon

Answer: Each node returns its best downward gain val + max(0, max(leftGain, rightGain)). Update global with val + max(0,L) + max(0,R). Initialise global to int.MinValue (all-negative trees). O(n).

Q7Implement a Trie; then Word Search II.GoogleAmazonUberAtlassian

Trie: node = children map/array[26] + isEnd. insert/search/startsWith are all O(L).

Word Search II: build a trie of the words, DFS from every board cell following trie edges; store the word at the end node, add it to results and null it out (dedupe). Prune leaf nodes as words are found — big speed-up.

↪ Autocomplete with top-3 suggestions → store top-k at each node, or sort + binary search on prefix.
2

Graphs — pick the algorithm

graph problem? shortest path"before / after""connected?"explore / count weights? Topo sort (Kahn) Union-Find (DSU) DFS / BFS flood none → BFS ≥ 0 → Dijkstra < 0 → Bellman-Ford 0/1 weights → 0-1 BFS (deque) · all pairs, V ≤ 400 → Floyd-Warshall also MST (Kruskal), cycle in undirected cycle in directed = leftover nodes
Fig 5.1 — name the algorithm and why: "weights are non-negative, so Dijkstra's greedy pop is safe".
Q8Number of Islands.🔥MetaAmazonGoogleFlipkartTCS

Answer: Scan the grid; on each unvisited '1', count++ and flood-fill (DFS/BFS) marking the island visited. O(R·C). DFS recursion can overflow on a 1000×1000 all-land grid → use BFS or an explicit stack.

↪ Islands added one by one (Number of Islands II) → DSU, O(α) per addition. Count distinct shapes → serialize the DFS path relative to the start.
Q9Course Schedule I & II (can all courses be finished? in what order?).🔥GoogleAmazonMetaUber

Answer: Directed graph prereq → course. Kahn's algorithm: queue all in-degree-0 nodes; pop, append to order, decrement neighbours, enqueue those that hit 0. If order has fewer than V nodes → cycle → impossible. O(V + E).

var q = new Queue<int>(Enumerable.Range(0, n).Where(i => indeg[i] == 0));
var order = new List<int>();
while (q.Count > 0) {
    int u = q.Dequeue(); order.Add(u);
    foreach (var v in adj[u]) if (--indeg[v] == 0) q.Enqueue(v);
}
return order.Count == n ? order : new List<int>();   // empty = cycle
Q10Rotting Oranges / Walls and Gates (multi-source BFS).AmazonMicrosoftSwiggy

Answer: Put all sources (rotten oranges) into the queue at time 0, BFS level by level; minutes = number of levels. If fresh oranges remain → −1. O(R·C).

Q11Word Ladder (shortest transformation sequence).GoogleAmazonMeta

Answer: BFS where nodes are words and edges differ by one letter. Generate neighbours by trying 26 letters at each position (O(L·26)) or by wildcard buckets h*t → [hot, hit]. Remove from the word set when enqueued. O(N·L²) with string building. Bidirectional BFS cuts the search a lot.

Q12Dijkstra — Network Delay Time. Why does it fail with negative edges?GoogleUberFlipkartSwiggy

Answer: Min-heap of (dist, node). Pop the closest; skip if stale (d > dist[u]); relax edges and push improved distances. O((V + E) log V). It assumes once a node is popped its distance is final — a later negative edge could make it shorter, breaking that guarantee. Use Bellman-Ford (O(V·E)) for negatives, and it also detects negative cycles.

↪ "Cheapest flight with at most K stops" → Bellman-Ford limited to K+1 rounds, or BFS by stops with a dist copy per round.
Q13Clone Graph?MetaGoogle
DFS/BFS with a map original → clone. Create the clone when first seen, then wire neighbours. The map doubles as "visited".
Q14Accounts Merge / Redundant Connection?MetaGoogle
Union-Find with path compression + union by size. Redundant edge = the first edge whose endpoints already share a root. Accounts: union emails, group by root.
Q15Detect a cycle — directed vs undirected?MicrosoftInfosys
Undirected: DFS seeing a visited node that is not the parent, or DSU. Directed: DFS with 3 colours (white/grey/black) — reaching a grey node = back edge = cycle; or Kahn leftovers.
Q16Alien Dictionary?MetaGoogleUber
Compare adjacent words; the first differing char gives an edge a → b. Topo sort the letters. Invalid if a word is followed by its own prefix (e.g. "abc" before "ab") or there is a cycle.
✅ Practice set
  • Invert / Symmetric Tree E
  • Construct Tree from Preorder + Inorder M
  • Kth Smallest in BST M
  • Vertical Order Traversal H
  • Pacific Atlantic Water Flow M
  • Graph Valid Tree M
  • Cheapest Flights Within K Stops M
  • Swim in Rising Water H
  • Min Cost to Connect All Points (MST) M
  • Shortest Path in Binary Matrix M

Dynamic Programming, Backtracking & Greedy

Google's favourite family. Say the 5 DP steps out loud: state → recurrence → base case → order → answer.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

DP concepts they ask before the code

Q1How do you recognise that a problem needs DP?GoogleAdobeTCS

Answer: Two properties: optimal substructure (the best answer is built from best answers of smaller sub-problems) and overlapping sub-problems (the plain recursion solves the same sub-problem many times). Trigger words: "number of ways", "min/max cost", "can you reach / is it possible", "longest/shortest … subsequence".

💡 Script: "Brute force tries every choice — exponential. Many branches repeat the same (i, j) state, so I'll memoise on (i, j): states × work per state."
Q2Memoization vs tabulation — which and why?AmazonInfosysWipro
Memoization (top-down)Tabulation (bottom-up)
HowRecursion + cacheLoops fill a table in dependency order
ProsNatural to derive; only computes reachable statesNo recursion depth risk; easy space optimisation (rolling rows)
ConsStack overflow on deep inputs; call overheadMust figure out the order; computes all states

Interview strategy: derive top-down, then convert to bottom-up and compress space if asked.

2

Classic DP questions

Q3House Robber (no two adjacent houses).AmazonGoogleCognizant

Answer: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) — skip house i or rob it. Only two previous values matter → O(n) / O(1). Circular street (House Robber II): answer = max(rob 0..n−2, rob 1..n−1).

Q4Coin Change (fewest coins) vs Coin Change II (number of ways).🔥AmazonGooglePayPalWalmart

Fewest: dp[a] = min over coins c of dp[a - c] + 1, dp[0] = 0, unreachable = ∞ → return −1. O(A · C).

Ways: dp[0] = 1; outer loop coins, inner loop amounts → counts combinations (1+2 same as 2+1).

var dp = new int[amount + 1]; dp[0] = 1;
foreach (var c in coins)                 // coins OUTSIDE → combinations
    for (int a = c; a <= amount; a++)
        dp[a] += dp[a - c];
⚠️ Swap the loops (amount outside) and you count permutations — that is Combination Sum IV. Interviewers ask exactly this.
↪ Why not greedy (largest coin first)? Coins {1, 3, 4}, amount 6: greedy 4+1+1 = 3 coins; optimal 3+3 = 2.
Q5Longest Increasing Subsequence — O(n²) and O(n log n).🔥GoogleMicrosoftAtlassian

O(n²): dp[i] = 1 + max(dp[j]) for j < i with nums[j] < nums[i].

O(n log n): keep tails[k] = smallest possible tail of an increasing subsequence of length k+1. For each x, binary-search the first tail ≥ x and replace it (or append). Length of tails = answer.

var tails = new List<int>();
foreach (var x in nums) {
    int i = tails.BinarySearch(x);
    if (i < 0) i = ~i;                       // insertion point = first ≥ x
    if (i == tails.Count) tails.Add(x); else tails[i] = x;
}
return tails.Count;
⚠️ tails is not the actual subsequence. To print one, keep parent indices.
↪ Russian Doll Envelopes = sort by width asc, height desc, then LIS on heights.
Q6Edit Distance (insert / delete / replace).GoogleAmazonMicrosoft

Answer: dp[i][j] = edits to turn first i chars of a into first j chars of b. Same char → dp[i-1][j-1]; else 1 + min(replace dp[i-1][j-1], delete dp[i-1][j], insert dp[i][j-1]). Base: dp[i][0] = i, dp[0][j] = j. O(m·n), O(n) with two rows.

a \ b""ros
""0123
h1123
o2212
r3222
s4332
e5443 ✓

"horse" → "ros" = 3 (replace h→r, delete r, delete e). Green cells = characters matched diagonally.

↪ LCS is the same grid: match → 1 + diagonal, else max(up, left).
Q7Word Break.🔥MetaAmazonGoogleUber

Answer: dp[i] = can s[0..i) be segmented. dp[0] = true; dp[i] = any j < i with dp[j] and s[j..i) in the dictionary (HashSet). Limit j to the max word length. O(n · maxLen) substring checks.

↪ Word Break II (return all sentences) → memoised DFS returning lists; output can be exponential.
Q8Partition Equal Subset Sum (0/1 knapsack).MetaAmazonAdobe

Answer: Odd total → false. Target = total/2; boolean dp[s] = some subset sums to s. For each number, iterate s downwards from target to num: dp[s] |= dp[s - num]. O(n · target).

⚠️ Iterating upwards reuses the same item (that's the unbounded knapsack). Downwards = each item once.
Q9Longest Palindromic Substring?AmazonMicrosoftTCS
Expand around each of the 2n−1 centres (odd and even) — O(n²) time, O(1) space. Simpler than the DP table; Manacher is O(n) but rarely expected.
Q10Unique Paths / Minimum Path Sum?GoogleAccenture
Grid DP: dp[r][c] = dp[r-1][c] + dp[r][c-1] (or min + cost). One row is enough. Unique paths has a closed form C(m+n−2, m−1).
Q11Decode Ways ("226" → 3)?MetaUber
dp[i] += dp[i−1] if s[i−1] ≠ '0'; dp[i] += dp[i−2] if s[i−2..i) is 10–26. Leading '0' → 0 ways. O(n), two variables.
Q12Longest Common Subsequence?AmazonAdobe
Match → 1 + dp[i−1][j−1], else max(dp[i−1][j], dp[i][j−1]). O(m·n). Used in diff tools (follow-up: "how does git diff work?").
3

Backtracking

[ ] take 1skip 1 [1] [ ] +2−2 [1,2] [1] [2] [ ] [1,2,3][1,2] [1,3][1] [2,3][2] [3][ ] 2ⁿ leaves · each leaf is one subset
Fig 6.1 — draw this tree for the interviewer: it proves the O(2ⁿ · n) bound and shows where pruning cuts branches.
Q13Subsets, Permutations, Combination Sum — one template?🔥MetaAmazonUberInfosys

Answer: Choose → explore → un-choose.

void Backtrack(int start, List<int> path) {
    result.Add(new List<int>(path));          // subsets: record every node
    for (int i = start; i < nums.Length; i++) {
        if (i > start && nums[i] == nums[i - 1]) continue;  // skip dups (sorted)
        path.Add(nums[i]);                       // choose
        Backtrack(i + 1, path);                  // explore (i, not i+1, to reuse: Combination Sum)
        path.RemoveAt(path.Count - 1);           // un-choose
    }
}
  • Permutations: loop from 0 every time, use a used[] array; record only when path.Count == n. O(n · n!).
  • Combination Sum: recurse with i (reuse allowed), stop when remaining < 0; sort and break early when nums[i] > remaining.
Q14N-Queens and Word Search.AmazonMicrosoftAdobe

N-Queens: place row by row; keep sets for columns, r - c diagonals and r + c anti-diagonals for O(1) conflict checks.

Word Search: DFS from each cell matching word[0]; mark the cell (e.g. '#') before recursing and restore it after. O(R·C·4^L). Prune: if the board lacks enough letters, return false immediately.

4

Greedy

Q15Jump Game I & II?AmazonMicrosoft
I: track farthest reachable; if i > farthest → false. II: BFS-by-ranges — when i reaches the current range end, jumps++ and range end = farthest. Both O(n).
Q16Gas Station?AmazonFlipkart
If total gas < total cost → −1. Otherwise scan; when the tank goes negative, the start must be after i — reset tank, start = i+1. O(n).
Q17How do you prove a greedy choice is correct?Google
Exchange argument: take any optimal solution that differs from greedy at the first choice; swap in the greedy choice and show it is no worse. Or find a counter-example quickly → then it's DP.
Q18Non-overlapping intervals (min removals)?MetaAtlassian
Sort by end; keep an interval if its start ≥ last kept end, else remove it. Earliest end leaves the most room. O(n log n).
🧠 DP in 5: "State, Recurrence, Base, Order, Answer" — "Smart Recruiters Brag Over Answers".

Operating Systems & Concurrency

Heavy in Tier 2/3 and Microsoft/Amazon India. Seniors get the concurrency follow-ups ("make it thread-safe").
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Processes, threads & memory

Process A (own address space) code (text) data + heap one stack + registers 1 thread crash here ≠ crash in B Process B with 3 threads code — shared data + heap — shared ⚠️ races T1 stack+ regs T2 stack+ regs T3 stack+ regs one thread corrupts heap → whole process dies IPC: pipes,sockets, shm
Fig 7.1 — threads share the heap (fast communication, but races); processes are isolated (safe, but IPC is costly).
Q1Process vs thread — differences and when to use which?🔥MicrosoftAmazonAdobeTCSInfosys
ProcessThread
MemoryOwn virtual address spaceShares the process's heap, code, files; own stack + registers
Creation / switch costHigh (new page tables, TLB flush)Low
CommunicationIPC: pipes, sockets, shared memory, queuesShared variables (needs synchronisation)
Fault isolationCrash is containedOne bad thread can kill the process

Use processes for isolation/security (Chrome tabs, microservices, worker processes); threads for cheap parallelism inside one service.

Q2What happens during a context switch?MicrosoftAdobeWipro

Answer: Timer interrupt or blocking call → kernel saves the running thread's CPU state (registers, program counter, stack pointer) into its PCB/TCB → scheduler picks the next one → restores its state. Between processes it also switches page tables, so TLB/cache entries become cold — that's the hidden cost. Thread switches inside a process skip the address-space change.

Q3Virtual memory, paging, page faults and thrashing.MicrosoftGoogleTCSHCLTech
  • Virtual memory: each process sees a large private address space; the MMU maps virtual pages to physical frames via page tables. Enables isolation and running programs bigger than RAM.
  • Paging: fixed-size pages (often 4 KB). No external fragmentation; some internal fragmentation in the last page.
  • TLB: a cache of recent page-table translations — a TLB miss costs a page-table walk.
  • Page fault: page not in RAM → OS loads it from disk (major fault) and retries the instruction. Replacement policies: LRU (approximated by Clock), FIFO (Belady's anomaly), Optimal (theoretical).
  • Thrashing: working sets don't fit in RAM, so the system spends its time paging. Fix: reduce multiprogramming, add RAM, improve locality.
Q4Stack vs heap memory?TCSCognizant
Stack: per thread, LIFO frames, automatic, very fast, small (≈1 MB default for .NET threads) → stack overflow on deep recursion. Heap: shared, dynamic, managed by GC/allocator, slower, fragmentation.
Q5User mode vs kernel mode; system call?MicrosoftInfosys
Kernel mode can execute privileged instructions and touch hardware. A system call (read, write, fork) traps from user to kernel mode via a controlled entry point, then returns.
Q6CPU scheduling algorithms?TCSWipro
FCFS (convoy effect), SJF/SRTF (optimal average wait, starves long jobs), Round Robin (time slice; good response), Priority (starvation → fix with aging), Multilevel Feedback Queue (what real OSes approximate).
Q7How many processes after n fork() calls?TCSCapgemini
2ⁿ total (2ⁿ − 1 children), because every existing process executes each subsequent fork. fork returns 0 in the child and the child's PID in the parent.
2

Synchronisation & deadlocks

Q8Mutex vs semaphore vs monitor.🔥MicrosoftAmazonSalesforceInfosys
  • Mutex: one owner at a time; must be released by the thread that acquired it. Protects a critical section.
  • Semaphore: a counter of permits (counting) — limits concurrency to N (e.g. max 10 DB calls). Any thread can signal. Binary semaphore ≈ lock without ownership.
  • Monitor: mutex + condition variables bundled with the data (C# lock + Monitor.Wait/Pulse, Java synchronized + wait/notify).
💡 One-liner: "A mutex is a key to one room; a semaphore is a bowl of N keys."
Q9What is a deadlock? Necessary conditions and how to prevent it.🔥MicrosoftAmazonPayPalTCSAccenture
Thread 1 Thread 2 A B holds holds waits for B waits for A
Fig 7.2 — a cycle in the wait-for graph. Fix: always take locks in the same global order (A then B).

Coffman conditions (all 4 needed): mutual exclusion, hold-and-wait, no preemption, circular wait. Break any one:

  • Circular wait → global lock ordering (most practical).
  • Hold-and-wait → acquire all locks at once, or TryEnter with timeout and back off.
  • No preemption → timeouts/cancellation.
  • Avoidance: Banker's algorithm (theory). Detection: wait-for graph + kill a victim (databases do this).
↪ Livelock = threads keep reacting to each other but make no progress (both step aside forever). Starvation = a thread never gets the resource (fix: fairness/aging).
Q10Race condition — example and three ways to fix it.AmazonAtlassianCognizant

Answer: count++ is read-modify-write; two threads read 5, both write 6 → lost update. Fixes:

  1. Lock around the critical section (lock (_gate) { count++; }).
  2. Atomic instruction — Interlocked.Increment(ref count) (compare-and-swap under the hood).
  3. Avoid sharing — thread-local counters merged at the end, or immutable data / message passing (channels, actors).
↪ Check-then-act races (if (!dict.ContainsKey(k)) dict.Add(k, v)) → ConcurrentDictionary.GetOrAdd. Same race exists in databases → unique constraints / conditional writes.
Q11Implement producer–consumer with a bounded buffer.MicrosoftUberSalesforceIntuit

Answer: Two semaphores — empty (free slots, starts at N) and full (items, starts at 0) — plus a lock for the queue itself. Producers wait on empty, consumers wait on full.

class BoundedBuffer<T> {
    private readonly Queue<T> _q = new();
    private readonly SemaphoreSlim _empty, _full = new(0);
    private readonly object _gate = new();
    public BoundedBuffer(int capacity) => _empty = new SemaphoreSlim(capacity);

    public async Task PutAsync(T item) {
        await _empty.WaitAsync();               // wait for a free slot
        lock (_gate) _q.Enqueue(item);
        _full.Release();                        // signal: one more item
    }
    public async Task<T> TakeAsync() {
        await _full.WaitAsync();                // wait for an item
        T item; lock (_gate) item = _q.Dequeue();
        _empty.Release();                       // signal: one more free slot
        return item;
    }
}
💡 In production say: "I'd use System.Threading.Channels.Channel.CreateBounded or BlockingCollection — but here is how it works inside."
Q12Print odd and even numbers alternately using two threads.MicrosoftWalmartInfosysWipro

Answer: Shared counter + a monitor. Each thread waits while it is not its turn, prints, increments, and pulses the other.

int n = 1; const int Max = 10; object gate = new();
void Run(int parity) {                            // parity 1 = odd, 0 = even
    while (true) lock (gate) {
        while (n <= Max && n % 2 != parity) Monitor.Wait(gate);
        if (n > Max) { Monitor.PulseAll(gate); return; }
        Console.WriteLine($"{parity}: {n++}");
        Monitor.PulseAll(gate);
    }
}
var t1 = new Thread(() => Run(1)); var t2 = new Thread(() => Run(0));
t1.Start(); t2.Start(); t1.Join(); t2.Join();
⚠️ Always wait in a while loop (spurious wake-ups, and the condition may have changed). Pulse on exit so the other thread is not stuck forever.
Q13Concurrency vs parallelism?AtlassianTCS
Concurrency = dealing with many things at once (interleaving, even on 1 core — e.g. async I/O). Parallelism = doing many things at the same instant on multiple cores.
Q14Why use a thread pool?MicrosoftIntuit
Thread creation is expensive and unbounded threads exhaust memory/context-switch the CPU to death. Pools reuse threads and bound concurrency. Don't block pool threads on I/O — use async.
Q15Optimistic vs pessimistic locking?AmazonRazorpay
Pessimistic: lock first (SELECT … FOR UPDATE) — good under high contention. Optimistic: read a version, write WHERE version = v, retry on conflict — good when conflicts are rare.
Q16Dining philosophers — the fix?TCSInfosys
Deadlock if everyone picks the left fork. Fix: number forks and always pick the lower-numbered first (ordering), or allow at most N−1 to sit (semaphore), or a waiter/arbitrator.
🎯 Senior twist
After any DS question at Tier 1/2, expect: "Now 100 threads call this." Answer with: what is shared → where the race is → lock / lock-free / partitioning → what it costs in throughput.

DBMS, Transactions, Indexing & SQL

Every service company asks SQL. Every product company asks "why is this query slow?" and isolation levels.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Transactions

Q1Explain ACID with a bank transfer.🔥AmazonPayPalRazorpayTCSInfosys

Transfer ₹100 from A to B = debit A + credit B.

  • Atomicity — both happen or neither (rollback via undo log if the credit fails).
  • Consistency — constraints hold before and after (balance ≥ 0, total money unchanged).
  • Isolation — a concurrent report never sees A debited but B not yet credited.
  • Durability — once committed, survives a crash (write-ahead log fsynced before ack).
↪ Across two services/databases there is no single ACID transaction → Saga with compensations, or outbox pattern (page 12).
Q2Isolation levels and the anomalies each one allows.🔥GoogleAmazonAtlassianRazorpay
LevelDirty readNon-repeatable readPhantomNotes
Read Uncommitted❌ possible❌❌Almost never used
Read Committed✅ prevented❌❌Default in PostgreSQL, SQL Server, Oracle
Repeatable Read✅✅❌ (in the standard)Default in MySQL InnoDB (gap locks limit phantoms)
Serializable✅✅✅Safest, slowest; may abort → retry
  • Dirty read: you read data another transaction has not committed (it may roll back).
  • Non-repeatable read: same row read twice, different value (someone updated it).
  • Phantom: same range query twice, new rows appear (someone inserted).
  • Lost update / write skew: two transactions read then write based on stale reads — e.g. two doctors both go off-call. Fix: SELECT … FOR UPDATE, serializable, or a constraint.
💡 MVCC: readers see a snapshot and don't block writers. Snapshot isolation prevents dirty/non-repeatable reads but still allows write skew.
2

Indexing & performance

[ 30 | 60 ] [ 10 | 20 ] [ 40 | 50 ] [ 70 | 80 ] 1..9 → rows 10..29 → rows 30..49 → rows 50..59 → rows 60..79 → rows 80+ → rows height 3–4 even formillions of rows leaves are linked → range scans (BETWEEN, ORDER BY) walk sideways
Fig 8.1 — B+ tree: high fan-out keeps lookups at O(logfanout n) page reads; linked leaves make ranges cheap.
Q3How does an index work? Clustered vs non-clustered?🔥MicrosoftAmazonSalesforceAccentureTCS
  • An index is a separate sorted structure (usually a B+ tree) mapping key → row location, so lookups are O(log n) page reads instead of a full table scan.
  • Clustered: the table rows themselves are stored in key order (one per table — usually the primary key in SQL Server / InnoDB).
  • Non-clustered (secondary): separate tree whose leaves point to the row (or to the clustered key → extra "key lookup").
  • Covering index: includes all columns the query needs → no lookup back to the table (INCLUDE columns).
  • Cost: slower writes (every insert/update maintains each index) and extra storage.
Q4When will the database NOT use my index?AmazonFlipkartCognizant
  • Function or cast on the column: WHERE YEAR(created_at) = 2025 → rewrite as a range.
  • Leading wildcard: LIKE '%son'.
  • Composite index (a, b, c) but filtering only on b — the left-most prefix rule.
  • Low selectivity (status with 2 values) — a scan is cheaper.
  • Implicit type conversion (varchar column compared to an int).
  • OR across different columns, stale statistics.
Q5An API is slow because of a query. How do you debug it?🔥WalmartInfosysTCSCognizant
  1. Measure first — APM trace / logs: is time in the DB, the network or the app?
  2. Read the plan — EXPLAIN ANALYZE / actual execution plan: table scans, key lookups, bad row estimates, sorts spilling to disk.
  3. Fix the query — add/adjust the index (composite in the right order, covering), remove SELECT *, make predicates sargable, paginate with keyset (WHERE id > last) not big OFFSETs.
  4. Fix the access pattern — N+1 queries from the ORM (use Include/joins/batching), add caching for hot reads.
  5. Verify — compare before/after latency (p95/p99) and check write cost of new indexes.
Q6Normalization 1NF → 3NF, and when to denormalize?TCSWipro
1NF: atomic values, no repeating groups. 2NF: no partial dependency on part of a composite key. 3NF: no transitive dependency (non-key → non-key). BCNF: every determinant is a key. Denormalize for read-heavy paths (reporting, feeds) and accept update complexity.
Q7SQL vs NoSQL — how do you choose?AmazonSwiggy
SQL: relations, joins, multi-row transactions, ad-hoc queries (payments, orders). NoSQL: known access patterns at huge scale, flexible schema, easy horizontal scale (key-value, wide-column for time series, document). Choose by access pattern + consistency need, not hype.
Q8DELETE vs TRUNCATE vs DROP?TCSInfosysCapgemini
DELETE: row by row, WHERE allowed, logged, fires triggers, can roll back. TRUNCATE: removes all rows by deallocating pages, resets identity, minimal logging. DROP: removes the table definition too.
Q9WHERE vs HAVING; UNION vs UNION ALL?AccentureCognizant
WHERE filters rows before GROUP BY; HAVING filters groups after aggregation. UNION removes duplicates (sort/hash cost); UNION ALL keeps them and is faster.
3

SQL they make you write

Q10Find the Nth highest salary (handle ties).🔥AmazonTCSInfosysWiproAccenture
-- Window function (works for any N, ties share a rank)
SELECT DISTINCT salary
FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
      FROM Employee) t
WHERE rnk = 3;

-- 2nd highest without window functions
SELECT MAX(salary) FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee);

-- LIMIT/OFFSET (MySQL/PostgreSQL): N = 3 → OFFSET 2
SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET 2;
↪ RANK vs DENSE_RANK vs ROW_NUMBER for salaries 100, 100, 90: RANK 1,1,3 · DENSE_RANK 1,1,2 · ROW_NUMBER 1,2,3. Return NULL if fewer than N distinct salaries.
Q11Top 3 salaries in each department.AmazonWalmartCognizant
SELECT d.name AS department, e.name, e.salary
FROM (SELECT *, DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
      FROM Employee) e
JOIN Department d ON d.id = e.dept_id
WHERE e.rnk <= 3;
Q12Employees who earn more than their manager (self-join).TCSInfosysHCLTech
SELECT e.name
FROM Employee e
JOIN Employee m ON e.manager_id = m.id
WHERE e.salary > m.salary;
Q13Find and delete duplicate emails, keeping the smallest id.AccentureCapgeminiAdobe
-- find
SELECT email, COUNT(*) FROM Person GROUP BY email HAVING COUNT(*) > 1;

-- delete (SQL Server / PostgreSQL style with a CTE)
WITH d AS (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn FROM Person
)
DELETE FROM Person WHERE id IN (SELECT id FROM d WHERE rn > 1);
Q14Running total of sales per day; customers who never ordered.FlipkartTCSWipro
SELECT order_date, amount,
       SUM(amount) OVER (ORDER BY order_date ROWS UNBOUNDED PRECEDING) AS running_total
FROM Sales;

SELECT c.name FROM Customers c
LEFT JOIN Orders o ON o.customer_id = c.id
WHERE o.id IS NULL;                     -- anti-join (or NOT EXISTS)
⚠️ NOT IN (subquery) returns nothing if the subquery contains a NULL — prefer NOT EXISTS.
🎯 Memory hook
"Dirty → Non-repeatable → Phantom" are fixed one by one as you go RC → RR → Serializable. Window functions = "GROUP BY that keeps the rows".

Networking, HTTP & APIs

The backend engineer's daily vocabulary. Asked as warm-ups in T1, as full rounds in T3.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

The famous one

① cache?browser/OS ② DNS→ IP address ③ TCPSYN/SYN-ACK/ACK ④ TLScert + keys ⑤ HTTP GETCDN / LB ⑥ serverapp → cache → DB ⑦ response 200 + HTMLgzip/br, cache headers ⑧ renderDOM + CSSOM → layout → paint recursive resolver → root → .com → authoritative then more requests for CSS/JS/images (reusing the same connection with HTTP/2)
Fig 9.1 — go as deep as the interviewer wants at any step; that depth is the signal.
Q1What happens when you type a URL and press Enter?🔥GoogleAmazonMicrosoftTCSInfosys
  1. Parse URL; check HSTS (force HTTPS); check browser / OS / router caches.
  2. DNS: stub resolver → recursive resolver (ISP / 8.8.8.8) → root → TLD (.com) → authoritative server → A/AAAA record (cached by TTL).
  3. TCP 3-way handshake to the IP on port 443 (or QUIC over UDP for HTTP/3).
  4. TLS 1.3: ClientHello / ServerHello, server certificate verified against trusted CAs, key exchange (ECDHE) → symmetric session keys.
  5. HTTP request hits a CDN edge or load balancer → reverse proxy → app server → cache / DB.
  6. Response with status, headers (Cache-Control, Set-Cookie), compressed body.
  7. Render: parse HTML → DOM, CSS → CSSOM, run JS, layout, paint; extra resources fetched in parallel.
2

Transport & protocols

Q2TCP vs UDP — and where would you use each?🔥AmazonAdobeTCSWipro
TCPUDP
ConnectionConnection-oriented (handshake)Connectionless
ReliabilityOrdered, retransmits, flow + congestion controlBest effort; may drop / reorder
OverheadHigher; head-of-line blockingLow latency, small header
UseHTTP/1–2, DB connections, file transfer, emailDNS, video calls, gaming, streaming, QUIC (HTTP/3)
Q3HTTP/1.1 vs HTTP/2 vs HTTP/3.GoogleMetaAtlassian
  • HTTP/1.1: text, keep-alive, one request at a time per connection → browsers open ~6 connections; head-of-line blocking.
  • HTTP/2: binary framing, multiplexed streams on one TCP connection, header compression (HPACK). Still TCP-level HOL blocking on packet loss.
  • HTTP/3: over QUIC (UDP) — independent streams (no TCP HOL), faster handshakes (TLS 1.3 built in, 0-RTT resumption), connection migration (Wi-Fi → 4G).
Q4How does HTTPS / TLS keep data secure?MicrosoftPayPalAccenture

Answer: Authentication — the server presents a certificate signed by a CA your OS/browser trusts, proving it owns the domain. Key exchange — asymmetric crypto (ECDHE) agrees on a shared secret without sending it (gives forward secrecy). Encryption + integrity — the rest uses fast symmetric ciphers (AES-GCM / ChaCha20) with authentication tags. TLS 1.3 needs one round trip.

↪ mTLS = the client also presents a certificate — common for service-to-service auth in a mesh.
Q5OSI vs TCP/IP layers?TCSInfosys
OSI 7: Physical, Data link, Network, Transport, Session, Presentation, Application ("Please Do Not Throw Sausage Pizza Away"). TCP/IP 4: Link, Internet (IP), Transport (TCP/UDP), Application (HTTP, DNS).
Q6L4 vs L7 load balancer?AmazonFlipkart
L4 routes by IP/port (fast, protocol-agnostic, e.g. AWS NLB). L7 understands HTTP — route by path/header/cookie, TLS termination, retries (AWS ALB, NGINX, Envoy).
Q7WebSockets vs SSE vs long polling?MetaUberSwiggy
WebSocket: full-duplex, persistent (chat, games). SSE: server → client only over HTTP, auto-reconnect (live scores, notifications). Long polling: request held open until data — fallback, more overhead.
Q8What does a CDN do?NetflixAccenture
Caches content at edge locations near users → lower latency, less origin load, DDoS absorption. Control with Cache-Control/TTL, versioned file names for cache busting, purge APIs.
3

API design & security

Q9PUT vs PATCH vs POST — and which methods are idempotent?🔥SalesforceIntuitTCSCognizant
  • POST — create / action; not idempotent (retry = second order!).
  • PUT — replace the full resource at a known URI; idempotent.
  • PATCH — partial update; not guaranteed idempotent (e.g. "increment").
  • GET, HEAD, PUT, DELETE — idempotent; GET/HEAD are also safe (no side effects).
💡 Make POST safe to retry with an Idempotency-Key header: store key → response; replay the stored response on retry (how payment APIs work).
↪ Status codes to know: 200, 201 Created, 202 Accepted, 204, 301/302/304, 400, 401 (who are you?), 403 (not allowed), 404, 409 Conflict, 422, 429 Too Many Requests, 500, 502, 503, 504.
Q10REST vs gRPC vs GraphQL — when to pick which?UberGoogleAtlassianWalmart
RESTgRPCGraphQL
FormatJSON over HTTPProtobuf over HTTP/2JSON, single endpoint
Best forPublic APIs, simplicity, cachingInternal service-to-service, streaming, low latencyMany clients needing different shapes (mobile/web)
Watch outOver/under-fetchingBrowser support needs a proxy; binary debuggingN+1 resolvers, caching, query cost limits
Q11Authentication vs authorization; sessions vs JWT; what is OAuth 2.0?🔥MicrosoftAtlassianPayPalInfosysAccenture
  • AuthN = who are you (login). AuthZ = what may you do (roles, scopes, policies).
  • Session cookie: server stores session, cookie holds an opaque ID — easy to revoke, needs shared session store.
  • JWT: signed, self-contained claims (header.payload.signature) — stateless verification, but hard to revoke → keep access tokens short-lived (5–15 min) + refresh tokens. Signed ≠ encrypted: never put secrets in it.
  • OAuth 2.0 = delegated authorization ("let this app read my Google Drive"). Web/mobile apps use Authorization Code + PKCE. OpenID Connect adds an ID token on top for authentication (Sign in with Google / Entra ID).
Q12What is CORS and why does my browser call fail while Postman works?TCSCognizantAdobe

Answer: Browsers enforce the same-origin policy. For cross-origin calls the server must send Access-Control-Allow-Origin (and for non-simple requests answer the preflight OPTIONS with allowed methods/headers). Postman is not a browser, so no CORS check. Fix on the server (e.g. ASP.NET Core AddCors with explicit origins) — never * with credentials.

Q13Top web security issues and how you prevent them.PayPalIntuitAccenturebank GCCs
  • SQL injection → parameterised queries / ORM, least-privilege DB user.
  • XSS → output encoding, Content-Security-Policy, HttpOnly cookies.
  • CSRF → SameSite cookies, anti-forgery tokens.
  • Broken access control / IDOR → check ownership on every resource ID server-side.
  • Secrets → vault (Azure Key Vault / AWS Secrets Manager), never in code or images.
  • Rate limiting, input validation, dependency scanning, TLS everywhere.
Q14How do you version an API?SalesforceInfosys
URL (/v2/orders) — simplest and visible; header / media type — cleaner URLs. Prefer additive, backward-compatible changes; deprecate with dates and telemetry on old versions.
Q15Offset vs cursor pagination?MetaAtlassian
OFFSET is simple but slow for deep pages and skips/duplicates rows when data changes. Cursor/keyset (?after=lastId) is stable and uses the index — use it for feeds and large tables.
🎯 Takeaway
Idempotency, status codes and auth flows show up again in every design round — learn them here once and reuse them on pages 12–13.

OOP, SOLID & Design Patterns

The language of every LLD / machine-coding round. Tier 3 asks definitions; Tier 2 asks you to apply them live.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

OOP fundamentals

Q1Explain the four pillars of OOP with real examples.🔥TCSInfosysWiproCognizantAdobe
  • Encapsulation — hide state behind behaviour: Account.Withdraw(amount) validates; the balance field is private. Protects invariants.
  • Abstraction — expose what, hide how: IPaymentGateway.Charge() without knowing Razorpay vs Stripe internals.
  • Inheritance — "is-a" reuse: SavingsAccount : Account. Use sparingly.
  • Polymorphism — one call, many behaviours: shape.Area() on Circle/Square. Compile-time = overloading; runtime = overriding (virtual dispatch).
Q2Abstract class vs interface — when to use which?🔥MicrosoftTCSAccentureCapgemini
Abstract classInterface
InheritanceSingleMultiple
StateFields, constructorsNo instance fields (C# 8+ allows default methods)
Meaning"is-a" with shared code"can-do" capability / contract
Use whenRelated classes share base logic (template method)Unrelated classes share a contract; for DI and mocking
Q3Overloading vs overriding?InfosysHCLTech
Overloading: same name, different parameters, chosen at compile time. Overriding: subclass redefines a virtual method with the same signature, chosen at runtime. new in C# hides instead of overriding — a classic trick question.
Q4Why composition over inheritance?AmazonAtlassian
Inheritance is compile-time, tightly coupled and leaks base-class changes (fragile base class). Composition ("has-a") lets you swap behaviour at runtime (Strategy) and test with fakes. Inherit only for true "is-a" with LSP intact.
Q5Coupling vs cohesion?WiproIntuit
Aim for low coupling (modules know little about each other — depend on interfaces) and high cohesion (each class does one focused job). Both make change cheap.
Q6DRY, KISS, YAGNI?Accenture
Don't Repeat Yourself (one source of truth for knowledge), Keep It Simple, You Aren't Gonna Need It (don't build for imagined requirements). Seniors add: duplication is cheaper than the wrong abstraction.
2

SOLID

Q7Explain SOLID — with a violation and a fix for each.🔥FlipkartWalmartMicrosoftTCSInfosys
PrincipleViolationFix
Single ResponsibilityInvoiceService calculates totals, writes PDFs and sends emailsSplit into calculator, renderer, notifier — one reason to change each
Open/Closedswitch (paymentType) edited for every new methodIPaymentStrategy per method; add a class, don't edit old code
Liskov SubstitutionSquare : Rectangle — setting width also changes height, breaking callersDon't inherit; both implement IShape
Interface SegregationIMachine { Print; Scan; Fax } forces a basic printer to throw on FaxIPrinter, IScanner, IFax
Dependency InversionOrderService does new SqlOrderRepo()Depend on IOrderRepo, inject it (DI container)
💡 In machine coding, the grader literally checks: "Can I add a new X without modifying existing classes?" — that's O + D in action.
3

Design patterns

CheckoutService - strategy: IPaymentStrategy has-a (composition) «interface» IPaymentStrategy + Pay(amount): Result CardPayment UpiPayment Wallet… new method = new class no edits to Checkout ✓ (OCP)
Fig 10.1 — Strategy: the most reused pattern in LLD rounds (pricing, splitting, payment, parking fee, matching).
Q8Implement a thread-safe Singleton in C#. Why is Singleton often called an anti-pattern?🔥MicrosoftTCSInfosysCognizant
public sealed class ConfigCache {
    private static readonly Lazy<ConfigCache> _instance =
        new(() => new ConfigCache());              // thread-safe by default
    public static ConfigCache Instance => _instance.Value;
    private ConfigCache() { }                      // no outside construction
}

Alternatives: double-checked locking with volatile, or a static readonly field (eager). Downsides: hidden global state, hard to unit-test/mock, couples callers to a concrete class. Better in modern .NET: register as a singleton lifetime in the DI container (services.AddSingleton<IConfigCache, ConfigCache>()).

Q9Factory vs Abstract Factory vs Builder.FlipkartSalesforceAccenture
  • Factory Method: one method decides which concrete class to create (NotificationFactory.Create("sms")). Hides new + the switch in one place.
  • Abstract Factory: creates families of related objects (IUiFactory → Windows button + Windows checkbox, Mac button + Mac checkbox).
  • Builder: step-by-step construction of a complex object with many optional parts (new HttpRequestBuilder().WithHeader(..).WithTimeout(..).Build()) — avoids telescoping constructors, enables immutability.
Q10Observer pattern — where have you used it?WalmartSwiggyWipro

Answer: Subject keeps a list of observers and notifies them on change (C# event/IObservable, UI data-binding, domain events). Example: Order.StatusChanged → email, SMS and analytics handlers. At system scale the same idea becomes pub/sub on Kafka.

⚠️ Memory leaks: subscribers that never unsubscribe from a long-lived publisher stay alive.
Q11Decorator vs Proxy vs Adapter?AdobeCapgemini
Decorator adds behaviour with the same interface (logging/caching wrapper, ASP.NET middleware). Proxy controls access with the same interface (lazy load, auth, remote). Adapter converts one interface into another (wrap a legacy SOAP client behind IPaymentGateway).
Q12State pattern — when?FlipkartSwiggy
When behaviour depends on a lifecycle (order: Created → Paid → Shipped → Delivered; vending machine; elevator). Each state is a class with allowed transitions — no giant if/else on a status field.
Q13Chain of Responsibility?PayPalAtlassian
A request passes through handlers until one handles it: middleware pipelines, approval workflows (manager → director → VP), fraud checks, ATM cash dispenser (2000 → 500 → 100 notes).
Q14What is Dependency Injection / IoC?TCSInfosysMicrosoft
Objects receive their dependencies (constructor injection) instead of creating them; a container wires the graph. Benefits: testability (inject fakes), swapping implementations, lifetime management. Lifetimes in .NET: Transient, Scoped (per request), Singleton.
Q15"Which design patterns have you used in your project?" — how to answer.All T3HM rounds

Answer shape: Problem → pattern → result. Pick 2–3 real ones:

  • "Our pricing rules kept growing a switch statement; I moved each rule into a Strategy resolved by a Factory — new rules shipped without touching checkout."
  • "Calls to a flaky vendor were wrapped in a Decorator adding retry + circuit breaker (Polly)."
  • "Repository + Unit of Work over EF Core so domain logic is testable without a database."
⚠️ Listing 10 pattern names without a story signals memorisation.
🧠 Patterns by family: Creational (Singleton, Factory, Abstract Factory, Builder, Prototype) · Structural (Adapter, Decorator, Proxy, Facade, Composite) · Behavioral (Strategy, Observer, State, Command, Chain of Responsibility, Template Method, Iterator).

Low-Level Design & Machine Coding

The Tier 2 gatekeeper (Flipkart, Swiggy, Uber IN, Atlassian "code design", Microsoft LLD). Working code > perfect diagrams.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

The 90-minute game plan

0–10 min · Read & clarify
List the must-have flows (3–5) and park the nice-to-haves. Ask: in-memory OK? CLI/driver or tests? Concurrency expected?
10–25 min · Model
Nouns → entities, verbs → service methods. Write interfaces for anything that will vary (pricing, strategy, storage). Enums for types/status.
25–70 min · Build the happy path end-to-end
Models → repository (in-memory dictionaries) → services → driver. Commit to runnable early, then deepen.
70–85 min · Edge cases & demo
Validation, custom exceptions, a main/driver or unit tests that exercise every requirement.
85–90 min · Extension talk
Show where a new requirement plugs in ("new split type = new class implementing ISplitStrategy").
Why candidates fail machine coding
  • Code doesn't run at the end (spent 60 min on the "perfect" design).
  • One god class (SplitwiseManager with 900 lines).
  • Hard-coded if (type == "CAR") everywhere instead of polymorphism/strategies.
  • No input validation / exception handling; public mutable fields.
  • Ignoring concurrency when the problem screams it (seat booking, inventory).
2

Parking lot — the classic

ParkingLot 1..* Floor 1..* ParkingSpottype · isFree · vehicle EntryGate ExitGate Ticketid · spot · inTime Payment / Receiptamount · outTime «interface»ISpotAllocationStrategy «interface»IFeeStrategy nearest-first · per-floor · EV-first | hourly · flat · weekend Car · Bike · Truck→ VehicleType enum
Fig 11.1 — the variable parts (allocation, fees) are interfaces; everything else is plain entities.
Q1Design a Parking Lot (multi-floor, vehicle types, tickets, fees).🔥AmazonMicrosoftUberFlipkartInfosys
Entities
ParkingLot, Floor, ParkingSpot (type, isFree), Vehicle (type, number), Ticket, Payment, Gate.
Interfaces
ISpotAllocationStrategy.FindSpot(vehicleType), IFeeStrategy.Calculate(ticket, exitTime).
Flows
Park → find spot → mark occupied → issue ticket. Unpark → compute fee → pay → free spot.
Data
Per floor and type, a set/min-heap of free spot IDs → O(log n) nearest spot; map ticketId → ticket.
Concurrency
Two gates must not assign the same spot: lock per floor+type, or atomic compare-and-set on spot.isFree.
Extensions
EV charging spots, reservations, display boards (Observer on spot changes), monthly passes (new fee strategy).
3

The rest of the top 10

Q2Design Splitwise (expenses, splits, balances, settle up).🔥FlipkartSwiggyPhonePeMicrosoft
Entities
User, Group, Expense (paidBy, amount, splits), Split (user, amount).
Strategy
ISplitStrategy: EqualSplit, ExactSplit, PercentSplit (validate sums = amount / 100%).
Balances
Dictionary<(from, to), decimal> or per-user net balance; update on each expense.
Simplify debts
Compute net balance per user; repeatedly match the largest creditor with the largest debtor (two heaps) — at most n−1 transactions.
Gotchas
Use decimal for money; rounding — give the leftover paisa to the first person; idempotent expense IDs.
Q3Design BookMyShow — how do you stop two users booking the same seat?🔥FlipkartMicrosoftSwiggyCognizant
Entities
City, Theatre, Screen, Seat, Movie, Show, ShowSeat (status: Available / Locked / Booked, lockedUntil), Booking, Payment.
Flow
Select seats → temporary lock (e.g. 10 min) → pay → confirm → Booked; on timeout/failure → release.
Concurrency
In memory: lock per show (or per ShowSeat) and check-then-set atomically. In a DB: UPDATE show_seat SET status='LOCKED', user=? WHERE id IN (…) AND status='AVAILABLE' and verify rows affected = seats requested (optimistic), or SELECT … FOR UPDATE. At scale: Redis SET seat:key user NX EX 600.
Patterns
State (seat status), Strategy (pricing: weekend/premium), Observer (notify on booking).
Q4Implement a rate limiter class (per user, N requests per second).🔥AtlassianUberAmazonRazorpay

Answer: Token bucket per user: capacity = burst, refill at rate r/sec, lazily computed on each call (no background timer). Thread-safe with a small lock per bucket.

public sealed class TokenBucket {
    private readonly double _capacity, _refillPerSec;
    private double _tokens;
    private long _last = Stopwatch.GetTimestamp();
    private readonly object _gate = new();

    public TokenBucket(double capacity, double refillPerSec) {
        _capacity = capacity; _refillPerSec = refillPerSec; _tokens = capacity;
    }
    public bool TryAcquire() {
        lock (_gate) {
            long now = Stopwatch.GetTimestamp();
            double elapsed = (now - _last) / (double)Stopwatch.Frequency;
            _tokens = Math.Min(_capacity, _tokens + elapsed * _refillPerSec);
            _last = now;
            if (_tokens < 1) return false;
            _tokens -= 1;
            return true;
        }
    }
}

public sealed class RateLimiter {
    private readonly ConcurrentDictionary<string, TokenBucket> _buckets = new();
    private readonly double _cap, _rate;
    public RateLimiter(double cap, double rate) { _cap = cap; _rate = rate; }
    public bool Allow(string userId) =>
        _buckets.GetOrAdd(userId, _ => new TokenBucket(_cap, _rate)).TryAcquire();
}
↪ Atlassian-style extension: "support different limits per tier" → inject an ILimitPolicy; "sliding window instead" → keep a queue of timestamps per user (exact, more memory) or sliding-window counter. Distributed version → page 13.
Q5Design an Elevator system.MicrosoftAmazonAdobe
Entities
Building, Elevator (currentFloor, direction, state, request queues), Request (floor, direction), Controller/Dispatcher, Door, Button.
Scheduling
IDispatchStrategy: nearest idle car, or SCAN/LOOK ("elevator algorithm") — keep two sorted sets (up stops ≥ current, down stops ≤ current) and serve in direction, then reverse.
State
Idle → MovingUp / MovingDown → DoorsOpen; maintenance mode.
Extensions
VIP/fire mode, load limit, minimising wait time vs energy.
Q6Snake & Ladder?FlipkartInfosys
Board (size, Dictionary<int,int> jumps for snakes + ladders), Player (position), Dice (IDice: random / crooked / multiple dice), Game loop with turn queue. Validate: no cycles, a snake head ≠ ladder start, exact 100 to win.
Q7Vending machine?AmazonWalmart
State pattern: Idle → HasMoney → Dispensing → (ReturnChange). Inventory map, coin/note denominations, change-making (greedy for canonical coins), refund on cancel.
Q8In-memory key-value store with TTL?AtlassianUber
Map key → (value, expiresAt). Lazy expiry on read + periodic sweeper using a min-heap of expiry times. Add LRU eviction (DLL) for capacity; ReaderWriterLockSlim or sharded locks for concurrency.
Q9Food ordering (Flipkart-style)?FlipkartSwiggyZomato
Restaurant (menu, rating, capacity), Order (state machine), IRestaurantSelectionStrategy (lowest cost / highest rating), capacity decremented atomically on accept and restored on completion.
Q10Logger / in-memory pub-sub?MicrosoftAtlassian
Logger: levels, ISink (console/file), formatter, Chain of Responsibility by level, async queue for non-blocking writes. Pub-sub: topics → subscriber list, per-subscriber offset, at-least-once delivery with acks.
Q11Library management (T3 favourite)?TCSWiproAccenture
Book vs BookItem (copies), Member, Loan (due date), Reservation queue, Fine strategy. Search by title/author via indexes (maps). Notify on availability (Observer).
🎯 The grader's checklist
✓ Runs and demos all requirements ✓ Entities with clear ownership ✓ Variable behaviour behind interfaces ✓ Validation + exceptions ✓ Thread-safety where state is shared ✓ You can add the next requirement in 5 minutes.

System Design Concepts — Rapid Fire

Asked standalone ("explain CAP") or as drill-downs inside a design round. Deeper diagrams: System Design notebook.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

The skeleton almost every answer reuses

clients CDN LB / API GW stateless svc ×Nauth · rate-limitautoscaled cache (Redis) DB primary replicas queue/Kafka workers + object storage (S3/Blob) for files · search index (Elastic) · observability (logs, metrics, traces) everywhere
Fig 12.1 — start every design from this and then change one box for the problem's real bottleneck.
2

Consistency & data distribution

Q1Explain CAP — and why PACELC is the more useful version.🔥GoogleAmazonAtlassianAccenture

Answer: During a network Partition, a distributed store must choose Consistency (refuse/serve errors to stay correct) or Availability (answer, possibly stale). Partitions are not optional, so it's really CP vs AP when partitioned.

PACELC: if Partition → A or C; Else (normal operation) → Latency or Consistency. Example: DynamoDB/Cassandra default PA/EL (fast, eventually consistent, tunable); Spanner / traditional single-leader SQL PC/EC.

💡 Choose per feature: payments/inventory → consistency; likes, feeds, view counts → availability + eventual consistency.
Q2Leader-follower vs multi-leader vs leaderless replication; what is a quorum?AmazonUberWalmart
  • Single leader: writes to the leader, async/sync replication to followers. Simple; replica lag → stale reads (fix: read-your-writes by reading from the leader for a few seconds after a write).
  • Multi-leader: writes in several regions; must resolve conflicts (last-write-wins, CRDTs).
  • Leaderless (Dynamo style): write to W of N replicas, read from R; if R + W > N, reads overlap the latest write. Read-repair + hinted handoff fix divergence.
Q3How do you shard a database? What problems come with it?🔥MetaGoogleFlipkartRazorpay
  • Range (by date/ID range) — good range scans, hot spots on the newest range.
  • Hash (hash(key) mod N or consistent hashing) — even spread, no range scans; consistent hashing moves only ~1/N keys when nodes change.
  • Directory / lookup — flexible placement, extra hop + the directory must be HA.

Problems: cross-shard joins and transactions, hot keys (celebrity user → split key / add salt / cache), resharding (use many virtual shards from day one), global secondary indexes, uneven growth.

↪ Pick the shard key from the main access pattern: chat → conversation_id, orders → customer_id, multi-tenant SaaS → tenant_id.
Q4Vertical vs horizontal scaling?TCSInfosys
Vertical: bigger machine — simple, has a ceiling and a single point of failure. Horizontal: more machines — needs stateless services, load balancing, partitioned data; scales further and adds fault tolerance.
Q5Strong vs eventual consistency?AmazonAdobe
Strong: every read sees the latest committed write (linearizable). Eventual: replicas converge if writes stop. Middle grounds: read-your-writes, monotonic reads, causal consistency.
Q6Partitioning vs sharding vs replication?CognizantSalesforce
Partitioning splits data (can be within one server); sharding = partitions spread across servers; replication = copies of the same data for availability and read scaling. Real systems do both.
Q7How is a leader elected?GoogleUber
Consensus (Raft/Paxos): majority vote with terms; a leader needs a quorum, so a minority partition can't elect one. In practice use etcd/ZooKeeper leases and fencing tokens to stop a stale leader writing.
3

Caching, queues & reliability

Q8Caching strategies, eviction and the hard part — invalidation.🔥MetaAmazonSwiggyInfosys
StrategyHowGood for
Cache-asideApp reads cache → miss → DB → populate; on write update DB then delete the keyDefault choice; read-heavy
Write-throughWrite cache + DB synchronouslyRead-after-write freshness
Write-backWrite cache, flush to DB laterWrite-heavy counters; risk of loss
Write-aroundWrite DB only; cache fills on readData rarely re-read

Eviction: LRU, LFU, TTL. Problems: stampede (many misses at once → request coalescing / lock per key, jittered TTLs), stale data (delete-on-write, short TTL, CDC-driven invalidation), hot keys (local in-process cache + replicas).

Q9Why use a message queue? Kafka vs RabbitMQ? Delivery guarantees?🔥UberAmazonWalmartPhonePe
  • Why: decouple services, absorb spikes (buffer), async work (emails, video encoding), fan-out events to many consumers.
  • Kafka: distributed append-only log; partitions give ordering per key; consumers track offsets and can replay; huge throughput. Great for event streaming, CDC, analytics.
  • RabbitMQ / SQS: broker deletes on ack; routing (exchanges), per-message TTL, priority; great for task queues.
  • Guarantees: at-most-once (may lose), at-least-once (may duplicate — the practical default), exactly-once = at-least-once + idempotent consumers (dedupe by message ID) or transactional writes.
  • Poison messages → retries with backoff → dead-letter queue.
Q10How do you keep data consistent across microservices (no distributed DB transaction)?AmazonUberRazorpayIntuit
  • 2PC: coordinator prepare → commit; strong but blocking and fragile — avoided across services.
  • Saga: a sequence of local transactions, each with a compensating action (refund, release inventory). Orchestrated (central coordinator) or choreographed (events).
  • Transactional outbox: write the business row and an "event" row in the same local transaction; a relay publishes outbox rows to Kafka → no "DB updated but event lost".
  • Plus idempotency keys everywhere, because retries happen.
Q11Rate-limiting algorithms — compare them.GoogleAmazonAtlassianRazorpay
AlgorithmIdeaTrade-off
Fixed windowCounter per minuteCheap; 2× burst at window edges
Sliding logStore each timestampExact; memory heavy
Sliding window counterWeighted current + previous windowGood approximation, cheap
Token bucketRefill tokens at rate r, capacity bAllows bursts up to b; most common (APIs)
Leaky bucketQueue drained at a fixed rateSmooth output; adds latency
Q12Retries done right?AmazonNetflix
Only retry idempotent / transient failures; exponential backoff + jitter; cap attempts; set timeouts shorter than the caller's; retry budgets so retries don't multiply load in an outage.
Q13Circuit breaker & bulkhead?NetflixPayPal
Breaker: after N failures → Open (fail fast, fallback) → Half-open (trial calls) → Closed. Bulkhead: separate pools per dependency so one slow dependency can't exhaust all threads.
Q14Load-balancing algorithms?TCSFlipkart
Round robin, weighted RR, least connections, least response time, IP-hash / consistent hash (sticky). Plus health checks and connection draining on deploys.
Q15Monolith vs microservices?All T3Intuit
Microservices buy independent deploys, scaling and team autonomy at the cost of network failures, distributed data, observability and ops overhead. Start with a modular monolith; split along bounded contexts when team/scale pain is real.
Q16SLI vs SLO vs SLA; why p99?GoogleMicrosoft
SLI = measured metric (latency, error rate). SLO = internal target (99.9% under 200 ms). SLA = contract with penalties. Averages hide tail latency; p99 is what heavy users and fan-out requests actually feel. Error budget = 100% − SLO.
Q17Bloom filter — where is it used?GoogleAtlassian
Bit array + k hashes: "definitely not present" or "maybe present" (false positives, no false negatives). Used to skip disk lookups (LSM trees/Cassandra), username-taken checks, crawler "seen URL" sets.
4

Napkin numbers to memorise

ThingRough numberUse it for
1 day≈ 86,400 s ≈ 105 s1M req/day ≈ 12 QPS avg; peak ≈ 2–5× avg
Memory read / SSD read / same-DC round trip~100 ns / ~100 µs / ~0.5 msWhy caches and batching win
Cross-continent round trip~100–150 msWhy multi-region + CDN
One Redis node~100K simple ops/sCache sizing
One SQL primarya few thousand write TPS (varies a lot)When to shard
Storage100M users × 1 KB = 100 GBFits one node? Then don't shard yet

System Design Problems — Answer Blueprints

Each blueprint = what to say in 45 minutes. URL shortener & chat are fully worked in the System Design notebook (p.9–10).
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

The 45-minute shape

MinutesStepSay / draw
0–5Requirements3–5 functional, then non-functional: scale, latency, consistency, availability. Write them down.
5–10EstimatesDAU → QPS (avg, peak), storage/day, read:write ratio. Only the numbers that change the design.
10–15API + data model3–4 endpoints; main tables/keys; choose SQL/NoSQL with a reason.
15–25High-level diagramThe skeleton from page 12, walking one request end to end.
25–40Deep divesThe 2 hardest parts (the interviewer often picks). Trade-offs, failure modes.
40–45Wrap-upBottlenecks, monitoring, what you'd do next with more time.
2

Social & real-time

WRITE path (push / fan-out on write) normal user post svc + Kafka fan-out workers feed cache per userRedis list of post IDs(keep last ~800) READ path (pull for celebrities) reader feed service celebrity posts (pull) merge by time/rank → hydrate → return push = fast reads, expensive writes for 10M followers · pull = cheap writes, slow reads · hybrid = best of both
Fig 13.1 — the hybrid fan-out answer is what Tier 1 interviewers are waiting to hear.
Q1Design a News Feed (Twitter / Instagram / LinkedIn).🔥MetaGoogleLinkedInAtlassian
Requirements
Post, follow, see a ranked/recent feed; feed loads < 200 ms; eventual consistency OK (a post appearing 5 s late is fine).
Estimates
300M DAU × 10 feed loads/day ≈ 35K QPS avg reads; writes ~10× fewer → read-heavy.
API
POST /posts, POST /follow/{id}, GET /feed?cursor=.
Data
Posts (sharded by post_id / author), follow graph (user → followers, followee lists), feed cache (user → list of post IDs), media in object storage + CDN.
Deep dive
Hybrid fan-out (Fig 13.1); ranking service (features: recency, affinity, engagement); cursor pagination; cache warm-up for inactive users computed on login.
Trade-offs
Fan-out cost vs read latency; ordering under eventual consistency; deleting a post must remove/skip it on read (tombstones).
Q2Design a Notification System (push, SMS, email, in-app).🔥AmazonFlipkartSwiggyWalmartGCCs
Requirements
Multi-channel, user preferences / opt-out, templates, scheduling, priority (OTP > promo), at-least-once without spamming duplicates.
Flow
Producers → Notification API (validate, idempotency key) → preference + rate-limit check → per-channel priority queues → channel workers → providers (APNs/FCM, SMS gateway, SES/SendGrid).
Data
Templates, user preferences, device tokens, notification log (status per channel: queued/sent/delivered/failed).
Reliability
Retries with backoff, provider failover (secondary SMS vendor), DLQ, dedupe by (user, event_id, channel).
Extras
Quiet hours by timezone, batching/digests, tracking opens/clicks, per-user rate limits.
Q3Design a distributed rate limiter for an API gateway.GoogleAmazonUberRazorpay
Where
In the API gateway / sidecar, keyed by API key, user or IP; rules from a config service.
Algorithm
Token bucket or sliding-window counter (page 12).
State
Central Redis; do the read-update-decide in one atomic Lua script (or INCR + EXPIRE for fixed windows) to avoid races between gateway nodes.
Scale
Shard Redis by key; for very hot paths keep a local in-memory bucket and sync periodically (slightly approximate, much faster).
Response
HTTP 429 with Retry-After and X-RateLimit-Remaining headers.
Failure
If Redis is down: fail-open (availability) for most APIs, fail-closed for login/OTP endpoints.
3

Location, money & search

Q4Design Uber / Ola (ride matching).🔥UberGoogleSwiggyZomato
Requirements
Drivers send location every ~4 s; riders request a ride, get matched in seconds; trip tracking; pricing.
Estimates
1M active drivers / 4 s ≈ 250K location writes/s → keep live locations in memory, not in a SQL table.
Geo index
Geohash / S2 / H3 cells: driver location → cell; search the rider's cell + neighbours (Redis GEO or an in-memory sharded index by cell).
Matching
Candidate drivers ranked by ETA (routing service), offer to one at a time with timeout; lock driver state to avoid double assignment.
Trip
State machine (Requested → Accepted → Arrived → InProgress → Completed) persisted in a durable DB; events to Kafka for billing, analytics.
Deep dives
Surge pricing per cell (supply/demand), WebSocket/push for live tracking, city-level sharding.
Q5Design a Payment System (wallet / checkout).🔥AmazonStripePayPalRazorpayPhonePe
Must-haves
Never double-charge, never lose money, full audit trail; latency less critical than correctness.
Idempotency
Client sends Idempotency-Key; store key → status/result; retries return the stored result.
Ledger
Double-entry, append-only: every movement = debit one account + credit another; balances derived (or cached) from entries. SQL with strong consistency.
Flow
Create payment (PENDING) → call PSP / bank → webhook or poll → SUCCESS/FAILED → ledger entries + outbox event → order service.
Failures
Timeouts = unknown state → query PSP status, never blindly retry the charge; daily reconciliation against PSP settlement files.
Security
Tokenised cards (PCI DSS scope reduction), encryption, fraud/risk checks, rate limits.
Q6Design Typeahead / Search Autocomplete.GoogleAmazonFlipkartLinkedIn
Requirements
Top 5–10 suggestions per prefix in < 100 ms; ranked by popularity; updated daily/hourly is fine.
Data
Trie where each node stores precomputed top-k completions → O(prefix length) lookup.
Build
Offline pipeline aggregates query logs (counts with decay) → builds trie snapshots → pushed to serving nodes.
Serve
Shard by prefix (first chars, balanced by traffic); cache hot prefixes at CDN/edge and in the browser; debounce keystrokes on the client.
Extras
Personalisation layer, filtering offensive terms, fuzzy matching for typos.
Q7Design YouTube / Netflix (upload + streaming).GoogleNetflixMeta
Upload
Pre-signed URL → resumable upload to object storage → event → transcoding pipeline (DAG of workers) produces multiple resolutions + codecs, split into 2–10 s segments.
Streaming
Adaptive bitrate (HLS/DASH manifests); player switches quality per segment based on bandwidth; segments served from CDN.
Metadata
Video info in a DB, view counts via async counters (Kafka → aggregator), search index, recommendations offline.
Scale
Popular content pre-pushed to edge caches; long tail served from origin/regional caches.
Q8Ticket booking at a flash sale (IRCTC Tatkal / concert drop)?FlipkartGCCsMicrosoft
Virtual waiting room / queue to admit users at a safe rate; seat hold with TTL (Redis SETNX / conditional DB update); payment window; release on expiry; inventory counter decremented atomically; idempotent booking API.
Q9Web crawler?GoogleAmazon
URL frontier (priority + per-host queues for politeness), robots.txt cache, DNS cache, fetchers, parser → extract links → dedupe (Bloom filter on URLs, content hash/simhash), store pages in object storage. Scale by partitioning hosts across workers.
Q10Distributed cache (like Redis Cluster)?AmazonWalmart
Consistent hashing (or 16,384 hash slots) across nodes, replicas per shard with failover, LRU/TTL eviction, client-side routing, hot-key replication, async persistence (snapshot + append-only file).
Q11Distributed job scheduler (cron at scale)?AtlassianUber
Jobs table (next_run_at, indexed); schedulers poll due jobs and claim with a lease (UPDATE … WHERE status='READY' / SKIP LOCKED) → queue → workers; heartbeats, retries, idempotent jobs, history for audit.

💬 Phrases that score

  • "Let me quantify before choosing a DB."
  • "This is read-heavy 100:1, so…"
  • "The failure mode here is ___; I'd handle it by ___."

🚩 Phrases that hurt

  • "We'll just use microservices and Kafka" (no reason).
  • "NoSQL because it scales."
  • Silence while drawing for 5 minutes.

C# / .NET & JavaScript / Node.js

Tier 3 and GCC interviews go deep on your stack; Tier 1 asks these when your resume says "expert in C#".
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

C# / .NET

Q1How does async/await work, and why does .Result cause deadlocks?🔥MicrosoftTCSInfosysAccentureGCCs
  • The compiler rewrites an async method into a state machine. At an await on an incomplete task, the method returns to its caller; the rest is registered as a continuation.
  • For I/O (HTTP, DB, file) no thread is blocked while waiting — the OS signals completion and a thread-pool thread resumes the continuation. That's why async scales servers.
  • The continuation resumes on the captured SynchronizationContext (UI thread, old ASP.NET) if there is one.
  • Deadlock: UI/old ASP.NET thread calls task.Result → blocks the only context thread → the continuation needs that same thread → both wait forever.
💡 Rules: "async all the way", never .Result/.Wait() on async code, ConfigureAwait(false) in library code. ASP.NET Core has no SynchronizationContext, but blocking still starves the thread pool.
↪ CPU-bound work → Task.Run (not for I/O). Many independent calls → await Task.WhenAll(...). Hot path returning cached values → ValueTask.
Q2Value types vs reference types; struct vs class; boxing.MicrosoftTCSCognizantCapgemini

Value types (int, struct, enum) hold data directly and are copied on assignment; reference types (class, string, arrays) hold a reference to a heap object. (Value types live inline — on the stack for locals, inside the object for fields.) Boxing wraps a value type in a heap object when treated as object/interface — allocation + GC cost (e.g. non-generic ArrayList).

Use a struct for small, immutable, value-like data (Point, Money) — ideally ≤ 16 bytes; otherwise class. record gives value-based equality for classes; record struct for structs.

Q3How does the .NET garbage collector work? IDisposable vs finalizer?🔥MicrosoftInfosysHCLTechGCCs
  • Generational, mark-and-compact: Gen0 (new, collected often, cheap) → survivors promoted to Gen1 → Gen2 (long-lived, collected rarely). Objects ≥ 85 KB go to the Large Object Heap (collected with Gen2, not compacted by default).
  • Workstation vs Server GC; background GC reduces pauses.
  • The GC handles memory only. For unmanaged resources (file handles, sockets, DB connections) implement IDisposable and use using for deterministic cleanup.
  • A finalizer (~Class) is a safety net that runs at an unknown time on the finalizer thread and delays collection — call GC.SuppressFinalize(this) in Dispose.
↪ Memory leaks in .NET: static collections growing, event handlers never unsubscribed, caches without size limits, HttpClient created per request (socket exhaustion → use IHttpClientFactory).
Q4IEnumerable vs IQueryable; what is deferred execution?TCSInfosysWiproSalesforce

IQueryable builds an expression tree that the provider (EF Core) translates to SQL — filters run in the database. IEnumerable runs in memory — calling .AsEnumerable() or .ToList() too early pulls the whole table. LINQ is deferred: the query runs when enumerated, and runs again on every enumeration (multiple-enumeration bug).

Q5DI lifetimes — and the "captive dependency" bug?GCCsAccenture
Transient (new each time), Scoped (one per HTTP request — e.g. DbContext), Singleton (one per app). Injecting a Scoped service into a Singleton captures it forever (stale DbContext, threading bugs). ASP.NET Core validates this in Development.
Q6ASP.NET Core middleware pipeline?TCSCognizant
Ordered chain of delegates; each can act before/after calling next() or short-circuit. Order matters: exception handling → HTTPS → static files → routing → CORS → authentication → authorization → endpoints.
Q7const vs readonly vs static readonly?InfosysWipro
const: compile-time, baked into callers (changing it needs recompiling dependents). readonly: set in the constructor, per instance. static readonly: set once at type init, runtime value (e.g. a TimeSpan).
Q8Why is string immutable; when StringBuilder?TCSCapgemini
Immutability gives thread safety, safe hashing as dictionary keys and interning. Each concatenation allocates a new string → in loops use StringBuilder (or string.Join/interpolation for a few parts).
Q9EF Core performance tips?GCCsWalmart
AsNoTracking() for reads, project with Select to DTOs, avoid N+1 (Include / split queries), paginate, compiled queries for hot paths, batch saves, check generated SQL in logs.
Q10How does Dictionary work internally?MicrosoftInfosys
Array of buckets; GetHashCode() picks a bucket, collisions chained; resizes (≈ doubling to a prime) when full → amortised O(1). Override both Equals and GetHashCode for custom keys; never mutate a key's hashed fields.
2

JavaScript / Node.js

call stack main() console.log Web APIs / libuvtimers · fetch · fs · sockets microtask queue ⚡promise .then · await · queueMicrotask macrotask queuesetTimeout · setInterval · I/O callbacks event loop: stack empty → ALL microtasks → ONE macrotask so: sync code → promise callbacks → timers
Fig 14.1 — "microtasks cut the line": every promise callback runs before the next timer fires.
Q11What is the output order? (event loop)🔥MetaMicrosoftAtlassianTCSInfosys
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
(async () => { console.log('D'); await null; console.log('E'); })();
console.log('F');

Answer: A D F C E B. Sync first (A, D — an async function runs synchronously until its first await — then F). Then microtasks in order (C, E). Then the timer macrotask (B).

Q12Closures — and the classic var-in-a-loop bug.🔥MetaAdobeInfosysCognizant
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);   // 3 3 3
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);   // 0 1 2

Answer: A closure is a function bundled with references to the variables of the scope where it was created. var is function-scoped → one shared i (3 when the timers run). let is block-scoped → a fresh binding per iteration. Uses: data privacy (module pattern), memoisation, partial application, React hooks.

Q13Implement debounce. How is throttle different?MetaGoogleFlipkartAtlassian
function debounce(fn, wait) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), wait);
  };
}
const onSearch = debounce(q => fetchSuggestions(q), 300);

Debounce: run once after the calls stop for wait ms (search box). Throttle: run at most once every wait ms while calls continue (scroll / resize handlers).

Q14var vs let vs const; hoisting; TDZ?TCSAccenture
var: function-scoped, hoisted and initialised to undefined. let/const: block-scoped, hoisted but in the temporal dead zone until declared (ReferenceError). const prevents rebinding, not mutation of the object.
Q15How is "this" decided?MetaAdobe
By the call site: obj.f() → obj; plain f() → undefined (strict) / global; new → new object; call/apply/bind → explicit. Arrow functions have no own this — they capture it lexically.
Q16Promise.all vs allSettled vs race vs any?AtlassianInfosys
all: all fulfil or the first rejection. allSettled: waits for every result (status per promise). race: first to settle (timeouts). any: first to fulfil; rejects only if all reject.
Q17Node is single-threaded — how does it handle 10K connections?UberPayPalWalmart
One JS thread + non-blocking I/O via the OS (epoll/kqueue/IOCP) through libuv; a small libuv thread pool handles fs/crypto/DNS. Great for I/O-bound work. CPU-heavy work blocks everyone → worker_threads, child processes or a separate service; scale out with cluster/PM2/containers.
Q18== vs ===; prototypal inheritance?TCSWipro
== coerces types (0 == '' is true); === compares without coercion — always use it. Objects delegate missing properties up the [[Prototype]] chain; class is syntax sugar over prototypes.
🎯 Stack-depth tip
For every buzzword on your resume, prepare: what it is, how it works inside, one production problem it caused you and how you fixed it. That's the Tier 3 / GCC technical round in one sentence.

Docker, Kubernetes & Cloud

Expected from every senior backend engineer; deep-dived in GCC and service-company rounds. Theory: Docker · Kubernetes notebooks.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Docker

Q1Container vs virtual machine.🔥TCSInfosysAccentureSalesforce

Answer: A VM virtualises hardware — each VM runs its own guest OS kernel on a hypervisor (GBs, boots in minutes, strong isolation). A container virtualises the OS — processes share the host kernel, isolated with Linux namespaces (pid, net, mount…) and limited with cgroups (CPU, memory) — MBs, starts in milliseconds, weaker isolation. Many companies run containers inside VMs for both.

Q2How do you make a Docker image small, fast to build and secure?AmazonWalmartGCCsCognizant
# multi-stage: build with the SDK, run on the small runtime image
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY *.csproj ./
RUN dotnet restore                      # cached until the csproj changes
COPY . .
RUN dotnet publish -c Release -o /app

FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app .
USER app                                # non-root
ENTRYPOINT ["dotnet", "Api.dll"]
  • Multi-stage builds; slim/distroless/alpine base images.
  • Layer order: least-changing first (dependency manifests before source) to maximise cache hits; .dockerignore.
  • Combine RUN steps and clean package caches; pin image versions/digests.
  • Run as non-root, no secrets in layers (use build secrets / runtime env from a vault), scan images (Trivy, Defender).
Q3CMD vs ENTRYPOINT; COPY vs ADD?TCSWipro
ENTRYPOINT = the executable; CMD = default args (overridable at docker run). Use exec form ["…"] so signals reach the process (PID 1). COPY copies files; ADD also untars archives and fetches URLs — prefer COPY.
Q4Volumes vs bind mounts?InfosysCapgemini
Volumes are managed by Docker (portable, for persistent data like DB files). Bind mounts map a host path (local dev hot-reload). Container filesystem is ephemeral — data written there dies with it.
Q5Docker networks?Accenture
bridge (default, single host; containers reach each other by name on a user-defined bridge), host (share host network stack), overlay (multi-host, Swarm), none. Compose creates a network per project.
Q6Image vs container?TCSHCLTech
Image = read-only template of stacked layers. Container = a running instance of an image plus a thin writable layer, its own namespaces and cgroups. One image → many containers.
2

Kubernetes

user Ingress host/path rules, TLS Service (ClusterIP) stable IP + DNS, selects by label pod ✓ ready pod ✓ ready pod ✗ not ready ← no traffic Deployment ReplicaSet HPA CPU / custom metrics → replicas rolling update =new RS up, old down
Fig 15.1 — readiness decides traffic, liveness decides restarts, the Deployment decides versions, the HPA decides count.
Q7Explain Kubernetes architecture — what happens on kubectl apply?🔥MicrosoftSalesforceGCCsAccenture
  • Control plane: kube-apiserver (the only door; validates, stores), etcd (consistent key-value store of desired + current state), scheduler (picks a node for unscheduled pods), controller-manager (reconciliation loops: Deployment, ReplicaSet, Node…), cloud-controller-manager.
  • Nodes: kubelet (starts containers via the runtime, reports status, runs probes), kube-proxy (Service routing via iptables/IPVS — or eBPF CNIs), container runtime (containerd).

apply flow: kubectl → API server (authn/authz/admission) → etcd → Deployment controller creates a ReplicaSet → RS controller creates Pods → scheduler binds pods to nodes → kubelet pulls image and starts containers → readiness passes → endpoints added to the Service.

💡 Everything is a reconciliation loop: controllers keep moving actual state toward desired state.
Q8Liveness vs readiness vs startup probes.🔥MicrosoftWalmartGCCs
  • Readiness fails → pod removed from Service endpoints (no traffic), not restarted. Use for warm-up, dependency outages, draining.
  • Liveness fails → kubelet restarts the container. Use only for "stuck/deadlocked" detection.
  • Startup → disables the others until the app has started (slow-booting apps).
⚠️ Liveness that checks the database → DB blip restarts every pod at once (cascading failure). Keep liveness shallow; put dependencies in readiness.
Q9A pod is in CrashLoopBackOff. How do you debug it?🔥TCSInfosysGCCsPayPal
kubectl get pods -o wide                      # restarts count, node
kubectl describe pod <pod>                    # events: OOMKilled? probe failed? image pull?
kubectl logs <pod> --previous                 # logs of the crashed container
kubectl get events --sort-by=.lastTimestamp
kubectl exec -it <pod> -- sh                  # if it stays up long enough

Common causes: app exits on missing config/secret or bad connection string, OOMKilled (memory limit too low), liveness probe too aggressive, wrong command/entrypoint, missing file permissions when running non-root.

Q10Requests vs limits; how does autoscaling work?AmazonMicrosoftFlipkart
  • Request = what the scheduler reserves (placement). Limit = hard cap: CPU over limit → throttled; memory over limit → OOMKilled.
  • QoS classes: Guaranteed (requests = limits), Burstable, BestEffort (evicted first).
  • HPA scales pod replicas on CPU/memory/custom metrics (e.g. queue length via KEDA). VPA adjusts requests. Cluster Autoscaler / Karpenter adds nodes when pods are unschedulable.
Q11Deployment vs StatefulSet vs DaemonSet vs Job?GCCsSalesforce
Deployment: stateless replicas. StatefulSet: stable names (db-0, db-1), ordered rollout, a PVC per pod (databases, Kafka). DaemonSet: one pod per node (log/metrics agents). Job/CronJob: run to completion / on a schedule.
Q12Service types & Ingress?InfosysAccenture
ClusterIP (internal), NodePort (port on every node), LoadBalancer (cloud LB per service), ExternalName (DNS alias). Ingress = one L7 entry point routing many hosts/paths to services (needs an ingress controller; Gateway API is the successor).
Q13ConfigMap vs Secret?TCSWipro
Both inject config as env vars or files. Secrets are only base64-encoded by default — enable encryption at rest in etcd, RBAC-restrict them, or sync from a vault (External Secrets / CSI driver).
Q14Rolling vs blue-green vs canary?NetflixIntuitGCCs
Rolling: replace pods gradually (maxSurge/maxUnavailable) — default. Blue-green: full new stack, switch traffic at once, instant rollback, 2× cost. Canary: small % of traffic to the new version, watch metrics, then ramp (Argo Rollouts / service mesh).
3

Cloud & delivery

Q15IaaS vs PaaS vs SaaS?TCSCognizant
IaaS: you manage OS and up (EC2, Azure VMs). PaaS: you deploy code, provider runs the platform (App Service, Elastic Beanstalk, Cloud Run). SaaS: you just use the software (M365, Salesforce).
Q16Describe your CI/CD pipeline.All T3Intuit
PR → build + unit tests + lint + SAST → image build + scan → push to registry → deploy to dev (IaC: Terraform/Bicep, Helm) → integration tests → staging → approval → prod canary → monitor → full rollout / auto-rollback.
Q17Zero-downtime deploy with a DB schema change?AmazonAtlassian
Expand → migrate → contract: add the new column (nullable) → deploy code that writes both and reads new-with-fallback → backfill → switch reads → later drop the old column. Never rename in one step.
Q18AWS ↔ Azure service map (quick)?GCCsAccenture
EC2 ↔ VMs · S3 ↔ Blob Storage · Lambda ↔ Functions · EKS ↔ AKS · RDS ↔ Azure SQL · DynamoDB ↔ Cosmos DB · SQS ↔ Service Bus queues · SNS ↔ Event Grid/Service Bus topics · CloudWatch ↔ Azure Monitor · IAM ↔ Entra ID + RBAC.

AI / ML & LLM Interview Q&A

Now asked to every backend engineer: "How would you add an LLM feature?" History & foundations: AI Notes book.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

ML fundamentals (still asked)

Q1Supervised vs unsupervised vs reinforcement learning?TCSInfosys
Supervised: labelled examples → predict (spam, price). Unsupervised: find structure without labels (clustering, anomaly detection). RL: agent learns from rewards (games, robotics; RLHF tunes LLMs on human preferences).
Q2Overfitting vs underfitting?AmazonAccenture
Overfit: great on train, poor on test (high variance) → more data, regularisation (L1/L2, dropout), early stopping, simpler model. Underfit: poor on both (high bias) → richer features/model, train longer.
Q3Precision vs recall — which matters when?GooglePayPal
Precision = of predicted positives, how many are right (spam filter: don't bin real mail). Recall = of real positives, how many we caught (cancer screening, fraud). F1 = harmonic mean. Accuracy misleads on imbalanced data.
Q4How does a neural network learn?InfosysCapgemini
Forward pass → loss → backpropagation computes gradients via the chain rule → gradient descent (SGD/Adam) nudges weights against the gradient by the learning rate. Repeat over mini-batches/epochs.
2

LLMs

Q5Explain how a Transformer / LLM works in 2 minutes.🔥GoogleMicrosoftMetaAdobe
  1. Text → tokens (sub-words) → embeddings (vectors) + position information.
  2. Each layer uses self-attention: every token builds a Query, Key and Value; attention weights = softmax(Q·Kᵀ / √d); the output mixes Values — so each token "looks at" the tokens most relevant to it. Multi-head = several such views in parallel. Then a feed-forward network.
  3. Decoder-only LLMs are trained to predict the next token on huge text corpora (causal mask: can't see the future), then instruction-tuned and preference-tuned (RLHF/DPO).
  4. Generation = sample one token at a time; temperature/top-p control randomness.
↪ Why better than RNNs? Parallel training over the whole sequence and direct long-range connections (no vanishing gradients across steps). Cost: attention is O(n²) in sequence length → context-window limits, KV cache at inference.
Q6What are embeddings and how does vector search work?AmazonAtlassianSalesforce

Answer: An embedding model maps text (or images) to a vector so that similar meanings are close (cosine similarity / dot product). Vector stores (pgvector, Azure AI Search, OpenSearch, Pinecone…) use approximate nearest neighbour indexes such as HNSW or IVF to find top-k neighbours in milliseconds among millions of vectors, trading a little recall for speed. Combine with keyword search (BM25) = hybrid search.

OFFLINE (ingest) docs, wiki chunk + clean embed vector index ONLINE (query) question embed + BM25 top-k + rerank LLM answer +citations prompt = instructions + retrieved chunks + question ("answer only from context")
Fig 16.1 — RAG: retrieval quality decides answer quality. Most "LLM bugs" are retrieval bugs.
Q7Design a RAG-based Q&A bot over company documents.🔥MicrosoftAmazonAtlassianSalesforceAccenture
Ingest
Connectors → parse (PDF, HTML, tables) → chunk (~300–800 tokens, overlap, split on headings) → metadata (source, ACL, date) → embed → index. Incremental re-index on change.
Retrieve
Hybrid (vector + keyword) → filter by user's permissions (ACL in metadata!) → rerank with a cross-encoder → top 5–10 chunks.
Generate
System prompt: answer only from context, cite sources, say "I don't know". Stream tokens to the UI.
Evaluate
Golden Q&A set; retrieval metrics (recall@k), answer faithfulness/groundedness, LLM-as-judge + human review; online thumbs up/down.
Production
Caching (exact + semantic), cost per query, latency budget, PII redaction, prompt-injection defences, logging for audits.
Q8Prompting vs RAG vs fine-tuning — how do you choose?GoogleMetaIntuit
PromptingRAGFine-tuning (e.g. LoRA)
AddsInstructions, examplesFresh / private knowledgeBehaviour: style, format, domain skill
CostLowestMedium (index infra)Highest (data, training, re-training)
UpdateInstantRe-index docsRe-train

Order: prompt well → add RAG for knowledge → fine-tune only for consistent behaviour/latency/cost at scale (smaller tuned model).

Q9How do you reduce hallucinations?MicrosoftAdobe
Ground with RAG + citations, instruct to abstain, lower temperature, structured outputs (JSON schema) validated in code, tool calls for facts (calculators, DB lookups), verification step, evals that measure faithfulness.
Q10What is an AI agent / tool calling?GoogleAtlassian
The model is given tool schemas; it decides to call a tool (search, API, code), your code executes it and returns results; loop until done. Protocols like MCP standardise tool access. Risks: loops, cost, unsafe actions → limits, human approval for side effects.
Q11What is prompt injection; how do you defend?MicrosoftPayPal
Untrusted content (a web page, email, doc) contains instructions the model follows. Defend: treat retrieved text as data, least-privilege tools, allow-lists, confirmation for side effects, output filtering, separate privileged/unprivileged models.
Q12How do you cut LLM cost and latency?AmazonSwiggy
Route easy requests to smaller models, prompt/semantic caching, shorter prompts (fewer, better chunks), streaming, batching offline jobs, quantised self-hosted models for high volume, cap output tokens.
3

AI-assisted coding rounds (Meta pilot, others following)

Q13How should I use the AI assistant in an AI-enabled interview round?🔥MetaGoogleMicrosoft
First 3–5 min: no AI
Read the codebase and the task yourself. Explain the structure and your plan aloud — they are scoring your understanding.
Prompt precisely
Give the AI the data structure / algorithm, the language, constraints and the quality bar ("O(n log n), handle empty input, keep the existing interface").
Review every line
Read generated code before using it; point out what you'd change. Blind paste = red flag.
Verify
Run tests, add edge cases, debug failures yourself; ask the AI for test ideas, not just code.
Narrate trade-offs
Why this approach, what the AI got wrong, what you'd do in production.
⚠️ The signal is judgment: decomposition, validation and debugging. Using AI to skip understanding loses the round even if tests pass.
🎯 One-liner for any GenAI design
"Retrieval for knowledge, prompts for behaviour, tools for facts and actions, evals before launch, guardrails and cost controls in production."

Behavioral Q&A — STAR, LPs & Values

At senior level this decides your level. Example answers below are templates — swap in your own real stories and numbers.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

STAR, with the right proportions

S T A R ~10%~10%~60% — "I" did…~20% + numbers Situation: context in 2 lines Task: your responsibility / the goal Action: 3–4 concrete steps, decisions, trade-offs Result: metric, impact, + what you learned 2–3 minutes total. Then stop and let them dig.
Fig 17.1 — most weak answers are 50% situation. Interviewers score the Action and the Result.

📒 Build a story bank (8–10)

  • Hardest technical problem
  • Production incident you led
  • Conflict / disagreement
  • Failure / mistake
  • Influence without authority
  • Mentoring / growing someone
  • Ambiguous project you shaped
  • Customer-driven decision

🎯 Senior signals

  • Scope beyond your team
  • Trade-offs stated explicitly
  • Numbers: latency, cost, %, people
  • You changed a process, not just code
  • Honest learning from failure

🏢 What each company calls it

  • Amazon: 16 Leadership Principles
  • Google: Googleyness & Leadership
  • Meta: ambiguity, conflict, growth, impact
  • Atlassian: 5 values (page 2)
  • Microsoft: growth mindset, collaboration
2

Amazon's 16 Leadership Principles → the question you'll hear

PrincipleTypical question
Customer ObsessionTell me about a time you went beyond what the customer asked for.
OwnershipA time you took on something outside your responsibility.
Invent and SimplifyA time you simplified a complex process or system.
Are Right, A LotA decision you made with incomplete data. Were you right?
Learn and Be CuriousSomething you learned recently on your own and applied.
Hire and Develop the BestHow you mentored someone / raised the bar in hiring.
Insist on the Highest StandardsA time you refused to ship something that wasn't good enough.
Think BigA bold idea you proposed that changed direction.
Bias for ActionA time you acted quickly on a calculated risk.
FrugalityAccomplished more with less (cost, people, time).
Earn TrustA time you admitted a mistake / received hard feedback.
Dive DeepA problem where the root cause was hidden; how did you find it?
Have Backbone; Disagree and CommitYou disagreed with your manager — what happened?
Deliver ResultsA time you delivered despite a major obstacle.
Strive to be Earth's Best EmployerHow you made your team's work environment better / safer / more inclusive.
Success and Scale Bring Broad ResponsibilityA decision where you considered the wider impact (users, community, long-term).
3

Top questions with worked answers

Q1"Tell me about yourself."🔥All T1All T2All T3

Formula (90 s): Present → Past → Why you're here.

"I'm a senior backend engineer with 8+ years, mostly C#/.NET and distributed systems on Azure. Right now I lead the payments-integration team of 5 at ___, where I re-architected our settlement pipeline from nightly batches to event-driven processing on Kafka — settlement time dropped from ~8 hours to under 10 minutes. Before that I built ___ at ___, which taught me ___. I'm looking for a role with larger-scale distributed problems and more architecture ownership, which is why this team's work on ___ excites me."

⚠️ Not your life story, not a resume read-out. End with a hook they can ask about.
Q2"Tell me about a conflict with a teammate or manager."🔥MetaAmazonGoogleAtlassian

Example:

  • S/T: A peer tech lead wanted to add a synchronous call from checkout to a new recommendations service; I owned checkout reliability (99.95% SLO).
  • A: I asked to understand his goal first (conversion uplift); shared data showing the new service's p99 was 900 ms; proposed an async alternative — precompute recommendations and read from cache with a 50 ms timeout and fallback. We ran a one-week experiment comparing both.
  • R: The async version gave the same conversion uplift with no impact on checkout latency; we adopted it and wrote it up as a team guideline for calling non-critical services.
  • Learning: Disagree on data, not opinions; align on the shared goal first.
⚠️ Never make the other person the villain; never pick a story where you simply gave in or simply "won".
Q3"Tell me about a time you failed / made a mistake."🔥AmazonGoogleNetflixAll T3
  • S/T: I shipped a database migration that added an index on a 400M-row table during business hours.
  • A: It locked writes and caused 12 minutes of order failures. I rolled it back, then led the post-mortem (blameless): we had no migration review checklist and staging data was 1% of prod. I added online index creation, a migration checklist in PR templates and a prod-sized staging snapshot.
  • R: No migration-related incidents in the following 18 months; the checklist was adopted by 3 other teams.
💡 A real failure with real impact + ownership + systemic fix. "I work too hard" answers fail.
Q4"Describe the most complex technical problem you solved." (Dive Deep)AmazonUberFlipkartGCCs

Shape: symptom → hypotheses → evidence → root cause → fix → prevention.

Example: "p99 latency spiked every ~20 minutes. Metrics showed Gen2 GC pauses aligned with spikes. A memory dump revealed a static dictionary cache growing without bounds (per-tenant keys). I replaced it with a size-bounded MemoryCache with TTL, and added an alert on Gen2 collections. p99 went from 1.8 s to 220 ms."

Q5"Tell me about a time you influenced without authority."GoogleMetaMicrosoftAtlassian

Show: understanding others' incentives, building evidence (prototype, data, RFC), finding allies, making adoption easy (library, docs, migration script), and credit-sharing. Example: drove adoption of structured logging + trace IDs across 6 teams via an RFC, a NuGet package and pairing sessions → mean time to diagnose incidents fell ~40%.

Q6"Tell me about a time you had to make a decision with incomplete information / under a tight deadline."AmazonMetaSwiggy

Show how you separated reversible from irreversible decisions (two-way vs one-way doors), what minimum data you gathered, the risk you accepted, the mitigation (feature flag, rollback plan), and the outcome. Mention what you cut from scope and how you communicated it.

Q7"How do you mentor engineers?"GoogleHM rounds
One concrete person: where they started, what you did (stretch project, design-review pairing, feedback cadence), and their outcome (promotion, owned a component). Mention adapting style to the person.
Q8"Disagree and commit" example?Amazon
You argued with data, the decision went the other way, you committed fully (no sandbagging), and — key — you helped make it succeed. Bonus: how you'd revisit with new data.
Q9"How do you handle critical feedback?"MetaMicrosoft
Real feedback you got (e.g. "your design docs are too long for execs"), how you acted (one-page summaries, asked for review), and evidence it worked. Shows growth mindset.
Q10"Time you handled ambiguity?"MetaGoogle
Vague goal → you defined the problem, metrics and milestones, ran a spike/prototype, got stakeholder alignment, iterated. The structure you created is the signal.
Behavioral red flags
  • "We" everywhere — interviewer can't find your contribution.
  • No numbers or outcomes; or a story from 8 years ago for a senior role.
  • Blaming others, badmouthing the current employer.
  • Same story reused for 3 different questions in one loop.
  • Rambling past 4 minutes.

Senior / Staff, Managerial & HR Rounds

The rounds people prepare least — and where offers, levels and money are actually decided.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Project deep dive & hiring-manager round

Q1"Walk me through the most significant project you've worked on."🔥UberGoogleFlipkartAll T3
Why it mattered (1 min)
Business problem + metric: "checkout failures cost ~2% of orders".
Architecture (3–4 min)
Draw it: components, data flow, scale numbers (QPS, data size, team size).
Your part (2 min)
What you designed/decided/led vs what the team did.
Hardest decision (3 min)
Two options, trade-offs, why you chose one, what it cost.
What broke + what you'd change (2 min)
Incidents, tech debt, the redesign you'd do today. Shows maturity.
⚠️ Be ready for "why not X?" on every box you draw. If you can't defend a component, leave it out.
Q2"How do you balance tech debt against feature work?"MicrosoftAtlassianIntuit

Make debt visible and priced: tie it to metrics (incident count, lead time, on-call pages, cost). Reserve a steady capacity slice (e.g. 15–20% per sprint), bundle refactors with features touching the same code, and escalate debt that blocks roadmap goals with a business case. Example with numbers beats philosophy.

Q3"A team member is underperforming. What do you do?"HM roundsManagerial
Private 1:1 to understand causes (clarity, skills, personal) → specific, observable feedback → agree on goals + support (pairing, smaller scoped tasks) → check in weekly → document; escalate to the manager if no change. Empathy + accountability.
Q4"How do you estimate work?"TCSInfosysAccenture
Break into tasks; relative sizing (story points / T-shirt) with the team; compare to past velocity; add risk buffer for unknowns; re-estimate after a spike. Communicate ranges ("2–3 sprints, 80% confident"), not single dates.
Q5"Client changes requirements mid-sprint / escalates?"AccentureCognizantCapgemini
Acknowledge, understand the business reason, show impact on scope/timeline/cost transparently, offer options (swap a story, next sprint, phased delivery), get written sign-off via the change process. Stay calm; facts, not defensiveness.
Q6"Production is down at 2 AM — walk me through it."AmazonGCCs
Acknowledge + incident channel + roles → mitigate first (rollback, feature flag, failover, scale) → communicate status regularly → root cause after recovery → blameless post-mortem with action items and owners.
Q7Staff-level: "How do you set technical direction for multiple teams?"GoogleMetaUber

Start from business goals → identify the few cross-team technical bets → write a strategy doc / RFCs with options and trade-offs → get buy-in from tech leads and managers (pre-wire 1:1s) → define success metrics and milestones → build paved roads (libraries, templates) so the right thing is the easy thing → review progress quarterly, and kill bets that aren't working.

↪ Have one story of stopping a project or migration — saying no with data is a strong staff signal.
2

HR round — India specifics

"CTC" is a bundle — compare offers component by component fixed / base (monthly in-hand) variable joining RSUs (per year) % paid depends on rating one-time, clawback if you leave early vesting over 4 years: even 25 · 25 · 25 · 25 back-loaded e.g. 5 · 15 · 40 · 40 (Amazon)year-1 cash comes via sign-on bonus
Fig 18.1 — compare year-1 cash and 4-year total; fixed pay is the only part that's guaranteed.
Q8"What is your current and expected CTC?"🔥All T1All T2All T3
  • Current: be honest and break it down (fixed, variable, stock, bonus) — Indian companies often ask for payslips/offer letters, so inflated numbers backfire.
  • Expected: anchor on the role and market, not a hike %: "Based on the scope of this senior role and offers in the market, I'm looking at ₹__ fixed and total comp in the ₹__–__ range. I'm flexible on the mix."
  • Early in the process, you can defer: "I'd like to understand the role and level first; I'm sure we can align if it's the right fit."
  • Research bands (levels.fyi, AmbitionBox, Glassdoor, peers) for that company + level before the call.
Q9How do I negotiate the offer?🔥AllAll
  1. Get the offer in writing with the full breakdown; thank them, ask for a few days.
  2. Negotiate on level first (biggest long-term lever), then total comp.
  3. Use real competing offers or data; be specific: "If you can get the fixed to ₹__ or add a joining bonus of ₹__, I'm ready to sign."
  4. Trade components: if fixed is capped by band, ask for joining bonus, more RSUs, earlier review, relocation, or notice-period buyout.
  5. Stay warm and collaborative — the recruiter is negotiating for you internally.
⚠️ Don't accept verbally and keep shopping; don't bluff with offers you don't have.
Q10"What is your notice period? Can you join early?"All T3FlipkartWalmart

State it exactly (e.g. 60/90 days) and what's realistic: "My notice is 90 days; I can try to negotiate an early release to ~60 days after handover. A buyout is possible if you support it." Never claim you can join in 30 days if you can't — offers get revoked over this.

Q11"Why are you leaving your current company?"🔥All
Positive, future-facing: "I've grown a lot here — led X and Y. I'm looking for larger-scale problems / deeper architecture ownership, which this role offers." Never badmouth. Layoff? Say it plainly and move on.
Q12"Why this company?"AllAll
Three specifics: the product/problem (name it), the engineering culture (a blog post, open-source project, talk), and how your experience fits their current challenge.
Q13"Strengths and weaknesses?"TCSInfosys
Strength with evidence ("debugging distributed systems — e.g. ___"). Weakness that is real, not fatal, and being fixed ("I used to over-engineer early; now I write a one-page design and timebox spikes").
Q14"Will you accept a counter-offer?"HRHR
Decide before interviewing. If your reasons are growth/scope, money rarely fixes them — say "I'm moving for the role, not only compensation." Companies ask because counter-offer drop-outs are common in India.
Q15Explaining a career gap?All
One honest sentence on why (layoff, health, family, study), then what you did to stay sharp (projects, certifications, open source) and that you're fully ready now.
Q16Questions to ask them at the end?🔥All
"What does success look like in the first 6 months?" · "What's the biggest technical challenge the team faces this year?" · "How are on-call and incidents handled?" · "How do engineers grow to the next level here?"
🎯 Takeaway
Level > CTC. Fixed > variable. Written > verbal. Honest numbers always — background verification checks payslips and dates.

Matrix, Bit Manipulation & String Puzzles

The "trick" questions — easy once you have seen the move, brutal if you haven't. Common in Microsoft, Amazon, Google phone screens and T3 OAs.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Matrix

123 456 789 original transposeswap m[i][j], m[j][i] 147 258 369 transposed reverse rows 741 852 963 rotated 90° ↻ anticlockwise?transpose, thenreverse columns
Fig 19.1 — two simple in-place passes beat juggling four corners. O(n²) time, O(1) space.
Q1Rotate Image (n×n, 90° clockwise, in place).🔥MicrosoftAmazonAdobeTCS
int n = m.Length;
for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++)                 // upper triangle only
        (m[i][j], m[j][i]) = (m[j][i], m[i][j]);
foreach (var row in m) Array.Reverse(row);
⚠️ Starting j at 0 swaps every pair twice and undoes the transpose.
Q2Spiral Matrix — return elements in spiral order.MicrosoftAmazonGoogleInfosys

Answer: Keep four walls top, bottom, left, right. Walk right along top (top++), down the right wall (right--), then — only if top ≤ bottom — left along bottom (bottom--), and only if left ≤ right — up the left wall (left++). Repeat while top ≤ bottom and left ≤ right. O(m·n).

⚠️ The two "only if" checks prevent double-printing the middle row/column of non-square matrices.
Q3Set Matrix Zeroes with O(1) extra space.MetaMicrosoftWalmart

Answer: Use the first row and first column as marker arrays. First remember (two booleans) whether row 0 / column 0 themselves contain a zero. Mark m[i][0] = m[0][j] = 0 for every zero cell, then zero cells (i, j ≥ 1) whose row or column marker is 0, and finally zero row 0 / column 0 if the booleans say so. O(m·n) time, O(1) space.

Q4Search a row- and column-sorted 2D matrix?AmazonMicrosoft
Start at the top-right: bigger than target → move left; smaller → move down. Each step discards a row or column → O(m + n). (Fully sorted "row continues the previous" matrix → one binary search over m·n.)
Q5Game of Life in place?GoogleAtlassian
Encode old and new state in the same cell: e.g. 2 = "was alive, now dead", 3 = "was dead, now alive"; count neighbours using the old state (value % 2 or a check for 1/2), then a second pass maps 2→0, 3→1.
2

Bit manipulation

n = 12 → 1 1 0 0 n - 1 = 11 → 1 0 1 1 n & (n-1) → 1 0 0 0 lowest 1-bit and everything after it flip… …so AND wipes exactly that one bit power of two ⇔ n > 0 and n & (n-1) == 0 count 1-bits: repeat until n == 0 (Kernighan)
Fig 19.2 — the single most reused bit trick in interviews.
Q6Single Number — every element appears twice except one.🔥AmazonAdobeTCSWipro

Answer: XOR everything: a ^ a = 0, a ^ 0 = a, and XOR is commutative → the pairs cancel. O(n) / O(1).

↪ Every other number appears three times → count each bit position mod 3. Two singles → XOR all to get x^y, split numbers by any set bit of that result, XOR each group.
Q7Counting Bits — number of 1s for every i in 0..n.AmazonAppleAdobe
var bits = new int[n + 1];
for (int i = 1; i <= n; i++) bits[i] = bits[i >> 1] + (i & 1);   // drop last bit, add it back

Alternative: bits[i] = bits[i & (i - 1)] + 1. Both O(n).

Q8Missing Number in 0..n?MicrosoftInfosysCognizant
XOR all indices 0..n with all values — the missing one survives. Or n(n+1)/2 − sum (watch overflow → long). Sorting is O(n log n) and not needed.
Q9Generate all subsets with bitmasks?MetaUber
For mask 0..2ⁿ−1, element i is in the subset if (mask >> i) & 1. O(n·2ⁿ). Same idea powers bitmask DP (TSP-style, n ≤ 20).
Q10Add two integers without + or −?MetaApple
Sum without carry = a ^ b; carry = (a & b) << 1. Repeat with a = sum, b = carry until carry is 0. Works for negatives in two's complement with fixed-width ints.
Q11Useful bit one-liners?TCSAccenture
Check bit: (n >> i) & 1 · set: n | (1 << i) · clear: n & ~(1 << i) · toggle: n ^ (1 << i) · lowest set bit: n & -n · odd: (n & 1) == 1.
3

String puzzles

Q12Find a pattern in text in O(n + m) — explain KMP.GoogleMicrosoftAdobe

Answer: Precompute lps[i] = length of the longest proper prefix of pattern[0..i] that is also a suffix. On a mismatch, instead of restarting, jump the pattern pointer to lps[j-1] — the text pointer never moves backwards.

int[] lps = new int[p.Length];
for (int i = 1, len = 0; i < p.Length; ) {
    if (p[i] == p[len]) lps[i++] = ++len;
    else if (len > 0) len = lps[len - 1];
    else lps[i++] = 0;
}
for (int i = 0, j = 0; i < s.Length; ) {
    if (s[i] == p[j]) { i++; j++; if (j == p.Length) return i - j; }
    else if (j > 0) j = lps[j - 1];
    else i++;
}
return -1;                                     // (empty pattern → return 0 up front)
↪ Alternatives to name: Rabin-Karp (rolling hash, great for many patterns / plagiarism), Z-algorithm. In production: IndexOf(…, StringComparison.Ordinal).
Q13Decode String: "3[a2[c]]" → "accaccacc".🔥GoogleAmazonAtlassianFlipkart

Answer: Two stacks: counts and partial strings. Digit → build k (multi-digit!). [ → push (k, current), reset. ] → pop (k, prev), current = prev + current × k. Letter → append. Use StringBuilder. Time = O(output length).

Q14Basic Calculator II ("3+2*2", no parentheses).MetaAmazonUber

Answer: Keep the running result and the last term; + and − commit the last term, * and / modify it (precedence for free). O(n) time, O(1) space.

int result = 0, last = 0, num = 0; char op = '+';
for (int i = 0; i <= s.Length; i++) {
    char c = i < s.Length ? s[i] : '+';          // sentinel flushes the last number
    if (char.IsDigit(c)) { num = num * 10 + (c - '0'); continue; }
    if (c == ' ') continue;
    if (op == '+')      { result += last; last = num; }
    else if (op == '-') { result += last; last = -num; }
    else if (op == '*') last *= num;
    else                last /= num;              // truncates toward zero, as required
    op = c; num = 0;
}
return result + last;
↪ With parentheses (Calculator I/III) → recursion on "(" or a stack of (result, sign) frames.
Q15String to Integer (atoi) — what edge cases?MicrosoftAmazonTCS
Leading spaces, optional single sign, stop at first non-digit, empty/only-sign input → 0, overflow → clamp to int.MinValue/MaxValue (check before multiplying: res > (int.MaxValue - d) / 10).
Q16Valid Palindrome II (delete at most one char)?MetaInfosys
Two pointers; at the first mismatch, return isPal(L+1..R) || isPal(L..R−1). O(n). Meta's #1 warm-up for years.
Q17Reorganize String (no two equal neighbours)?AmazonGoogle
Impossible if max frequency > (n+1)/2. Else max-heap by count: take the top, append, hold it back one round. Or fill even indices with the most frequent letter first, then the rest. O(n log k).
Q18Reverse words in a string in place?TCSWiproCapgemini
Reverse the whole char array, then reverse each word; squeeze extra spaces with a write pointer. O(n), O(1) extra if the language allows mutable strings (char[] in C#).
✅ Practice set
  • Diagonal Traverse M
  • Word Search (grid DFS) M
  • Reverse Bits E
  • Bitwise AND of Numbers Range M
  • Repeated DNA Sequences (rolling hash) M
  • Integer to English Words H
  • Text Justification H
  • Basic Calculator (with parentheses) H

Hard Tier-1 Patterns & Design-a-DS

The second question of a Google/Meta round, and Tier 2's favourite "design a class" problems.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Monotonic deque

Q1Sliding Window Maximum in O(n).🔥GoogleAmazonAtlassianUber

Answer: Deque of indices whose values are decreasing. For each i: drop the front if it left the window; pop the back while its value ≤ nums[i] (they can never be a max again); push i; the front is the window max. Each index enters and leaves once → O(n).

var dq = new LinkedList<int>(); var res = new List<int>();
for (int i = 0; i < nums.Length; i++) {
    if (dq.Count > 0 && dq.First.Value <= i - k) dq.RemoveFirst();         // out of window
    while (dq.Count > 0 && nums[dq.Last.Value] <= nums[i]) dq.RemoveLast(); // useless now
    dq.AddLast(i);
    if (i >= k - 1) res.Add(nums[dq.First.Value]);
}
inums[i]deque (values)window max
01[1]—
13[3] (1 popped)—
2−1[3, −1]3
3−3[3, −1, −3]3
45[5] (3 expired, −3, −1 popped)5
53[5, 3]5
66[6]6
77[7]7
↪ Same deque trick: Shortest Subarray with Sum ≥ K (with prefix sums, negatives allowed), Constrained Subsequence Sum, Jump Game VI.
2

Design a data structure

weights [1, 3, 2] → prefix [1, 4, 6] A B C 0146 r = 3 → first prefix ≥ 3 is 4 → B P(B) = 3/6
Fig 20.1 — Random Pick with Weight: prefix sums + binary search. O(n) build, O(log n) per pick.
Q2Insert, Delete, GetRandom — all O(1).🔥MetaAmazonFlipkartLinkedIn

Answer: List<int> for O(1) random index + Dictionary<int,int> value → index. Delete: move the last element into the deleted slot, update its index in the map, remove the last slot. GetRandom: list[rng.Next(list.Count)].

↪ Duplicates allowed → map value → HashSet of indices.
Q3Time-Based Key-Value Store: set(key, value, t), get(key, t) → latest value at or before t.GoogleAtlassianNetflix

Answer: Dictionary<string, List<(int t, string v)>>; timestamps arrive increasing, so each list stays sorted. get → binary search for the last entry with time ≤ t. set O(1), get O(log n).

↪ Out-of-order timestamps → SortedList/SortedDictionary per key. This is MVCC in miniature — mention it.
Q4Design a Hit Counter (hits in last 5 min)?GoogleUberAtlassian
Queue of timestamps, pop older than t−300 (exact, memory ∝ hits). Scale: two arrays of 300 buckets (time, count) indexed by t % 300 — O(1) memory. Concurrent: lock per bucket or Interlocked counters.
Q5Design an LFU cache in O(1)?AmazonGoogle
key → (value, freq); freq → ordered set of keys (LRU order within a frequency); track minFreq. On access move the key to freq+1; evict from minFreq's oldest. Full code: DSA p.5.
Q6Flatten a Nested List Iterator?MetaGoogleLinkedIn
Stack of enumerators (lazy, O(depth) memory). HasNext() does the work: while the top is a list, push its enumerator; pop exhausted ones. Next() just returns the prepared integer.
Q7Median of a sliding window?GoogleAmazon
Two heaps with lazy deletion (a map of "to delete" counts, cleaned when they reach the top) or two SortedSets of (value, index). O(n log k).
3

Hard DP

Q8Regular Expression Matching with '.' and '*'.GoogleMetaUber

Answer: dp[i][j] = does s[0..i) match p[0..j). If p[j−1] is '*': zero copies → dp[i][j−2], or one more copy → dp[i−1][j] when s[i−1] matches p[j−2]. Else: dp[i−1][j−1] when chars match (or p is '.'). Base: dp[0][0] = true; dp[0][j] = p[j−1]=='*' && dp[0][j−2] (patterns like "a*b*" match empty). O(m·n).

Q9Burst Balloons — the "interval DP" template.GoogleMicrosoft

Answer: Pad with 1s at both ends. Think about the balloon burst last in (l, r): its neighbours are then l and r, and the two sides are independent. dp[l][r] = max over k of dp[l][k] + dp[k][r] + a[l]·a[k]·a[r], filled by increasing interval length. O(n³).

💡 "Choose the last action, not the first" turns dependent sub-problems into independent ones. Same for Matrix-Chain Multiplication and Minimum Cost to Cut a Stick.
Q10Longest Valid Parentheses?AmazonMeta
Stack of indices seeded with −1. "(" → push i. ")" → pop; if empty push i (new base) else length = i − top. O(n). Or two counter passes (left→right, right→left), O(1) space.
Q11Longest Increasing Path in a Matrix?GoogleMeta
DFS from every cell with memo[r][c] = 1 + max over strictly larger neighbours. "Strictly increasing" means no cycles, so memoised DFS is safe. O(m·n).
4

Hard graphs

Q12Critical Connections (bridges) in a network?AmazonGoogle
Tarjan: DFS with discovery time disc[u] and low[u] = earliest discovery reachable via the subtree plus one back edge. Edge (u, v) is a bridge if low[v] > disc[u]. O(V + E).
Q13Parallel Courses / minimum semesters?GoogleUber
Kahn's BFS level by level — each level is one semester; answer = number of levels, −1 if a cycle leaves nodes unprocessed. Longest path in a DAG = DP in topological order.
Q14Bus Routes (fewest buses)?GoogleUber
BFS over routes, not stops: map stop → routes; start with routes containing the source; mark visited routes and stops. Level = buses taken. O(sum of route lengths).
Q15Shortest path visiting all nodes (n ≤ 12)?Google
BFS over state (node, visitedMask), starting from every node at once; the first state with all bits set gives the answer. O(2ⁿ · n²). Recognise "n ≤ 20" → bitmask state.
✅ Practice set
  • Shortest Subarray with Sum ≥ K H
  • Design Twitter M
  • Snapshot Array M
  • Wildcard Matching H
  • Distinct Subsequences H
  • Minimum Cost to Cut a Stick H
  • Reconstruct Itinerary H
  • Making a Large Island H

System Design II — More Blueprints

Same 45-minute shape as page 13. These are the "second wave" problems seniors get once the classics are known.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Storage, collaboration & logs

Q1Design Google Docs (real-time collaborative editing).GoogleMicrosoftAtlassian
Core problem
Two users edit the same paragraph at once; everyone must converge to the same text without locking.
Algorithms
OT (Operational Transformation): a central server orders operations and transforms concurrent ones against each other (Google Docs style). CRDT: each character gets a unique, ordered ID so replicas merge without a central order (works offline / peer-to-peer; more metadata).
Architecture
WebSocket gateway → document session server (one owner per doc, sticky by doc_id) holding the live state → operation log (append-only) + periodic snapshots in storage. Presence/cursors via a lightweight pub/sub channel.
Deep dives
Reconnect: client sends last acked version, server replays ops since then. Version history = snapshots + op log. Permissions checked per op. Comments anchored to character IDs.
Q2Design Dropbox / Google Drive (file sync).🔥GoogleAmazonMicrosoftAtlassian
Upload
Client splits files into ~4 MB chunks, hashes each (SHA-256); asks the server which hashes are new; uploads only those via pre-signed URLs to object storage → resumable, deduplicated, delta sync.
Metadata
SQL: files, versions, chunk lists, folders, sharing ACLs. Strongly consistent (it's the source of truth for "what is the latest version").
Sync
Each change bumps a per-user/namespace cursor; clients long-poll or hold a notification connection, then pull changes since their cursor.
Conflicts
Two offline edits to the same version → keep both ("file (conflicted copy)"); don't silently overwrite.
Extras
Cold storage tiering for old versions, virus scanning, link sharing with expiry, quota accounting.
Q3Design a distributed message queue / log like Kafka.UberLinkedInAmazonWalmart
Model
Topic → partitions; each partition is an append-only log split into segment files; messages get a monotonically increasing offset. Ordering is per partition (key → partition by hash).
Durability
Each partition has a leader + followers; producer acks=all waits for the in-sync replicas; sequential disk writes + OS page cache make it fast.
Consumers
Pull model; consumer groups split partitions among members; committed offsets stored by the broker; rebalancing on join/leave.
Retention
By time/size, or log compaction (keep the last value per key).
Semantics
At-least-once by default; idempotent producer + transactions for exactly-once within the system.
2

IDs, ranking & location

0 41 bits · ms since custom epoch 10 bits · machine 12 bits · sequence sign ≈ 69 years of IDs · roughly time-sortable 1,024 generators 4,096 IDs / ms / machine no coordination per ID · watch out for clock going backwards (wait or refuse)
Fig 21.1 — Snowflake-style IDs: unique, 64-bit, sortable by time, generated locally.
Q4Design a distributed unique ID generator.AmazonUberFlipkartRazorpay
OptionProsCons
DB auto-incrementSimple, orderedSingle bottleneck; multi-master needs step/offset tricks
UUID v4No coordination128-bit, random → poor index locality
UUID v7 / ULIDTime-ordered, no coordinationStill 128-bit
Snowflake (Fig 21.1)64-bit, time-sortable, fastNeeds machine-ID assignment (ZooKeeper/config) and sane clocks
Ticket server / ID rangesEach node leases a block of 1,000 IDsGaps on crash; range service must be HA
Q5Design a real-time gaming leaderboard (top 10 + my rank).AmazonMicrosoftDream11 / gaming
Store
Redis sorted set per leaderboard: ZINCRBY on score, ZREVRANGE 0 9 for the top 10, ZREVRANK for a user's rank — all O(log n).
Durability
Scores also written to a DB (source of truth) via the game service; Redis can be rebuilt.
Scale
Hundreds of millions of users: shard by score range, or keep exact top-K + approximate rank for the long tail (percentile buckets).
Time windows
One sorted set per day/week with TTL; merge with ZUNIONSTORE for "this month".
Q6Design "nearby restaurants" (Yelp / Swiggy discovery).UberGoogleSwiggyZomato
Shape
Very read-heavy, business data changes rarely → precompute a geo index and cache aggressively.
Index
Geohash (prefix = area; search own cell + 8 neighbours), or quadtree (splits dense areas finer, built in memory), or S2/H3 cells. Postgres + PostGIS or Elasticsearch geo queries are fine answers at moderate scale.
Query
Candidates from cells → filter by exact distance, open-now, cuisine → rank (distance, rating, delivery time, ads) → paginate.
Edge cases
Sparse areas (expand radius), cell boundaries (neighbours), hot cities (replicas).
3

Analytics, booking & migrations

Q7Design ad-click / metrics aggregation (counts per minute, at scale).MetaGoogleAmazon
Ingest
Click events → Kafka (keyed by ad_id) → stream processor (Flink / Kafka Streams) with tumbling 1-min windows and event-time watermarks for late events.
Store
Aggregates to an OLAP/time-series store (ClickHouse, Druid, Pinot); raw events to cheap object storage for replay and audits.
Correctness
Dedupe by click_id; exactly-once sinks or idempotent upserts; nightly batch reconciliation (Lambda) or replay-from-log (Kappa).
Hot keys
A viral ad → pre-aggregate per partition, then merge.
Q8Design hotel / Airbnb booking — how do you prevent double booking?AmazonMicrosoftMakeMyTripGCCs

Answer: Model inventory per room-type per date (room_type_id, date, total, reserved). Booking = one transaction that, for each night, runs UPDATE … SET reserved = reserved + 1 WHERE … AND reserved < total and checks every update affected a row (or use a version column). Make the reserve API idempotent with a booking key; hold inventory for the payment window and release on timeout. Search is served from a cache/replica — it can be slightly stale; the booking path cannot.

Q9Migrate a live database with zero downtime?AmazonAtlassianGCCs
Backfill the new store from a snapshot + CDC stream (Debezium) → dual-write or CDC keeps it in sync → shadow-read and compare → switch reads gradually (flag) → switch writes → keep the old store as rollback for a while → decommission.
Q10Active-active multi-region — what's hard?NetflixMicrosoft
Write conflicts (route each user/tenant to a home region, or use CRDT/LWW for non-critical data), replication lag, global uniqueness (IDs, usernames), failover traffic shifting (DNS/anycast), and testing it (regular region evacuation drills).
Q11Handle a hot partition / celebrity key?MetaSwiggy
Detect via per-key metrics. Reads: replicate the key / local cache / CDN. Writes: split the key (key#0..key#N) and aggregate on read; batch counters in memory and flush.
Q12Design an online code judge (LeetCode)?AtlassianHackerRank-style
Submission API → queue → sandboxed runners (containers/gVisor/Firecracker, no network, CPU/memory/time limits) → compare outputs against hidden tests → results via polling/WebSocket. Autoscale runners on queue depth during contests.
🎯 Pattern behind every blueprint
Find the one invariant that must never break (no double booking, no lost money, convergent text, unique IDs) and design the write path around it. Make the read path fast with caches and replicas — it can be a little stale.

LLD & Machine Coding II — Build It Live

Ten more problems reported from Flipkart, Uber, Microsoft, Swiggy, PhonePe and Atlassian "code design" rounds. Use the 90-minute plan from page 11.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

Order matching engine (stock exchange)

ASKS (sell) — lowest price on top of the book 103 × 50 102 × 30 101 × 20 ← best ask spread 100 × 40 ← best bid 99 × 70 BIDS (buy) — highest price on top incoming BUY 101 × 35limit order ① fills 20 @ 101 (resting price) ② 102 > 101 → stop matching ③ rest 15 joins bids @ 101
Fig 22.1 — price-time priority: best price first, then earliest order at that price.
Q1Implement a limit-order matching engine (price-time priority).🔥PhonePeZerodha / fintechUberbank GCCs
enum Side { Buy, Sell }
record Order(long Id, Side Side, decimal Price, int Qty, long Seq);
record Trade(long BuyId, long SellId, decimal Price, int Qty);

class OrderBook {
    // priority = (price key, arrival seq): bids use -price so the highest bid comes first
    private readonly PriorityQueue<Order, (decimal, long)> _bids = new(), _asks = new();

    public List<Trade> Place(Order o) {
        var trades = new List<Trade>();
        var opposite = o.Side == Side.Buy ? _asks : _bids;
        int remaining = o.Qty;
        while (remaining > 0 && opposite.TryPeek(out var best, out _) && Crosses(o, best)) {
            opposite.Dequeue();
            int fill = Math.Min(remaining, best.Qty);
            trades.Add(o.Side == Side.Buy ? new Trade(o.Id, best.Id, best.Price, fill)
                                          : new Trade(best.Id, o.Id, best.Price, fill));
            remaining -= fill;
            if (best.Qty > fill) opposite.Enqueue(best with { Qty = best.Qty - fill }, Key(best));  // keeps its Seq
        }
        if (remaining > 0) {
            var rest = o with { Qty = remaining };
            (o.Side == Side.Buy ? _bids : _asks).Enqueue(rest, Key(rest));
        }
        return trades;
    }

    static bool Crosses(Order o, Order best) => o.Side == Side.Buy ? o.Price >= best.Price : o.Price <= best.Price;
    static (decimal, long) Key(Order o) => (o.Side == Side.Buy ? -o.Price : o.Price, o.Seq);
}
↪ Extensions they ask: cancel (lazy-delete set checked on peek, or SortedDictionary<price, LinkedList<Order>> + id → node map for O(1) cancel), market orders (no price check), one book per symbol, single-threaded matcher per symbol fed by a queue (no locks, deterministic).
2

More machine-coding problems

Q2Shopping cart with pluggable discount rules.FlipkartUberWalmartSwiggy
Entities
Product (id, price, category), Cart (lines: product + qty), Coupon, User (tier).
Rules
IDiscountRule { bool AppliesTo(Cart); decimal Discount(Cart); } — FlatOff, PercentOff (capped), BuyXGetY, CategoryOff, FirstOrder. A PricingEngine runs rules in priority order; a stacking policy (best single / all stackable) is itself a strategy.
Money
decimal, round once at the end, never below zero, return a line-by-line breakdown (users and graders both love it).
Extension
New rule = new class + registration; rules loaded from config/JSON.
Q3Cab booking (Uber/Ola LLD): riders, drivers, matching, fares.UberFlipkartMicrosoft
Entities
Rider, Driver (location, status, vehicle type), Trip (state machine), Location, Fare.
Strategies
IDriverMatchingStrategy (nearest, best-rated, least-recently-assigned), IFareStrategy (base + per-km + per-min, surge multiplier).
Flow
requestRide → find candidates within radius → assign atomically (driver Available → Assigned with a lock/CAS) → start/end trip → fare → rating.
Edge cases
No drivers, driver cancels (re-match), rider cancels (fee rule), concurrent requests for one driver.
Q4Tic-tac-toe on an n×n board — check the winner in O(1) per move.MicrosoftAmazonInfosys
int[] rows = new int[n], cols = new int[n]; int diag = 0, anti = 0;
int Move(int r, int c, int player) {           // player 1 → +1, player 2 → -1
    int v = player == 1 ? 1 : -1;
    rows[r] += v; cols[c] += v;
    if (r == c) diag += v;
    if (r + c == n - 1) anti += v;
    if (Math.Abs(rows[r]) == n || Math.Abs(cols[c]) == n || Math.Abs(diag) == n || Math.Abs(anti) == n)
        return player;
    return 0;
}

Wrap it in Board / Player / Game classes with move validation and a IWinStrategy so "connect-4 rules" can be swapped in. Chess follows the same split: Piece subclasses own their move rules; Board validates check/checkmate.

Q5Meeting room scheduler?MicrosoftAtlassian
Room (capacity, features), Booking (interval). Per room, keep bookings in a SortedSet by start; a new [s, e) fits if the previous booking ends ≤ s and the next starts ≥ e (O(log n)). Room selection strategy: smallest room that fits. Lock per room.
Q6ATM machine?AmazonTCSbank GCCs
State pattern (Idle → CardInserted → Authenticated → Transaction → Dispense). Cash dispenser as Chain of Responsibility (2000 → 500 → 200 → 100). Bank calls behind an interface; the debit and the dispense must reconcile if dispensing fails.
Q7Task scheduler with dependencies and priorities?AtlassianUber
Tasks as a DAG; ready queue = priority queue of tasks with in-degree 0; workers (thread pool) pull, run, then decrement dependents. Detect cycles on submit; retries with backoff; cancellation tokens.
Q8Cache with pluggable eviction policy?FlipkartMicrosoft
Cache<K,V> depends on IStorage (dictionary) and IEvictionPolicy { KeyAccessed(k); K EvictKey(); } → LRU (DLL), LFU, FIFO implementations. Classic test of Strategy + DIP.
Q9Inventory with reservations (e-commerce)?FlipkartSwiggy
available vs reserved per SKU per warehouse; reserve on checkout (atomic), confirm on payment, auto-release after TTL; never let available go negative; events for low stock (Observer).
Q10Feature-flag evaluator (Atlassian-style)?Atlassian
Flag → ordered rules (user in list, attribute match, percentage rollout via hash(userId + flag) % 100) → first match wins → default. Rules are classes implementing IRule; config hot-reloaded; evaluation is pure and unit-testable.

🧱 Reusable skeleton

  • models/ plain entities + enums
  • strategies/ the parts that vary
  • services/ flows, validation
  • repositories/ in-memory maps
  • Program.cs demo of every requirement

💬 Say while coding

  • "I'll keep this behind an interface because pricing will change."
  • "This is shared state — I'll lock per room, not globally."
  • "Happy path first, then edge cases."

Production Scenarios — "What would you do if…"

The core of Tier 3 / GCC technical rounds and every senior hiring-manager round. Answer shape: symptoms → evidence → tool → fix → prevention.
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

.NET services in production

Q1CPU is at 100% on your API pods. Walk me through it.🔥MicrosoftGCCsTCSInfosys
  1. Mitigate: scale out / roll back the last deploy if it correlates.
  2. Scope: all pods or one? Which endpoints got slower (APM traces)? Traffic spike or same traffic?
  3. Evidence: dotnet-counters monitor (CPU, GC %, thread-pool queue, exceptions/sec); dotnet-trace collect for a CPU profile → hot methods.
  4. Usual suspects: tight retry loops, regex backtracking, huge JSON serialisation, LINQ in loops (O(n²)), GC thrash from allocations, exception storms.
  5. Prevent: load test the hot path, alerts on CPU + p99, regex timeouts, allocation budgets.
Q2Memory keeps growing until the pod is OOMKilled. How do you find the leak?MicrosoftGCCsAccenture

Confirm with metrics (working set vs GC heap size — native vs managed leak). Take two heap dumps some minutes apart (dotnet-gcdump / dotnet-dump), compare object counts by type, follow the GC roots of the growing type. Typical roots: static dictionaries/caches without limits, event subscriptions, singletons capturing scoped objects, timers, unbounded in-memory queues. Fix + add a memory alert and a size-limited MemoryCache.

Q3Latency spikes under load but CPU is low. What is thread-pool starvation?MicrosoftWalmartGCCs

Synchronous blocking (.Result, .Wait(), Thread.Sleep, sync I/O) parks thread-pool threads; new work queues up while the pool grows slowly (~1–2 threads/sec), so requests wait even though the CPU is idle. Evidence: ThreadPool Queue Length and thread count climbing in dotnet-counters. Fix: async all the way; as a short-term band-aid, raise ThreadPool.SetMinThreads.

Q4Why is async void dangerous?TCSCognizant
Callers can't await it, and exceptions go to the synchronization context → can crash the process. Only for event handlers; otherwise return Task.
Q5Global error handling in ASP.NET Core?InfosysGCCs
UseExceptionHandler / IExceptionHandler returning RFC 7807 ProblemDetails; log with a correlation/trace ID; never leak stack traces; map domain exceptions to 400/404/409.
Q6IMemoryCache vs IDistributedCache?TCSSalesforce
In-memory: fastest, per instance (inconsistent across pods, lost on restart). Distributed (Redis): shared, survives deploys, network hop + serialisation. Common: L1 memory + L2 Redis (.NET HybridCache).
Q7How do you make logs useful?AmazonGCCs
Structured (JSON, Serilog/ILogger templates), correlation/trace IDs propagated across services (OpenTelemetry), consistent levels, no PII/secrets, sampling for noisy paths, logs + metrics + traces linked.
2

Database scenarios

Q8Design an index for: WHERE tenant_id = ? AND status = ? AND created_at > ? ORDER BY created_at.AmazonAtlassianGCCs

Answer: Composite index (tenant_id, status, created_at) — equality columns first, then the range/sort column. The index then serves the filter and the ORDER BY (no sort step). Add frequently selected columns with INCLUDE to make it covering. Verify with the actual plan.

⚠️ Putting created_at first makes the range scan everything after the date for all tenants.
Q9Database deadlocks in production?GCCsPayPal
Capture the deadlock graph (SQL Server extended events / Postgres logs). Fix: touch tables/rows in a consistent order, keep transactions short, add indexes so updates lock fewer rows, retry the victim transaction.
Q10Lost updates with EF Core?InfosysGCCs
Optimistic concurrency: a rowversion/[Timestamp] or concurrency-token column; EF adds it to the WHERE and throws DbUpdateConcurrencyException → reload, merge or show a conflict.
Q11User saved data but doesn't see it on refresh?MetaWalmart
Replica lag (read from a follower) or a stale cache. Read-your-writes: read from the primary for that user for a few seconds after a write, or pass the write's LSN/version; invalidate the cache key on write.
Q12Add a column to a 500M-row table safely?AmazonAtlassian
Nullable column (metadata-only in modern engines) → backfill in small batches during off-peak → add default/NOT NULL after → online index creation. Expand → migrate → contract (page 15).
3

Network & Linux debugging

client load balancer /gateway (nginx) upstream app 502 Bad Gatewayrefused / reset / garbage response 503 Service Unavailableno healthy targets / overloaded 504 Gateway Timeoutupstream too slow the status comes from the gateway — look at the upstream's health, logs and latency, not the gateway's
Fig 23.1 — 5xx from a proxy: 502 = it answered wrong, 503 = nobody to ask, 504 = it took too long.
Q13Users get intermittent 502/504 errors after a deploy. Debug it.🔥AmazonGCCsTCS
  • Correlate with the deploy → roll back first if impact is high.
  • 502 during rollout: pods killed while serving (no graceful shutdown / preStop delay), readiness passing too early, keep-alive timeout of app shorter than the LB's (LB reuses a connection the app just closed).
  • 504: a slow dependency or query; LB timeout shorter than the request path; thread-pool starvation.
  • Tools: LB access logs (target status, latency), app logs by trace ID, curl -v from inside the cluster, pod events.
Q14Linux commands for a sick server?TCSInfosysHCLTech
top/htop (CPU, load), free -m (memory), df -h / du -sh (disk), ss -tulpn (ports), lsof -p (open files), journalctl -u svc / tail -f (logs), dig/nslookup (DNS), curl -v (HTTP/TLS), tcpdump (packets).
Q15"Works on my machine, fails in prod with SSL error"?AccentureGCCs
Expired/incomplete certificate chain, hostname mismatch, missing CA in the container image, TLS version mismatch, corporate proxy. Check with openssl s_client -connect host:443 -servername host. Automate renewal (cert-manager / Key Vault) and alert 30 days before expiry.
4

Kubernetes, cloud & delivery scenarios

Q16Pod stuck in Pending?GCCsWalmart
kubectl describe pod → events: insufficient CPU/memory (requests too high / cluster full → autoscaler), node selector/taints without tolerations, unbound PVC, quota exceeded.
Q17ImagePullBackOff?TCSInfosys
Wrong image name/tag, private registry without imagePullSecrets / managed identity, registry rate limits (Docker Hub), network egress blocked.
Q18Service exists but calls time out?GCCsSalesforce
kubectl get endpoints svc — empty means the selector doesn't match pod labels or pods aren't Ready. Then check targetPort vs container port, NetworkPolicies, and DNS (svc.namespace.svc.cluster.local).
Q19RPO vs RTO; DR strategies?Accenturebank GCCsAmazon
RPO = how much data you can lose (time since last good copy); RTO = how long you can be down. Cheapest → fastest: backup & restore → pilot light → warm standby → multi-region active-active. Test restores; untested backups don't count.
Q20Cut the cloud bill by 30%?AmazonIntuit
Measure by service/team (tags) → right-size (requests vs actual usage) → autoscale + scale to zero off-hours → reserved/savings plans for steady load, spot for batch → storage tiering + lifecycle rules → kill idle resources → cache/CDN to cut egress.
Q21git merge vs rebase; revert vs reset?TCSWiproCognizant
Merge keeps history with a merge commit; rebase replays your commits on top for linear history — never rebase shared branches. revert adds an undo commit (safe on shared branches); reset moves the branch pointer (rewrites history, local only).
Q22Unit vs integration vs contract tests?AtlassianGCCs
Test pyramid: many fast unit tests (logic, mocks at boundaries), fewer integration tests (real DB via Testcontainers), contract tests between services (Pact) instead of brittle full end-to-end suites, a few smoke E2E tests.
Q23How do you roll out a risky change?MetaNetflix
Feature flag (off by default) → internal users → 1% canary with dashboards and auto-rollback on error/latency SLOs → ramp 10/50/100% → remove the flag. Separate deploy from release.

Behavioral II & AI / LLM Engineering II

More worked stories (templates — swap in your own numbers) and the GenAI follow-ups that come after "explain RAG".
🙈 Quiz mode is ON — answers are hidden. Say your answer out loud, then click the question to check.
1

More behavioral questions, worked

Q1"Tell me about a time you took ownership of something outside your role." (Ownership)🔥AmazonUberAtlassian
  • S/T: Our on-call got ~40 pages a week, most from one flaky integration owned by another team that was busy with a launch.
  • A: I grouped a month of alerts by cause, found 70% came from timeouts on one vendor endpoint, proposed a fix in their repo (retry with jitter + circuit breaker + a dead-letter queue), paired with their engineer to review it, and added a dashboard both teams watched.
  • R: Pages dropped from ~40 to ~6 a week within a month; the other team adopted the pattern for two more vendors.
💡 Ownership = you noticed, acted beyond your lane, and brought the owner along instead of going around them.
Q2"Tell me about delivering under a tight deadline." (Deliver Results / Bias for Action)AmazonMetaFlipkartAll T3
  • S/T: A regulatory change gave us 3 weeks to add consent tracking to every checkout flow — normally a quarter's work.
  • A: I split must-have (audit trail, consent capture on 4 flows) from nice-to-have (admin UI), agreed the cut with the PM and legal in writing, built the capture as a shared middleware instead of 4 separate changes, and ran daily 15-minute check-ins with QA so testing ran in parallel.
  • R: Shipped 2 days early with zero audit findings; the admin UI followed a month later.
⚠️ "We all worked weekends" is not the story. Prioritisation and smart scoping are.
Q3"Tell me about a difficult stakeholder."GoogleAtlassianAccentureCognizant

Structure: understand their real goal (often not what they first ask) → make trade-offs visible (options with cost and risk, not a "no") → agree in writing → keep them updated proactively. Example: a product head demanded real-time reports; I learned they needed fresh numbers for a 9 AM review, so a 15-minute refresh was enough — delivered in 1 week instead of a 2-month streaming pipeline.

Q4"Why should we hire you?"All T3HR
Three proofs mapped to their job description: "You need X — I did X at scale (number). You need Y — I led Y. And I bring Z your team mentioned they lack." End with enthusiasm for their problem.
Q5"A time you simplified something." (Invent & Simplify)Amazon
Before → after with numbers: "Deploy took 14 manual steps and ~2 hours; I scripted it into one pipeline with automated rollback — 12 minutes, zero manual steps, adopted by 5 teams."
Q6"A time you refused to compromise on quality."AmazonApple
What the risk was (data loss, security), the evidence you showed, the alternative you offered (ship behind a flag / smaller scope), and the outcome. Show judgment — not perfectionism on things that don't matter.
Q7"Priorities changed / your project was cancelled."MetaGoogle
Acknowledge the frustration briefly, explain how you understood the why, salvaged reusable parts, re-planned with the team, and kept morale. Adaptability without bitterness.
Q8"Tell me about learning something fast."AmazonMicrosoft
Concrete: new language/system, your method (docs → small spike → pair with an expert → teach it back), time taken, and what you shipped with it. Growth mindset with evidence.
2

AI / LLM engineering — the follow-ups

user goal LLM decidesplan / next step tool call (JSON) your code runs toolsearch · DB · API · code observation / result final answer guardrails: max steps · token/cost budget allow-listed tools · approval before side effects
Fig 24.1 — an "agent" is just this loop. Most of the engineering is in the tools, the limits and the evals.
Q9How do you evaluate a RAG system?🔥MicrosoftAmazonSalesforceAtlassian
  • Build a golden set — 100–300 real questions with expected answers and the source passages (from support tickets, SMEs, logs).
  • Retrieval metrics: recall@k (is the right chunk in the top k?), MRR / nDCG (is it near the top?).
  • Generation metrics: faithfulness/groundedness (every claim supported by retrieved text), answer relevance, correctness vs reference, citation accuracy — scored by human review plus an LLM-as-judge calibrated against humans.
  • Online: thumbs up/down, escalation-to-human rate, deflection rate, latency and cost per answer.
  • Run evals in CI on every prompt/model/chunking change — prompts are code.
Q10Chunking strategies — and why chunking matters so much.GoogleAdobeAccenture

Too small → chunks lose context; too large → noisy retrieval and wasted tokens. Options: fixed size with overlap (baseline), structure-aware (split on headings/sections, keep tables whole), semantic (split where topic shifts), parent-child (retrieve small chunks, send the larger parent section to the model). Attach metadata (title, section path, date, ACL) and prepend the document title to each chunk.

Q11LoRA / QLoRA / quantization?MetaGoogle
LoRA trains small low-rank adapter matrices instead of all weights → cheap fine-tuning, swappable adapters. QLoRA does it on a 4-bit quantized base model to fit on smaller GPUs. Quantization (8/4-bit) shrinks memory and speeds inference at a small quality cost.
Q12What drives LLM latency?MicrosoftSwiggy
Time-to-first-token (prompt length → prefill) + output tokens ÷ tokens/sec (decode). Cut it with shorter prompts, prompt caching, smaller models for easy steps, streaming to the UI, parallel tool calls, capped output length.
Q13How do you get reliable structured output?IntuitAtlassian
Use the provider's structured-output / tool-calling with a JSON schema, validate in code (strong types), retry with the validation error on failure, keep fields minimal, and never trust the output for authorization decisions.
Q14Estimate the cost of an LLM feature?AmazonFlipkart
requests/day × (input tokens × input price + output tokens × output price), plus embeddings and vector-store costs. E.g. 100K requests × (3K in + 300 out tokens). Then show levers: caching hit-rate, smaller model routing, fewer retrieved chunks.
Q15Long conversations exceed the context window?GoogleSalesforce
Keep the system prompt + recent turns verbatim, summarise older turns, store facts in retrievable memory (vector store / profile), and retrieve only what's relevant to the current turn.
Q16When should you NOT use an agent?MetaAtlassian
When the steps are known — a fixed workflow (retrieve → generate → validate) is cheaper, faster, testable and predictable. Use agents when the path genuinely depends on intermediate results, and add limits + human approval for actions.
Q17You switch embedding models — what breaks?AmazonAdobe
Vectors from different models aren't comparable → re-embed the whole corpus into a new index, dual-run and compare retrieval evals, then cut over (blue/green indexes). Store the model name/version with each vector.
Q18What guardrails would you put on a customer-facing bot?PayPalbank GCCs
Input: PII redaction, prompt-injection and abuse classifiers, topic limits. Output: grounding/citation checks, toxicity filter, no financial/medical advice rules, safe refusals. Plus rate limits, audit logs and a human-handoff path.
🎯 Takeaway
For stories: scope, trade-off, number, learning. For GenAI: retrieval quality, evals, cost/latency levers, guardrails — say those four and you sound like someone who has shipped it.

30-Day Plan & Company Cheat Sheet

Print this page. Tick a box every day. ~2–3 hours/day alongside a full-time job.
1

The 30-day calendar

Wk 1 DSA: arrays · hashing · two pointers · sliding window · lists · stacks (p.3–4) + 45 min/day: OS & concurrency (p.7) · Sun: 1 timed mock (2 mediums / 45 min) Wk 2 DSA: binary search · heaps · intervals · trees · tries · graphs (p.4–5) + DBMS & SQL (p.8) + networking (p.9) · Sun: mock + write 4 STAR stories Wk 3 DSA: DP · backtracking · greedy (p.6) · OOP/SOLID/patterns (p.10) + 2 full machine-coding builds in 90 min each: parking lot, Splitwise (p.11) · stack depth (p.14–15) Wk 4 HLD concepts + 6 design blueprints out loud (p.12–13) · AI/LLM (p.16) + finish 8–10 STAR stories (p.17) · HR prep (p.18) · 3 mock loops with a friend / platform Day 29–30: re-solve your "missed" list, skim this notebook in Quiz mode, sleep 8 h.
Fig 25.1 — Tier 3 target? Compress weeks 3–4 and spend more on stack depth (p.14–15, 23). Tier 1? Add a 5th week: Q&A Bank II (p.19–24).
2

Company-wise cheat sheet

CompanyWin conditionRevise these pages
GoogleClean optimal code without running it; graphs/DP; G&L stories; design depth at L5+5, 6, 12, 13, 17, 19–21
MetaSpeed (2 mediums / 40 min), trees/graphs/arrays; AI-enabled round; product design; ambiguity & conflict stories3, 4, 5, 13, 16, 17, 20, 24
AmazonLP story in every round (2 per principle); OOD; system design for SDE2+3, 4, 11, 13, 17, 21, 24
MicrosoftDSA medium, LLD + HLD, AA round, collaboration stories; C#/.NET depth helps4, 7, 10, 11, 14, 19, 23
UberGraphs/DP, runnable machine coding, project-centred design, strong HM round5, 6, 11, 13, 18, 20, 22
Flipkart · Swiggy · RazorpayMachine coding gate (SOLID, extensible, runs), PSDS mediums, practical HLD10, 11, 22, 3–5, 13, 21
AtlassianCode design build-and-extend, values round, system design2, 11, 12, 17, 20, 22
Adobe · Salesforce · Walmart · PayPal · IntuitBalanced DSA + LLD/HLD + CS fundamentals; Intuit craft demo3–5, 7–10, 12, 19
TCS · Infosys · Wipro · HCLTechStack depth, SQL, OOP, project walkthrough, scenario + HR8, 10, 14, 15, 18, 23
Accenture · Cognizant · CapgeminiCommunication, client scenarios, fundamentals, sometimes OA3, 8, 9, 14, 18, 23, 24
Bank / retail GCCsOA mediums, current-system design, testing & security, cloud/K8s3–4, 9, 13, 15, 23
3

Am I ready?

Q1How do I know I'm ready for the loop?🔥
  • ✓ You solve an unseen medium in ≤ 25 min with a clean dry run, 4 times out of 5.
  • ✓ You can answer every 🔥 question in this notebook in Quiz mode without peeking.
  • ✓ You've built parking lot + one other LLD in 90 minutes and it ran (T2 targets).
  • ✓ You can whiteboard feed, notifications and rate limiter in 40 minutes each, with numbers.
  • ✓ You have 8+ STAR stories with metrics, each told in under 3 minutes.
  • ✓ You know your own numbers: current CTC breakdown, notice period, expected range.
💡 If two boxes are unticked, reschedule by a week — recruiters almost always agree, and a failed loop often means a 6–12 month cool-down.

🌙 Night before

  • Skim your mistakes list, not new problems
  • Re-read your 8 STAR stories once
  • Test camera, mic, IDE, CoderPad link
  • Sleep. Seriously.

☀️ Morning of

  • 1 easy warm-up problem (confidence, not learning)
  • Water, notebook, pen within reach
  • Join 5 min early; close Slack/email

🎤 In every round

  • Clarify → examples → approach → Big-O → code → test
  • Think aloud; accept hints gracefully
  • Leave 5 min for your questions

🔁 After each round

  • Write down the questions within an hour
  • Forget the last round — every round is scored separately
  • Send a short thank-you to the recruiter
🎯 Final word
Interviews test preparation more than talent. Patterns for coding, structure for design, stories for behaviour — and calm communication across all of them. You've got this. ✍️
📖 Interview Q&A Table of Contents