SWE Interview Flashcards

(30 cards)

1
Q

What is the difference between var, let, and const in JavaScript?

A

var is function-scoped and can be redeclared; let is block-scoped and reassignable; const is block-scoped and cannot be reassigned, but objects can be mutated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How does this work in JavaScript?

A

this refers to the context of a function’s call. In global scope, it’s window (browser). In a method, it’s the object. Arrow functions inherit this lexically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a closure in JavaScript?

A

A closure is a function that retains access to its outer scope’s variables. Example: function outer() { let x = 10; return () => x; } returns a function accessing x.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is event delegation in JavaScript?

A

Event delegation handles events on a parent element for its children, using event bubbling. Example: Add click listener to a ul to handle li clicks (reduces listeners).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Explain the event loop in JavaScript.

A

The event loop processes the call stack and callback queue, handling asynchronous tasks (e.g., setTimeout, promises) when the stack is empty, enabling non-blocking I/O.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a Promise in JavaScript?

A

A Promise represents an asynchronous operation’s outcome (pending, fulfilled, rejected). Example: new Promise((resolve, reject) => resolve('Done')).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do async and await simplify asynchronous code?

A

async functions return Promises; await pauses execution until a Promise resolves. Example: async function fetchData() { let data = await fetch(url); }.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a React component?

A

A React component is a function or class returning UI as JSX. Example: function MyComponent() { return <div>Hello</div>; }.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the purpose of useState in React?

A

useState manages state in functional components, returning a state value and updater. Example: const [count, setCount] = useState(0);.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain the useEffect hook in React.

A

useEffect runs side effects (e.g., API calls) after render, with a dependency array to control execution. Example: useEffect(() => { fetchData(); }, [id]);.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a controlled component in React?

A

A controlled component ties form input values to React state, updated via onChange. Example: <input value={state} onChange={(e) => setState(e.target.value)} />.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How does React.memo improve performance?

A

React.memo memoizes a functional component, preventing re-renders unless props change. Example: const Memoized = React.memo(MyComponent);.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the virtual DOM in React?

A

The virtual DOM is an in-memory representation of the real DOM. React diffs it with the previous version to minimize DOM updates.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a data structure?

A

A data structure organizes data for efficient access/modification, like arrays (contiguous memory) or linked lists (nodes with pointers).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is an algorithm?

A

An algorithm is a step-by-step procedure to solve a problem, like sorting an array or searching for an item.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Big O notation?

A

Big O describes the worst-case growth rate of an algorithm’s time or space usage as input size increases. Example: O(n) for linear time.

17
Q

What is O(log n) time complexity?

A

O(log n) is logarithmic time, where runtime grows slowly by halving the problem. Example: Binary search on a sorted array.

18
Q

What is the time complexity of accessing a hash table?

A

O(1) average case for hash table lookups, assuming minimal collisions and a good hash function.

19
Q

What is the Sliding Window pattern, with an example?

A

Sliding Window optimizes subarray/substring problems. Example: function maxSum(arr, k) { let sum = 0, max = 0; for (let i = 0; i < k; i++) sum += arr[i]; max = sum; for (let i = k; i < arr.length; i++) { sum += arr[i] - arr[i-k]; max = Math.max(max, sum); } return max; } (O(n)).

20
Q

Implement Two Pointers to reverse an array in place.

A

```javascript
function reverseArray(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++;
right–;
}
return arr;
}
// Example: reverseArray([1, 2, 3]) → [3, 2, 1]
// Explanation: Swaps elements from both ends (O(n)).
~~~

21
Q

Use Binary Search to find the first occurrence of a target.

A

```javascript
function firstOccurrence(arr, target) {
let left = 0, right = arr.length - 1, result = -1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
result = mid;
right = mid - 1;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
// Example: firstOccurrence([1, 2, 2, 2, 3], 2) → 1
// Explanation: Tracks first occurrence while searching (O(log n)).
~~~

22
Q

What is Kadane’s Algorithm for max subarray sum?

A

```javascript
function maxSubArray(nums) {
let max = nums[0], current = nums[0];
for (let i = 1; i < nums.length; i++) {
current = Math.max(nums[i], current + nums[i]);
max = Math.max(max, current);
}
return max;
}
// Example: maxSubArray([-2, 1, -3, 4, -1, 2]) → 6
// Explanation: Tracks local and global max sum (O(n)).
~~~

23
Q

Explain Depth-First Search (DFS) with a code snippet.

A

```javascript
function dfs(graph, start, visited = new Set()) {
visited.add(start);
console.log(start);
for (let neighbor of graph[start]) {
if (!visited.has(neighbor)) dfs(graph, neighbor, visited);
}
}
// Example: graph = {0:[1,2], 1:[2], 2:[]} → dfs(graph, 0) prints 0,1,2
// Explanation: Recursively explores each branch (O(V + E)).
~~~

24
Q

What is the Merge Intervals pattern?

A

```javascript
function mergeIntervals(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
let result = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
let 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;
}
// Example: mergeIntervals([[1,3], [2,6], [8,10]]) → [[1,6], [8,10]]
// Explanation: Merges overlapping intervals (O(n log n)).
~~~

25
What is a linked list, and how do you reverse it?
```javascript class ListNode { constructor(val) { this.val = val; this.next = null; } } function reverseList(head) { let prev = null, current = head; while (current) { let next = current.next; current.next = prev; prev = current; current = next; } return prev; } // Example: 1->2->3 → 3->2->1 // Explanation: Iteratively reverses pointers (O(n)). ```
26
What is the time complexity of quicksort?
Average case O(n log n), worst case O(n²) when the pivot is poorly chosen (e.g., sorted array). Uses divide-and-conquer.
27
How does currying work in JavaScript?
```javascript function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn(...args); return (...nextArgs) => curried(...args, ...nextArgs); }; } // Example: const add = curry((a, b) => a + b); add(2)(3) → 5 // Explanation: Transforms a function to take arguments one at a time. ```
28
What is a hash table, and what’s its average lookup time?
A hash table stores key-value pairs using a hash function for indexing. Average lookup time is O(1), worst case O(n) with collisions.
29
Explain error boundaries in React.
```javascript class ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError() { return { hasError: true }; } render() { if (this.state.hasError) return

Error!

; return this.props.children; } } // Example: Wraps to catch errors in child components // Explanation: Catches JavaScript errors in child tree, renders fallback UI. ```
30
What is the Monotonic Stack pattern?
```javascript function nextGreaterElement(nums) { let stack = [], result = new Array(nums.length).fill(-1); for (let i = 0; i < nums.length; i++) { while (stack.length && nums[stack[stack.length - 1]] < nums[i]) { result[stack.pop()] = nums[i]; } stack.push(i); } return result; } // Example: nextGreaterElement([4, 5, 2, 25]) → [5, 25, 25, -1] // Explanation: Maintains a stack of increasing/decreasing elements (O(n)). ```