// Phase 4 of 4 โ€” SDE 2 Trail

Question Bank for Final Hunt

Ugh. This last cave-wall before real battle. Click question, see answer hide inside โ€” cover click, test own brain first, THEN open see real answer. This how real practice work, not just read-and-forget.

โš  Cave-truth: no question-bank give "100% guarantee" pass โ€” real interviewer ask surprise question, follow-up, twist. But master THIS bank + explain-clear + own-project-story = very very strong chance.
Technical Round

DSA Question Bank

Cover pattern from Phase 1-2. Not just answer โ€” learn PATTERN, so new problem (never seen before) still solvable.

Q1Two Sum โ€” find pair that add to target.โ–ถ
Pattern: Hash Map, one-pass.
Walk array once, for each number check if (target - number) already seen in hash-map. If yes, found pair. If no, store current number in map.
function twoSum(nums, target) {
  const seen = new Map();
  for (let i = 0; i < nums.length; i++) {
    if (seen.has(target - nums[i])) return [seen.get(target - nums[i]), i];
    seen.set(nums[i], i);
  }
}
Complexity: O(n) time, O(n) space. Follow-up to expect: "What if array sorted?" โ†’ use two-pointer for O(1) space instead.
Q2Detect cycle in a Linked List.โ–ถ
Pattern: Floyd's Tortoise and Hare (slow-fast pointer).
Two pointer, slow move 1 step, fast move 2 step. If cycle exist, fast eventually "lap" slow and they meet. If fast hit null, no cycle.
function hasCycle(head) {
  let slow = head, fast = head;
  while (fast && fast.next) {
    slow = slow.next; fast = fast.next.next;
    if (slow === fast) return true;
  }
  return false;
}
Complexity: O(n) time, O(1) space. Follow-up: "Find where cycle start?" โ†’ after meet, reset one pointer to head, move both 1 step at a time, they meet at cycle start.
Q3Longest Substring Without Repeating Characters.โ–ถ
Pattern: Sliding Window (variable size) + Hash Set/Map.
Grow window right, if repeat char found, shrink from left until repeat gone. Track max window size seen.
function lengthOfLongestSubstring(s) {
  const seen = new Set();
  let left = 0, max = 0;
  for (let right = 0; right < s.length; right++) {
    while (seen.has(s[right])) { seen.delete(s[left]); left++; }
    seen.add(s[right]);
    max = Math.max(max, right - left + 1);
  }
  return max;
}
Complexity: O(n) time, O(min(n, charset)) space.
Q4Validate a Binary Search Tree.โ–ถ
Pattern: Recursion with range-bound (min/max allowed value).
Don't just compare node to direct children โ€” must pass down valid range from ancestor. Left subtree bounded by (min, node.val), right by (node.val, max).
function isValidBST(node, min = -Infinity, max = Infinity) {
  if (!node) return true;
  if (node.val <= min || node.val >= max) return false;
  return isValidBST(node.left, min, node.val) && isValidBST(node.right, node.val, max);
}
Common mistake: comparing node only to immediate child โ€” misses ancestor-level violation. Interviewer often check if you catch this.
Q5Number of Islands (Grid, connected components).โ–ถ
Pattern: DFS or BFS flood-fill on grid.
Scan grid, when hit unvisited land ('1'), increment count, then DFS/BFS to mark all connected land as visited so not counted again.
function numIslands(grid) {
  let count = 0;
  function dfs(r, c) {
    if (r<0||c<0||r>=grid.length||c>=grid[0].length||grid[r][c]!=='1') return;
    grid[r][c] = '0'; // mark visited
    dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1);
  }
  for (let r=0;rfor (let c=0;c0].length;c++)
      if (grid[r][c]==='1') { count++; dfs(r,c); }
  return count;
}
Complexity: O(rows ร— cols).
Q6Climbing Stairs (classic DP intro).โ–ถ
Pattern: DP, actually same recurrence as Fibonacci.
Ways to reach step n = ways to reach (n-1) + ways to reach (n-2), since you can take 1 or 2 step.
function climbStairs(n) {
  if (n <= 2) return n;
  let a = 1, b = 2;
  for (let i = 3; i <= n; i++) { [a, b] = [b, a + b]; }
  return b;
}
Why this matters: Interviewer use this to check if you SPOT the DP pattern quick, before jumping to knapsack-level problem.
Q7Kth Largest Element in an Array.โ–ถ
Pattern: Min-Heap of size K (or Quickselect for O(n) average).
Keep min-heap of size K while scanning array โ€” heap top is always Kth largest so far.
// Simplified using sort (mention heap/quickselect as optimal in interview)
function findKthLargest(nums, k) {
  return nums.sort((a,b)=>b-a)[k-1];
}
// Optimal: Min-Heap size k โ†’ O(n log k), or Quickselect โ†’ O(n) average
Interview tip: Always mention the optimal approach even if you code simpler version first โ€” shows you know trade-off.
Q8Merge Intervals.โ–ถ
Pattern: Sort by start time, then greedy merge overlapping.
function merge(intervals) {
  intervals.sort((a,b) => a[0] - b[0]);
  const result = [intervals[0]];
  for (let i = 1; i < intervals.length; i++) {
    const last = result[result.length - 1];
    if (intervals[i][0] <= last[1]) last[1] = Math.max(last[1], intervals[i][1]);
    else result.push(intervals[i]);
  }
  return result;
}
Complexity: O(n log n) due to sort.
Technical Round

System Design Question Bank

No single "correct" answer here โ€” interviewer grade on framework and trade-off thinking, not memorized diagram. Use this 4-step framework for EVERY design question: 1) Clarify requirement โ†’ 2) Estimate scale โ†’ 3) High-level design โ†’ 4) Deep-dive + trade-off.

Q1Design a URL Shortener.โ–ถ
Clarify: Custom alias support? Analytics needed? Expiry?
Scale: Assume 100M URL/month created, 100:1 read:write ratio.
High-level: Client โ†’ Load Balancer โ†’ App Server โ†’ Cache (Redis) โ†’ DB (key-value, short_code โ†’ long_url).
Deep-dive: Base62 encode of auto-increment ID for short code. Cache hot codes (80/20 rule). Discuss custom alias collision handling.
Q2Design a Rate Limiter.โ–ถ
Clarify: Per-user? Per-IP? Per-API-key? What happen on limit-hit (reject vs queue)?
High-level: Middleware/Gateway checks counter in Redis before forwarding request.
Deep-dive: Compare Token Bucket (allow burst) vs Fixed Window (simple, edge-burst risk) vs Sliding Window Log (accurate, costly). Recommend Token Bucket for most API use-case. Mention distributed counter needs atomic Redis INCR + TTL, not local memory.
Q3Design a Chat Application (like WhatsApp).โ–ถ
Clarify: 1-on-1 only or group too? Media support? Delivery/read receipt needed?
High-level: WebSocket Gateway for real-time connection โ†’ Message Queue for fan-out โ†’ NoSQL store (partition by conversation-id) for persistence.
Deep-dive: Offline user โ€” store message, push via notification service when online, sync on reconnect. Group chat โ€” fan-out message to all member's queue/socket.
Q4Design a News Feed (like Twitter/Instagram feed).โ–ถ
Clarify: Ranking chronological or engagement-based? Media-heavy?
High-level: Post service writes to DB + triggers fan-out.
Deep-dive: Discuss Fan-out-on-Write (fast read, costly for celebrity account) vs Fan-out-on-Read (slower read, no write-storm) vs Hybrid (real-world answer โ€” normal user get write fan-out, celebrity get read fan-out). Mention cursor-based pagination for infinite scroll, Redis cache for hot feed.
Q5How would you scale a system from 1,000 to 10 million users?โ–ถ
Answer framework: Start with Vertical Scale (simple, cheap at small scale) โ†’ add Caching (Redis) to reduce DB load โ†’ add Load Balancer + Horizontal Scale of app servers (stateless design required) โ†’ Database scale via Read Replicas first, then Sharding when write-load too high โ†’ add CDN for static asset โ†’ add Message Queue to decouple heavy async task (email, notification).
Key point to say: Scale incrementally based on actual bottleneck (measure first), don't over-engineer for scale you don't have yet.
Q6SQL or NoSQL โ€” how do you decide?โ–ถ
Answer: Depend on data shape and access pattern. SQL when: strong relationship between entity, need ACID transaction (payment, order), complex JOIN/query. NoSQL when: high write-volume, flexible/evolving schema, need horizontal scale built-in, simple key-based access (chat log, activity feed, session store).
Strong answer includes: a real example โ€” e.g. "I'd use PostgreSQL for order/payment, and Cassandra/DynamoDB-style store for chat history."
Q7What is the difference between Sharding and Replication? When use each?โ–ถ
Sharding: split DIFFERENT data across multiple machine โ€” solves capacity/write-throughput problem.
Replication: copy SAME data across multiple machine โ€” solves reliability and read-throughput problem.
Use both together in real large system: shard for write-scale, replicate each shard for fault-tolerance + read-scale.
Technical Round

Node.js / Backend Question Bank

Your past mock interview score 7-8/10 โ€” gap found in syntax precision and Promise pattern. This section target exact that weak spot.

Q1Explain the Node.js Event Loop.โ–ถ
Node.js single-threaded, but event loop let it handle many operation concurrently via non-blocking I/O. Event loop has phase: Timers (setTimeout/setInterval) โ†’ Pending Callbacks โ†’ Poll (fetch new I/O event) โ†’ Check (setImmediate) โ†’ Close Callbacks. Microtask queue (Promise callback, process.nextTick) run between EVERY phase, before moving to next phase.
Follow-up trap: "What print first โ€” setTimeout(0) or Promise.resolve()?" โ†’ Promise wins, because microtask queue always drain before next macrotask (timer) phase.
Q2Difference between Promise.all, Promise.allSettled, Promise.race, Promise.any.โ–ถ
  • Promise.all: wait for all, reject immediately if ANY one reject.
  • Promise.allSettled: wait for all, never reject โ€” return array of {status, value/reason} for each.
  • Promise.race: resolve/reject as soon as FIRST promise settle (win or lose).
  • Promise.any: resolve as soon as FIRST promise fulfill; only reject if ALL reject.
Common mistake (your known gap): confusing race and any โ€” race care about first SETTLE (success or fail), any care about first SUCCESS only.
Q3What is middleware in Express, and how does next() work?โ–ถ
Middleware โ€” function with signature (req, res, next) that run in sequence for a request. Call next() pass control to next middleware; skip it means response must end there (res.send/res.json) or request hang forever. Passing an argument to next() (e.g. next(err)) skip to error-handling middleware.
app.use((req, res, next) => {
  console.log(req.method, req.url);
  next(); // must call, or request stuck
});
Q4How do you handle errors in async/await code properly?โ–ถ
Wrap in try/catch, OR use a wrapper utility to avoid repeating try/catch in every route (common Express pattern).
const asyncHandler = fn => (req, res, next) => 
  Promise.resolve(fn(req, res, next)).catch(next);

app.get('/user', asyncHandler(async (req, res) => {
  const user = await getUser();
  res.json(user);
}));
Why this matters: unhandled promise rejection can crash Node process silently โ€” interviewer check if you know this risk.
Q5Explain connection pooling in database access.โ–ถ
Opening new DB connection is expensive (TCP handshake, auth). Connection pool keep set of reusable connections ready โ€” app "borrow" connection from pool, use it, "return" it, instead of open/close every query. Reduce latency and DB server load.
You've worked with this: your PostgreSQL work with connection pooling โ€” mention that real experience here, strong signal.
Q6How does Node.js handle CPU-intensive tasks without blocking the event loop?โ–ถ
Options: Worker Threads (true parallel thread for CPU-heavy work), Child Process (spawn separate process), or offload to external service/queue (process async, respond later via webhook/polling). Never do heavy synchronous loop directly in main thread โ€” it block ALL other request.
Q7What is the difference between == throttling and debouncing?โ–ถ
Throttle: allow function run at most once per fixed time-interval, regardless how many time triggered (e.g. scroll handler โ€” run max once per 200ms).
Debounce: delay function run until AFTER trigger stop for X time (e.g. search-box autocomplete โ€” wait until user stop typing).
Behavioral Round

Behavioral Question Bank (STAR Method)

STAR = Situation, Task, Action, Result. Use your real AgentOS / Caretaker / Nexus-a2a story here โ€” real project beat imaginary example every time.

Q1Tell me about a project you own end-to-end.โ–ถ
S: I wanted to build a persistent memory layer for AI agent, since most agent forget context between session.
T: Design and build "Caretaker" โ€” a memory backend with ChromaDB, plus "Nexus-a2a" for agent-to-agent communication.
A: Built in phases โ€” first got test suite and vector storage working, then added compression + conflict-resolution + Haiku LLM integration, then multi-agent support with 11-command CLI. Fixed real bug โ€” missing API key was silently causing memory to stay empty.
R: Now Caretaker run live as MCP memory backend integrated with Claude Desktop, with 18 passing tests, 17 new files added in final phase.
Why strong: Shows ownership, iteration, debugging real issue, and technical depth โ€” exactly SDE 2 signal.
Q2Tell me about a time you disagreed with a technical decision.โ–ถ
Frame it as: a real architecture choice you made โ€” e.g. choosing "Monolith First" over microservice for AgentOS early stage, or choosing Rust over Go for OS Core after comparing trade-off.
S: Describe the fork in decision.
T: What you needed to decide and why it mattered.
A: How you evaluated (research, prototype, discussion).
R: What you decided and outcome/learning.
Tip: Even if "disagree" was with your own past assumption (common for solo project), that's fine โ€” shows critical thinking.
Q3Describe a time you fixed a difficult bug.โ–ถ
S: Caretaker's ChromaDB was staying empty despite conversation happening.
T: Find root cause โ€” was it storage bug, embedding bug, or something else?
A: Traced pipeline step by step, found missing API key caused Haiku call to silently fail/skip instead of throwing clear error.
R: Fixed by adding explicit error handling for missing key, memory pipeline works correctly now.
Lesson to mention: "Silent failure is dangerous โ€” now I always design for loud, clear error over silent skip."
Q4How do you handle tight deadline or conflicting priority?โ–ถ
General framework answer: 1) Clarify true priority with stakeholder โ€” what's truly urgent vs nice-to-have. 2) Break task into smallest shippable piece. 3) Communicate early if timeline at risk, don't wait till deadline day. 4) Focus deep-work block, avoid context-switch.
Use example from your structured 16-week study plan approach โ€” shows you naturally think in phases/priority already.
Q5Where do you see yourself in the next few years?โ–ถ
Frame around genuine growth path: deepen system design and infrastructure skill (matches your Docker/K8s/AgentOS work), grow from feature-owner (SDE 2) toward architecture-level decision-making (SDE 3/Staff), while continuing to build ambitious personal project like AgentOS that push learning beyond day-job scope.
Q6Why do you want to work at our company?โ–ถ
Generic trap to avoid: "Great culture, exciting opportunity" โ€” too vague, interviewer hear this every day.
Strong approach: Research 1-2 SPECIFIC thing about company's tech stack or product challenge, connect to your own skill/interest (e.g. "I saw you work heavily with distributed system at X scale โ€” that matches what I've been exploring building AgentOS's Nexus-a2a communication layer, I'd love to bring that curiosity here.")
Interview Day

Final Checklist Before Battle

Small check, big confidence. Tick before big day.

Cave wisdom: Confidence come from repetition, not luck. You already climbed Phase 1 to 4 โ€” trust the hunt you already did.