InterviewTreedInterviewTreed

InterviewTreed Question Bank

Interview Preparation & Coding Interview Questions and Answers

Prepare for technical interviews with data structures, algorithms, coding problems, problem-solving techniques, behavioral questions, and practical interview exercises.

Total Questions

50

Beginner

20

Intermediate

25

Advanced

5

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Interview Fundamentals

How should you structure an answer to a technical interview question?

Start with a direct definition, explain why the concept matters, describe how it works, and give a concise example.

Answer

Start with a direct definition, explain why the concept matters, describe how it works, and give a concise example. For experience-based questions, state the context, your responsibility, the action you took, and the measurable result. This structure helps the interviewer follow your reasoning without unnecessary detail.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q2Interview Fundamentals

How do you clarify an ambiguous coding problem?

Restate the problem, identify inputs and outputs, ask about constraints, and confirm edge cases such as empty input, duplicates, and invalid values.

Answer

Restate the problem, identify inputs and outputs, ask about constraints, and confirm edge cases such as empty input, duplicates, and invalid values. Then propose a straightforward approach before optimizing it. Clarifying assumptions early prevents solving a different problem from the one intended.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q3Interview Fundamentals

What should you explain before writing code?

Explain the approach, important data structures, expected time and space complexity, and the edge cases you will handle.

Answer

Explain the approach, important data structures, expected time and space complexity, and the edge cases you will handle. Ask whether the interviewer agrees with the interpretation if requirements are unclear. Then write readable code and narrate meaningful decisions rather than describing every keystroke.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q4Interview Fundamentals

How do you analyze time complexity?

Time complexity describes how an algorithm's running time grows with input size.

Answer

Time complexity describes how an algorithm's running time grows with input size. Count how often the main operations execute and express the growth using Big O notation, ignoring constants and lower-order terms. For example, a single pass over n items is O(n), while comparing every pair is typically O(n²).

Syntax

Common growth rates:
O(1) constant | O(log n) halving | O(n) one pass | O(n log n) efficient sorting | O(n²) all pairs
Diagram: Input size n -> Count dominant operations -> Express growth as Big O

Example

// O(n): one pass through the input for (const item of items) { process(item); } // O(n^2): compare every pair for (let i = 0; i < items.length; i++) for (let j = i + 1; j < items.length; j++) compare(items[i], items[j]);

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q5Interview Fundamentals

What is the difference between time and space complexity?

Time complexity estimates how work grows with input size, while space complexity estimates how memory use grows.

Answer

Time complexity estimates how work grows with input size, while space complexity estimates how memory use grows. An algorithm can trade extra memory for faster lookup, such as using a hash set to reduce repeated searches. Explain whether you mean auxiliary space or total memory, including the input.

Syntax

Common growth rates:
O(1) constant | O(log n) halving | O(n) one pass | O(n log n) efficient sorting | O(n²) all pairs
Diagram: Input size n -> Count dominant operations -> Express growth as Big O

Example

// O(n): one pass through the input for (const item of items) { process(item); } // O(n^2): compare every pair for (let i = 0; i < items.length; i++) for (let j = i + 1; j < items.length; j++) compare(items[i], items[j]);

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q6Coding Problem Solving

How do you solve a problem using brute force first?

A brute-force approach systematically checks all plausible candidates and is often the simplest way to establish correctness.

Answer

A brute-force approach systematically checks all plausible candidates and is often the simplest way to establish correctness. State its complexity, test it against examples, and then look for repeated work or useful properties that can reduce the search. Starting simple provides a baseline for optimization.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q7Coding Problem Solving

When should you use a hash map in a coding interview?

Use a hash map when you need fast average-case lookup, counting, grouping, or mapping one value to another.

Answer

Use a hash map when you need fast average-case lookup, counting, grouping, or mapping one value to another. It can reduce repeated nested searches, as in the Two Sum problem. Consider key equality, collision behavior, memory use, and whether the problem requires deterministic ordering.

Syntax

Pattern:
```ts
const counts = new Map<number, number>();
for (const value of values) {
  counts.set(value, (counts.get(value) ?? 0) + 1);
}
```
Diagram: Input -> Scan once -> Update map/window -> Return result

Example

// Example: count frequencies with a map const counts = new Map<number, number>(); for (const value of values) { counts.set(value, (counts.get(value) ?? 0) + 1); }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q8Coding Problem Solving

How do you choose between an array and a linked list?

Arrays provide efficient indexed access and good cache locality, while inserting in the middle can require shifting elements.

Answer

Arrays provide efficient indexed access and good cache locality, while inserting in the middle can require shifting elements. Linked lists can insert or remove a known node efficiently but require traversal for indexed access and use extra pointer memory. Choose based on the operations the problem performs most often.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q9Coding Problem Solving

What is the two-pointer technique?

The two-pointer technique maintains two indexes that move through a sequence to avoid repeatedly scanning the same elements.

Answer

The two-pointer technique maintains two indexes that move through a sequence to avoid repeatedly scanning the same elements. It is useful for sorted arrays, pair-sum problems, reversing sequences, and removing duplicates. Correctness usually depends on a clear invariant explaining why moving one pointer cannot skip a valid solution.

Syntax

Pattern:
```ts
const counts = new Map<number, number>();
for (const value of values) {
  counts.set(value, (counts.get(value) ?? 0) + 1);
}
```
Diagram: Input -> Scan once -> Update map/window -> Return result

Example

// Example: count frequencies with a map const counts = new Map<number, number>(); for (const value of values) { counts.set(value, (counts.get(value) ?? 0) + 1); }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q10Coding Problem Solving

What is the sliding-window technique?

Sliding window maintains a contiguous range and updates its state as the left or right boundary moves.

Answer

Sliding window maintains a contiguous range and updates its state as the left or right boundary moves. It is useful for subarray or substring problems where a running count, sum, or constraint can be updated incrementally. Define when to expand and shrink the window, and prove that discarded positions cannot lead to a better answer.

Syntax

Pattern:
```ts
const counts = new Map<number, number>();
for (const value of values) {
  counts.set(value, (counts.get(value) ?? 0) + 1);
}
```
Diagram: Input -> Scan once -> Update map/window -> Return result

Example

// Example: count frequencies with a map const counts = new Map<number, number>(); for (const value of values) { counts.set(value, (counts.get(value) ?? 0) + 1); }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q41Interview Strategy and Practice

How should you prepare for a coding interview in one week?

Prioritize common patterns such as hash maps, two pointers, sliding windows, stacks, binary search, trees, graphs, and dynamic programming.

Answer

Prioritize common patterns such as hash maps, two pointers, sliding windows, stacks, binary search, trees, graphs, and dynamic programming. Solve a manageable number of problems deeply: explain the approach, implement it, test edge cases, and revisit mistakes. Also prepare a concise project walkthrough and behavioral examples.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q42Interview Strategy and Practice

How do you practice coding under a time limit?

Use a timer and follow a consistent sequence: clarify requirements, outline the approach, code, test, and state complexity.

Answer

Use a timer and follow a consistent sequence: clarify requirements, outline the approach, code, test, and state complexity. Afterward, review where time was lost and whether the solution was correct and readable. Gradually reduce hints and time while preserving explanation quality.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q43Interview Strategy and Practice

What should you do after failing a practice problem?

Record the pattern you missed, the key invariant, the bug or misconception, and a simpler example that reveals it.

Answer

Record the pattern you missed, the key invariant, the bug or misconception, and a simpler example that reveals it. Re-solve the problem later without looking at the solution, then try a related variant. The goal is to learn a reusable technique rather than memorize one answer.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q44Interview Strategy and Practice

How do you choose which problems to practice?

Choose problems that cover common patterns and match the target role's expected level.

Answer

Choose problems that cover common patterns and match the target role's expected level. Track patterns and weaknesses instead of counting only the number solved. Revisit problems after a delay and practice explaining solutions aloud to test whether the understanding is durable.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q45Interview Strategy and Practice

What questions should you ask the interviewer?

Ask about the team's technical challenges, architecture, code review and testing practices, success expectations for the role, and how work is delivered.

Answer

Ask about the team's technical challenges, architecture, code review and testing practices, success expectations for the role, and how work is delivered. Tailor questions to what has already been discussed. Avoid asking questions that are easily answered by the job description or company website.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q46Career Strategy and Follow-up

How do you tailor your resume to a job description?

Compare the job requirements with your actual experience, then emphasize relevant projects, responsibilities, and measurable outcomes using accurate terminology.

Answer

Compare the job requirements with your actual experience, then emphasize relevant projects, responsibilities, and measurable outcomes using accurate terminology. Prioritize the skills most relevant to the role and keep the document easy to scan. Never add technologies or achievements you cannot explain in an interview.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q47Career Strategy and Follow-up

How do you explain a career gap or job change?

Give a concise, honest explanation focused on the circumstances and what you did to stay prepared or what you learned.

Answer

Give a concise, honest explanation focused on the circumstances and what you did to stay prepared or what you learned. Then redirect to why the role fits your skills and goals. Avoid criticizing former employers or sharing unnecessary personal details.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q48Career Strategy and Follow-up

How should you follow up after an interview?

Send a brief thank-you message within a reasonable time, reference a specific discussion point, and reaffirm your interest.

Answer

Send a brief thank-you message within a reasonable time, reference a specific discussion point, and reaffirm your interest. If a timeline was provided, wait until it passes before asking for an update. Keep the message professional and avoid repeated follow-ups that create pressure.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q49Career Strategy and Follow-up

How do you negotiate an offer professionally?

Research a reasonable compensation range, consider the full package and role scope, and explain your expectations using market evidence and relevant experience.

Answer

Research a reasonable compensation range, consider the full package and role scope, and explain your expectations using market evidence and relevant experience. Ask clarifying questions before making a decision and communicate respectfully. Do not fabricate competing offers or make commitments you cannot keep.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q50Career Strategy and Follow-up

How do you evaluate whether a role is a good fit?

Consider the responsibilities, technologies, learning opportunities, team practices, manager expectations, compensation, and work arrangement.

Answer

Consider the responsibilities, technologies, learning opportunities, team practices, manager expectations, compensation, and work arrangement. Ask questions that reveal how success is measured and how engineering decisions are made. Compare the role against your priorities rather than deciding from title or salary alone.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q11Core Coding Patterns

How do you detect a cycle in a linked list?

Floyd's tortoise-and-hare algorithm uses a slow pointer moving one step and a fast pointer moving two steps.

Answer

Floyd's tortoise-and-hare algorithm uses a slow pointer moving one step and a fast pointer moving two steps. If a cycle exists, the pointers eventually meet; if the fast pointer reaches the end, there is no cycle. The algorithm runs in O(n) time and uses O(1) extra space.

Syntax

Floyd's cycle detection:
```ts
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
```
Diagram: Head -> A -> B -> C -> D
                     ^         |
                     |_________|
Slow moves 1 step; fast moves 2 steps

Example

function hasCycle(head: ListNode | null): boolean { let slow = head, fast = head; while (fast && fast.next) { slow = slow!.next; fast = fast.next.next; if (slow === fast) return true; } return false; }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q12Core Coding Patterns

How do you validate balanced parentheses?

Use a stack: push each opening bracket, and for every closing bracket verify that the stack is non-empty and its top is the matching opener.

Answer

Use a stack: push each opening bracket, and for every closing bracket verify that the stack is non-empty and its top is the matching opener. At the end, the stack must be empty. This takes O(n) time and O(n) worst-case space for n characters.

Syntax

Stack validation:
```ts
for (const char of text) {
  if (isOpening(char)) stack.push(char);
  else if (isClosing(char) && stack.pop() !== matchingOpen(char)) return false;
}
return stack.length === 0;
```
Diagram: Character -> Opening? push : closing? match top -> Balanced / Invalid

Example

function isBalanced(text: string): boolean { const stack: string[] = []; const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" }; for (const char of text) { if ("([{".includes(char)) stack.push(char); else if (")]}".includes(char) && stack.pop() !== pairs[char]) return false; } return stack.length === 0; }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q14Core Coding Patterns

What is a recursive solution and what is its risk?

A recursive solution solves a problem by calling itself on smaller subproblems until reaching a base case.

Answer

A recursive solution solves a problem by calling itself on smaller subproblems until reaching a base case. It can make trees and divide-and-conquer algorithms clearer, but missing base cases cause nontermination and deep recursion can exhaust the call stack. Explain the recurrence and stack-space cost.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q15Core Coding Patterns

How do you solve a problem with breadth-first search (BFS)?

BFS explores a graph level by level using a queue, marking nodes as visited when they are enqueued.

Answer

BFS explores a graph level by level using a queue, marking nodes as visited when they are enqueued. It finds shortest paths in an unweighted graph and runs in O(V + E) time with adjacency-list representation. Track parent pointers if you need to reconstruct a path.

Syntax

Graph traversal:
```ts
queue.push(start);
visited.add(start);
while (queue.length) {
  const node = queue.shift()!;
  for (const next of graph.get(node) ?? []) { /* visit unseen nodes */ }
}
```
Diagram: Start -> Frontier (queue/stack) -> Visit neighbors -> Continue

Example

function bfs(start: string, graph: Map<string, string[]>) { const queue = [start]; const visited = new Set([start]); for (let i = 0; i < queue.length; i++) { const node = queue[i]; for (const next of graph.get(node) ?? []) { if (!visited.has(next)) { visited.add(next); queue.push(next); } } } return visited; }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q16Data Structures and Algorithms

When is depth-first search (DFS) useful?

DFS explores a path as far as possible before backtracking, using recursion or an explicit stack.

Answer

DFS explores a path as far as possible before backtracking, using recursion or an explicit stack. It is useful for reachability, connected components, cycle detection, and tree traversals. Mark visited nodes to avoid repeated work, and account for recursion depth or use an iterative implementation.

Syntax

Graph traversal:
```ts
queue.push(start);
visited.add(start);
while (queue.length) {
  const node = queue.shift()!;
  for (const next of graph.get(node) ?? []) { /* visit unseen nodes */ }
}
```
Diagram: Start -> Frontier (queue/stack) -> Visit neighbors -> Continue

Example

function bfs(start: string, graph: Map<string, string[]>) { const queue = [start]; const visited = new Set([start]); for (let i = 0; i < queue.length; i++) { const node = queue[i]; for (const next of graph.get(node) ?? []) { if (!visited.has(next)) { visited.add(next); queue.push(next); } } } return visited; }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q17Data Structures and Algorithms

How do you find the top K frequent elements?

Count each value with a hash map, then use a min-heap of size K or bucket the values by frequency.

Answer

Count each value with a hash map, then use a min-heap of size K or bucket the values by frequency. A heap approach is typically O(n log k), while frequency buckets can achieve O(n) under suitable constraints. Clarify tie-breaking requirements before selecting an implementation.

Syntax

Pattern:
```ts
const counts = new Map<number, number>();
for (const value of values) {
  counts.set(value, (counts.get(value) ?? 0) + 1);
}
```
Diagram: Input -> Scan once -> Update map/window -> Return result

Example

// Example: count frequencies with a map const counts = new Map<number, number>(); for (const value of values) { counts.set(value, (counts.get(value) ?? 0) + 1); }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q18Data Structures and Algorithms

What is dynamic programming?

Dynamic programming solves overlapping subproblems by storing their results, using memoization or tabulation.

Answer

Dynamic programming solves overlapping subproblems by storing their results, using memoization or tabulation. Define the state, transition, base cases, and evaluation order before coding. It can reduce exponential repeated work to polynomial time when the number of distinct states and transitions is manageable.

Syntax

Tabulation:
```ts
dp[0] = 0; dp[1] = 1;
for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];
```
Diagram: Base states -> Transition -> Store results -> Final state

Example

function fib(n: number): number { if (n < 2) return n; const dp = Array(n + 1).fill(0); dp[1] = 1; for (let i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2]; return dp[n]; }

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q19Data Structures and Algorithms

How do you recognize a greedy algorithm problem?

A greedy algorithm makes a locally best choice at each step.

Answer

A greedy algorithm makes a locally best choice at each step. It is appropriate only when the problem has a property proving that local choices can be part of a global optimum. Provide a correctness argument, such as an exchange argument, and test counterexamples before relying on intuition.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q20Data Structures and Algorithms

How do you compare sorting algorithms in an interview?

Compare time complexity, auxiliary memory, stability, and whether the algorithm is in-place.

Answer

Compare time complexity, auxiliary memory, stability, and whether the algorithm is in-place. Merge sort guarantees O(n log n) time but usually needs extra memory for arrays; quicksort is often fast in practice but can degrade to O(n²) with poor pivots. Use the language's built-in sort unless implementation is the point.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q21Code Quality and Testing

How do you test a coding solution beyond the happy path?

Test normal inputs, boundary sizes, empty and singleton inputs, duplicates, sorted and reverse-sorted data, and invalid values if the contract allows them.

Answer

Test normal inputs, boundary sizes, empty and singleton inputs, duplicates, sorted and reverse-sorted data, and invalid values if the contract allows them. Compare results with a simple reference implementation for randomized small cases when useful. Tests should target the assumptions made by the algorithm.

Syntax

Arrange -> Act -> Assert:
```ts
const input = [2, 3];
const actual = sum(input);
expect(actual).toBe(5);
```
Diagram: Test input -> Function under test -> Assertion -> Pass/fail

Example

import { describe, it, expect } from "vitest"; describe("sum", () => { it("handles an empty array", () => expect(sum([])).toBe(0)); it("handles positive values", () => expect(sum([2, 3])).toBe(5)); });

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q22Code Quality and Testing

What is a unit test?

A unit test checks a small unit of behavior in isolation, usually with controlled dependencies.

Answer

A unit test checks a small unit of behavior in isolation, usually with controlled dependencies. Good unit tests are repeatable, fast, and focused on observable behavior rather than private implementation details. Include success cases, boundaries, and expected failures, and keep test names descriptive.

Syntax

Arrange -> Act -> Assert:
```ts
const input = [2, 3];
const actual = sum(input);
expect(actual).toBe(5);
```
Diagram: Test input -> Function under test -> Assertion -> Pass/fail

Example

import { describe, it, expect } from "vitest"; describe("sum", () => { it("handles an empty array", () => expect(sum([])).toBe(0)); it("handles positive values", () => expect(sum([2, 3])).toBe(5)); });

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q23Code Quality and Testing

What is the difference between a mock and a stub?

A stub supplies predetermined responses to a dependency, while a mock can also verify interactions such as whether a method was called with expected arguments.

Answer

A stub supplies predetermined responses to a dependency, while a mock can also verify interactions such as whether a method was called with expected arguments. Use test doubles to isolate external behavior, but avoid over-mocking internal details that make tests brittle when implementation changes.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q24Code Quality and Testing

How do you refactor code safely?

First establish behavior with tests, then make small changes that preserve the public contract and run the test suite after each step.

Answer

First establish behavior with tests, then make small changes that preserve the public contract and run the test suite after each step. Improve names, remove duplication, and separate responsibilities without mixing unrelated behavior changes into the refactor. Use version control so changes are reviewable and reversible.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q25Code Quality and Testing

What makes code readable in an interview?

Readable code uses meaningful names, small cohesive functions, consistent formatting, and explicit handling of edge cases.

Answer

Readable code uses meaningful names, small cohesive functions, consistent formatting, and explicit handling of edge cases. Avoid clever one-liners when they obscure intent. Explain important invariants and choose standard library functions when they make the solution clearer.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q26Project Discussion

How should you explain a project in an interview?

Start with the problem the project solves, the users, and the architecture at a high level.

Answer

Start with the problem the project solves, the users, and the architecture at a high level. Then describe your personal responsibilities, the most important technical decisions, a challenge you handled, and the outcome. Be clear about what you built yourself versus what the team delivered.

Syntax

STAR:
Situation -> Task -> Action -> Result
Example: Production latency spike -> Own diagnosis -> Inspect traces and optimize query -> Verify latency improvement

Example

// STAR answer outline const answer = { situation: "Context and impact", task: "My responsibility", action: "Steps I personally took", result: "Measured outcome and lesson" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q27Project Discussion

How do you explain your role in a team project?

Describe your ownership areas, interfaces with other team members, and the decisions you personally made.

Answer

Describe your ownership areas, interfaces with other team members, and the decisions you personally made. Use concrete examples such as designing an API, improving a query, or resolving a production issue. Avoid claiming ownership of work you only observed or contributed to indirectly.

Syntax

STAR:
Situation -> Task -> Action -> Result
Example: Production latency spike -> Own diagnosis -> Inspect traces and optimize query -> Verify latency improvement

Example

// STAR answer outline const answer = { situation: "Context and impact", task: "My responsibility", action: "Steps I personally took", result: "Measured outcome and lesson" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q28Project Discussion

How do you discuss a difficult technical challenge?

Explain the symptoms and impact, how you narrowed down the root cause, what options you considered, and why you chose the final fix.

Answer

Explain the symptoms and impact, how you narrowed down the root cause, what options you considered, and why you chose the final fix. State how you verified the fix and prevented recurrence. A strong answer shows a repeatable problem-solving process rather than only describing the final solution.

Syntax

STAR:
Situation -> Task -> Action -> Result
Example: Production latency spike -> Own diagnosis -> Inspect traces and optimize query -> Verify latency improvement

Example

// STAR answer outline const answer = { situation: "Context and impact", task: "My responsibility", action: "Steps I personally took", result: "Measured outcome and lesson" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q29Project Discussion

How do you explain a performance improvement?

Describe the baseline metric, how you measured the bottleneck, the change made, and the result under comparable conditions.

Answer

Describe the baseline metric, how you measured the bottleneck, the change made, and the result under comparable conditions. Include trade-offs and explain how you checked for regressions. Avoid unsupported percentage claims; use real measurements or clearly label estimates.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q30Project Discussion

How do you answer when you do not know a technology?

Be honest about the gap, then explain related concepts you do understand and how you would investigate the unfamiliar area.

Answer

Be honest about the gap, then explain related concepts you do understand and how you would investigate the unfamiliar area. Ask clarifying questions and outline a safe way to test assumptions. Do not bluff about production experience or invent details.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q31Behavioral and Situational Questions

How do you answer a behavioral question using STAR?

STAR stands for Situation, Task, Action, and Result.

Answer

STAR stands for Situation, Task, Action, and Result. Briefly set the context, explain your responsibility, focus most of the answer on actions you personally took, and finish with a concrete outcome or lesson. Keep the story relevant to the competency being assessed.

Syntax

STAR:
Situation -> Task -> Action -> Result
Example: Production latency spike -> Own diagnosis -> Inspect traces and optimize query -> Verify latency improvement

Example

// STAR answer outline const answer = { situation: "Context and impact", task: "My responsibility", action: "Steps I personally took", result: "Measured outcome and lesson" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q32Behavioral and Situational Questions

How do you describe a disagreement with a teammate?

Explain the shared goal, the specific technical disagreement, and how you compared options using evidence such as requirements, measurements, or a prototype.

Answer

Explain the shared goal, the specific technical disagreement, and how you compared options using evidence such as requirements, measurements, or a prototype. Describe how the team reached a decision and what you learned. Avoid blaming the other person or framing collaboration as winning an argument.

Syntax

STAR:
Situation -> Task -> Action -> Result
Example: Production latency spike -> Own diagnosis -> Inspect traces and optimize query -> Verify latency improvement

Example

// STAR answer outline const answer = { situation: "Context and impact", task: "My responsibility", action: "Steps I personally took", result: "Measured outcome and lesson" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q33Behavioral and Situational Questions

How do you prioritize when several tasks are urgent?

Clarify deadlines, business impact, dependencies, risk, and the cost of delaying each task.

Answer

Clarify deadlines, business impact, dependencies, risk, and the cost of delaying each task. Communicate trade-offs to stakeholders and agree on a priority order rather than silently attempting everything. Reassess when new information changes the impact or delivery constraints.

Syntax

Answer workflow:
```text
Clarify -> Explain approach -> Give example -> Discuss trade-offs -> Verify
```
Diagram: Problem -> Assumptions -> Solution -> Tests/metrics -> Result

Example

// A concise structured answer outline const response = { approach: "Explain the plan", example: "Give a concrete example", tradeOff: "State a limitation or alternative", verification: "Explain how you would test it" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q34Behavioral and Situational Questions

How do you respond to production incidents?

Stabilize the service and reduce user impact first, then gather evidence, communicate status, and coordinate a safe mitigation.

Answer

Stabilize the service and reduce user impact first, then gather evidence, communicate status, and coordinate a safe mitigation. After recovery, perform a blameless root-cause analysis and add tests, monitoring, or process changes. Explain your role and how you balance speed with operational safety.

Syntax

STAR:
Situation -> Task -> Action -> Result
Example: Production latency spike -> Own diagnosis -> Inspect traces and optimize query -> Verify latency improvement

Example

// STAR answer outline const answer = { situation: "Context and impact", task: "My responsibility", action: "Steps I personally took", result: "Measured outcome and lesson" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q35Behavioral and Situational Questions

How do you respond to constructive criticism?

Listen to the feedback, ask for a concrete example if needed, and separate the technical point from personal interpretation.

Answer

Listen to the feedback, ask for a concrete example if needed, and separate the technical point from personal interpretation. Explain what you changed or how you tested the suggestion, then describe the result. Show willingness to learn while still using evidence to discuss trade-offs.

Syntax

STAR:
Situation -> Task -> Action -> Result
Example: Production latency spike -> Own diagnosis -> Inspect traces and optimize query -> Verify latency improvement

Example

// STAR answer outline const answer = { situation: "Context and impact", task: "My responsibility", action: "Steps I personally took", result: "Measured outcome and lesson" };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q36System Design and API Discussion

How do you explain a system design under time constraints?

Clarify functional and non-functional requirements, estimate scale, identify core components and data flows, then discuss bottlenecks, failure modes, and trade-offs.

Answer

Clarify functional and non-functional requirements, estimate scale, identify core components and data flows, then discuss bottlenecks, failure modes, and trade-offs. Start with a simple design and deepen the areas most relevant to the requirements. Keep the interviewer involved by stating assumptions and asking which area to explore.

Syntax

Design sequence:
```text
Requirements -> API contract -> Components/data model -> Failure modes -> Metrics and trade-offs
```
Diagram: Client -> API -> Service -> Database/dependencies -> Response

Example

// Example request contract type ApiResponse<T> = | { ok: true; data: T; requestId: string } | { ok: false; error: { code: string; message: string }; requestId: string };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q37System Design and API Discussion

How do you design a reliable REST API?

Use resource-oriented endpoints, clear HTTP methods and status codes, input validation, authentication and authorization, pagination where needed, and consistent error responses.

Answer

Use resource-oriented endpoints, clear HTTP methods and status codes, input validation, authentication and authorization, pagination where needed, and consistent error responses. Define timeouts and idempotency behavior for retried operations. Document the contract and test both successful and failure paths.

Syntax

Design sequence:
```text
Requirements -> API contract -> Components/data model -> Failure modes -> Metrics and trade-offs
```
Diagram: Client -> API -> Service -> Database/dependencies -> Response

Example

// Example request contract type ApiResponse<T> = | { ok: true; data: T; requestId: string } | { ok: false; error: { code: string; message: string }; requestId: string };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q38System Design and API Discussion

What is idempotency and why does it matter?

An operation is idempotent when repeating the same request has the same intended effect as performing it once.

Answer

An operation is idempotent when repeating the same request has the same intended effect as performing it once. Idempotency keys can prevent duplicate payments, bookings, or job submissions when clients retry after timeouts. Store the key and result atomically with the operation and define its scope and retention.

Syntax

Design sequence:
```text
Requirements -> API contract -> Components/data model -> Failure modes -> Metrics and trade-offs
```
Diagram: Client -> API -> Service -> Database/dependencies -> Response

Example

// Example request contract type ApiResponse<T> = | { ok: true; data: T; requestId: string } | { ok: false; error: { code: string; message: string }; requestId: string };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q39System Design and API Discussion

How do you approach a database performance issue?

Measure query latency and workload first, inspect execution plans, indexes, row counts, and lock contention, then change one factor at a time.

Answer

Measure query latency and workload first, inspect execution plans, indexes, row counts, and lock contention, then change one factor at a time. Check whether the bottleneck is query design, missing indexes, excessive round trips, or infrastructure. Compare results under representative load and watch write overhead from new indexes.

Syntax

Design sequence:
```text
Requirements -> API contract -> Components/data model -> Failure modes -> Metrics and trade-offs
```
Diagram: Client -> API -> Service -> Database/dependencies -> Response

Example

// Example request contract type ApiResponse<T> = | { ok: true; data: T; requestId: string } | { ok: false; error: { code: string; message: string }; requestId: string };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.
Q40System Design and API Discussion

How do you explain a trade-off between consistency and availability?

Explain which failures the system must tolerate and what users observe during a network partition or dependency outage.

Answer

Explain which failures the system must tolerate and what users observe during a network partition or dependency outage. Stronger consistency can restrict successful operations when coordination is unavailable, while weaker consistency can allow temporary divergence. Choose based on business invariants and describe reconciliation behavior.

Syntax

Design sequence:
```text
Requirements -> API contract -> Components/data model -> Failure modes -> Metrics and trade-offs
```
Diagram: Client -> API -> Service -> Database/dependencies -> Response

Example

// Example request contract type ApiResponse<T> = | { ok: true; data: T; requestId: string } | { ok: false; error: { code: string; message: string }; requestId: string };

Key Points

  • State assumptions and explain the reasoning behind the approach.
  • Cover edge cases and verify the solution before concluding.
  • Communicate trade-offs clearly and avoid claiming experience you do not have.

Share this question bank

Send this page to someone preparing for an interview.