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.
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.
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.
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);
// 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];
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).
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().
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('');