Data Structures & Algorithms (JS Edition)

While React is your main tool, many companies (especially those asking for CS degrees) will test your fundamental knowledge of algorithms. You don't need to be a competitive programmer, but you must know the basics.

1. Big O Notation

Q: What is the time complexity of accessing an array element by index vs searching for a value?
Think about how memory is structured.
Examples
const arr = [10, 20, 30, 40];

// Access by Index: O(1) - Constant Time
console.log(arr[2]); 

// Search by Value: O(n) - Linear Time
const found = arr.find(x => x === 40); 
// In worst case, it has to check every element.
Show Answer

Access (Index): O(1). Arrays are stored in contiguous memory blocks, so the computer can calculate the exact address instantly.

Search (Value): O(n). The computer must check each box one by one until it finds the match.

Why it matters: If you are rendering a list of 10,000 items, find() inside a loop becomes O(n^2), which will freeze the browser.

2. Hash Maps (Objects/Maps)

Q: How can you optimize finding an item in a large dataset?
Turn O(n) into O(1).
The Problem (O(n))
const users = [{id: 1, name: 'A'}, {id: 2, name: 'B'}, ...];
// Finding user with ID 999 requires looping.
const user = users.find(u => u.id === 999);
The Solution (O(1))
// Pre-process into a Map/Object (Hash Map)
const userMap = {
  1: {id: 1, name: 'A'},
  2: {id: 2, name: 'B'},
  // ...
};

// Instant lookup
const user = userMap[999];
Show Answer

Use a Hash Map (Object or Map in JS). It allows for O(1) lookups by key. This is a very common optimization pattern in React when dealing with normalized state (like Redux).

3. Common Algorithms

Q: Explain the difference between Bubble Sort and Quick Sort/Merge Sort.
Why is .sort() fast?
Show Answer

Bubble Sort: O(n^2). Very slow. Compares adjacent elements and swaps them. Good for teaching, bad for production.

Quick Sort / Merge Sort: O(n log n). Much faster. JavaScript's built-in .sort() usually uses a variation of Merge Sort (TimSort in V8).

Takeaway: Never write your own sort function in production unless you have a very specific constraint. Use .sort().

Q: Reverse a string without using .reverse()
A classic "whiteboard" question.
Implementation
function reverseStr(str) {
  let result = '';
  for (let i = str.length - 1; i >= 0; i--) {
    result += str[i];
  }
  return result;
}

// Or using Array methods (Modern)
const reverseModern = str => str.split('').reverse().join('');