Algorithms and Data Structures Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What does Big O notation describe?
Correct answer: How the running time or memory grows as the input size grows
Big O describes the growth rate: how the cost changes when
ngrows, ignoring constants and lower-order terms. It says nothing about absolute time on a specific machine: an O(n) loop can be slower than an O(n²) one for small inputs.2. What is the time complexity of this function?
function sum(arr) { let total = 0; for (const x of arr) total += x; return total; }Correct answer: O(n)
The loop visits each element once, so the work grows linearly with the length of the array. The additions and the assignment inside the loop are constant-time operations.
3. What is the time complexity of two nested loops over the same array of length
n?for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { count++; } }Correct answer: O(n²)
For each of the
niterations of the outer loop the inner loop runsntimes, so the body runs n × n times. O(2n) would be two loops one after another, and that simplifies to O(n).4. Why is O(2n + 10) written simply as O(n)?
Correct answer: Because constants and lower-order terms don't change the growth rate
Big O describes the shape of growth for large
n. Multiplying by 2 or adding 10 doesn't change that the cost grows linearly, so both are dropped. In practice constants still matter, which is why benchmarks exist.5. Which complexity grows the slowest as
nincreases?Correct answer: O(log n)
Logarithmic growth is very slow: doubling
nadds just one step. For a million elements log₂ n is about 20. O(n) and O(n log n) grow much faster.6. What is the complexity of reading
arr[i]from a JavaScript array?Correct answer: O(1)
Access by index is constant time: the engine computes where the element is instead of walking through the array. That's the main advantage of arrays over linked lists.
7. Which array operation is usually O(n) in JavaScript?
Correct answer:
arr.shift()shiftremoves the first element, so every remaining element has to move one position to the left.pushandpopwork at the end of the array and are O(1) (amortized forpush).8. What is the complexity of
arr.includes(x)on an unsorted array?Correct answer: O(n)
includescompares elements one by one until it finds a match, so in the worst case it checks alln. If you need many membership checks, build aSetonce and useset.has(x), which is O(1) on average.9. Why is
set.has(x)usually faster thanarr.includes(x)for large collections?Correct answer: A
Setis a hash-based structure, so a lookup is O(1) on averageSet(andMap) are implemented with hash tables: the value's hash points almost directly to where it is stored.Setis not sorted and can store values of any type.10. What is the space complexity of this function?
function double(arr) { return arr.map((x) => x * 2); }Correct answer: O(n)
mapcreates a new array of the same length, so the extra memory grows linearly withn. Space complexity counts additional memory, not the input itself.11. What does O(1) extra space mean for an algorithm?
Correct answer: Its extra memory stays the same for any input size
O(1) space means a fixed amount of additional memory regardless of
n: a few counters or pointers. Reversing an array in place with two indices is O(1) space; copying it into a new array is O(n).12. What is the main idea of a hash table?
Correct answer: Turn a key into an index with a hash function and store the value there
The hash function maps a key to a bucket index, so the value can be found without scanning all entries. That gives O(1) average time for insert, lookup and delete.
13. What is a collision in a hash table?
Correct answer: Two different keys end up with the same bucket index
There are more possible keys than buckets, so different keys sometimes hash to the same index. Tables handle this with chaining (a list per bucket) or open addressing (probing the next free slot).
14. What is the worst-case lookup time in a hash table?
Correct answer: O(n)
If many keys collide into the same bucket, a lookup has to check them one by one. Good hash functions and resizing make this extremely rare, so the average stays O(1).
15. When is a
Mapa better choice than a plain object for a dictionary?Correct answer: When keys are not strings, or entries are added and removed often
Mapaccepts keys of any type (objects, numbers), keeps insertion order, hassizeand is optimized for frequent additions and deletions. A plain object converts keys to strings and inherits keys from its prototype.16. What is the simplest way to remove duplicates from an array of primitives?
const arr = [3, 1, 3, 2, 1];Correct answer:
[...new Set(arr)]A
Setkeeps only unique values and preserves the order of first occurrence, so the result is[3, 1, 2]in O(n). Sorting doesn't remove anything, andfilter(Boolean)only drops falsy values.17. How do you check in O(n) whether an array contains duplicates?
Correct answer: Walk the array once and track seen values in a
SetOne pass with a
Set: ifseen.has(x)is already true, there's a duplicate. Nested loops andindexOfinside a loop are both O(n²).18. What does the stack data structure guarantee?
Correct answer: Last in, first out (LIFO)
A stack returns the most recently added element first, like a stack of plates. In JavaScript an array with
pushandpopis a ready-made stack with O(1) operations.19. Which task is a natural fit for a stack?
Correct answer: Checking that brackets in an expression are balanced
Push every opening bracket; on a closing bracket pop and check that it matches. The last opened bracket must be closed first, which is exactly LIFO. Serving requests in order is a queue.
20. What does a queue guarantee?
Correct answer: The first added element is removed first
A queue is FIFO: elements leave in the order they arrived, like people in a line. "The smallest first" describes a priority queue, which is a different structure.
21. Why can a queue built on
pushandshiftbecome slow on large inputs?Correct answer:
shiftmoves all remaining elements, which is O(n)Each
shiftre-indexes the rest of the array, so dequeuingnitems can cost O(n²) in total. For heavy use keep a head index and readarr[head++], or use a linked list or a ring buffer.22. Where does the JavaScript runtime itself use a stack?
Correct answer: To keep track of function calls: the call stack
Each call pushes a frame with its local variables and return address;
returnpops it. That's why deep or infinite recursion ends with "Maximum call stack size exceeded".23. What is a singly linked list?
Correct answer: A chain of nodes, each pointing to the next one
Each node knows only its successor; the list is accessed through its head. Nodes don't have to sit next to each other in memory, unlike array elements.
24. What is the cost of getting the k-th element of a linked list?
Correct answer: O(k)
There is no index: you have to start at the head and follow
nextk times. That's the main trade-off compared with arrays, wherearr[k]is O(1).25. Which operation is O(1) in a linked list but O(n) at the start of an array?
Correct answer: Inserting a new element at the beginning
Adding to the front of a list means creating a node and pointing it at the old head. In an array every element has to shift one position to make room (
unshift).26. What does every correct recursive function need?
Correct answer: A base case that stops the recursion
Without a base case the function calls itself forever until the call stack overflows. Each recursive call must also move closer to the base case, for example with a smaller
n.27. What happens when you call this function?
function countdown(n) { console.log(n); countdown(n - 1); } countdown(3);Correct answer: It never stops and crashes with a stack overflow
There is no base case such as
if (n === 0) return, so the function goes into negative numbers and keeps calling itself. Each call takes a stack frame, and eventually the stack overflows.28. Why is this Fibonacci function slow for
n = 40?function fib(n) { if (n < 2) return n; return fib(n - 1) + fib(n - 2); }Correct answer: It recomputes the same values again and again
fib(n - 1)andfib(n - 2)both recompute the same smaller values, so the call tree has about 2ⁿ nodes. Caching results (memoization) or a simple loop makes it O(n).29. What is memoization?
Correct answer: Caching results by arguments so repeat calls are instant
A memoized function stores results in a cache keyed by its arguments. It only works correctly for pure functions, whose result depends only on their arguments.
30. What is linear search?
Correct answer: Checking elements one by one until the target is found
Linear search works on any array, sorted or not, and costs O(n) in the worst case.
indexOf,includesandfindall do linear search.31. What does binary search require from the data?
Correct answer: The array must be sorted
Binary search compares the target with the middle element and discards the half where it cannot be. That decision only makes sense if the array is sorted. Duplicates are fine.
32. What is the time complexity of binary search?
Correct answer: O(log n)
Each step halves the remaining range, so after about log₂ n steps only one element is left. For a billion elements that's about 30 comparisons.
33. Roughly how many comparisons does binary search need in a sorted array of 1,000,000 elements?
Correct answer: About 20
2²⁰ is about a million, so halving the range 20 times leaves one element. Linear search would need up to a million comparisons.
34. What does this code return?
[10, 1, 5, 100].sort();Correct answer:
[1, 10, 100, 5]Without a comparator
sortconverts elements to strings and compares them as text, so "10" and "100" come before "5". For numbers pass a comparator:sort((a, b) => a - b).35. What should the comparator
(a, b) => ...return forsortto putabeforeb?Correct answer: A negative number
A negative value means
agoes first, a positive value meansbgoes first, and zero keeps their relative order. That's why(a, b) => a - bsorts numbers in ascending order.36. What is important to remember about
arr.sort()?Correct answer: It sorts the array in place and returns the same array
sortmutates the original array, which can surprise code that still uses it, for example React state.toSorted()(ES2023) returns a sorted copy instead.37. What does a stable sort guarantee?
Correct answer: Equal elements keep their original relative order
Stability matters when you sort by several keys: sort users by name, then stably by age, and users of the same age stay ordered by name.
Array.prototype.sorthas been required to be stable since ES2019.38. What is the typical time complexity of a good general-purpose comparison sort?
Correct answer: O(n log n)
Merge sort, heapsort and Timsort (used by V8) run in O(n log n). Simple sorts such as bubble, selection and insertion sort are O(n²) in the worst case.
39. How does bubble sort work?
Correct answer: It repeatedly swaps adjacent elements that are in the wrong order
After each pass the largest remaining element "bubbles" to the end. It's O(n²) and is mainly used for teaching. Splitting and merging is merge sort; partitioning around a pivot is quicksort.
40. When is insertion sort a good choice?
Correct answer: For small or almost sorted arrays
Insertion sort is O(n²) in general but close to O(n) on nearly sorted data, and it has very low overhead. That's why Timsort uses it for short runs inside its O(n log n) algorithm.
41. How do you reverse an array in place with O(1) extra memory?
Correct answer: Swap elements from both ends, moving toward the middle
Two pointers
i = 0andj = n - 1swaparr[i]andarr[j]and move toward each other until they meet. Copying or using a stack needs O(n) extra memory.42. What is the "two pointers" technique?
Correct answer: Moving two indices through the data by a rule
Two indices move through the array instead of nested loops, which often turns O(n²) into O(n). Classic uses: checking a palindrome from both ends, merging two sorted arrays, finding a pair with a given sum in a sorted array.
43. How do you check whether a string is a palindrome in O(n) time and O(1) extra space?
Correct answer: Compare characters from both ends moving toward the middle
Two pointers compare
s[i]withs[j]and stop at the first mismatch. Reversing works too but creates a new string, so it uses O(n) memory. Sorting is wrong: it loses the order of characters.44. How do you check that two strings are anagrams in O(n)?
Correct answer: Count the characters of both strings and compare the counts
Count characters of the first string in a map, subtract the second string, and check that all counts are zero. Equal length isn't enough, and the "every character is present" check ignores how many times it appears ("aab" vs "abb"). Sorting both strings works too, but costs O(n log n).
45. What is the complexity of building a string with
+=in a loop in modern JavaScript engines?Correct answer: Usually fine: engines optimize repeated concatenation
Strings are immutable, but engines such as V8 use ropes, so repeated
+=is not copied every time and stays practical. In languages without this optimization the classic advice is to collect parts in an array andjointhem.46. What is a tree in data structures?
Correct answer: A hierarchy with one root where each node has one parent
A tree has no cycles and exactly one path between any two nodes. Examples: the DOM, the file system, a JSON object. A general network of nodes with possible cycles is a graph.
47. What is a leaf in a tree?
Correct answer: A node without children
Leaves are the end points of the hierarchy: files in a folder tree, text nodes in the DOM. The root is the only node without a parent.
48. What is the height of a tree?
Correct answer: The longest root-to-leaf path, counted in edges
Height determines the cost of many operations: in a balanced binary search tree it's about log₂ n, in a degenerate one (a "stick") it's n.
49. What property does a binary search tree (BST) have?
Correct answer: Left subtree values are smaller than the node, right ones are larger
This ordering lets a search go left or right at each node and skip half of the remaining tree when it's balanced. "Values increase toward the leaves" describes a heap, not a BST.
50. What is the time to find a value in a balanced BST with
nnodes?Correct answer: O(log n)
Each step goes down one level, and a balanced tree has about log₂ n levels. If the tree degenerates into a chain (for example, after inserting sorted values), search becomes O(n).
51. What happens if you insert the values 1, 2, 3, 4, 5 in order into a simple (non-balancing) BST?
Correct answer: The tree becomes a chain, and operations degrade to O(n)
Each new value is larger than all previous ones and goes to the right, so the tree turns into a linked list. Self-balancing trees (AVL, red-black) rotate nodes to keep the height O(log n).
52. Which structure is the DOM of a web page?
Correct answer: A tree
documentis the root, every element has one parent and an ordered list of children. That's why DOM traversal (children,parentNode,querySelector) is tree traversal.53. What is the difference between depth-first (DFS) and breadth-first (BFS) traversal?
Correct answer: DFS follows one branch to the end first; BFS goes level by level
DFS is usually written with recursion or a stack, BFS with a queue. Both visit every node once, O(V + E), but in a different order. Both work on trees and on general graphs.
54. Which data structure does breadth-first search (BFS) use?
Correct answer: A queue
BFS takes the oldest discovered node next, which is FIFO: neighbors of the current level are processed before the next level. Replacing the queue with a stack turns it into DFS.
55. What is a graph?
Correct answer: Vertices connected by edges, possibly with cycles
Graphs model networks: users and friendships, pages and links, cities and roads. A tree is a special case of a connected graph without cycles.
56. What is the difference between a directed and an undirected graph?
Correct answer: In a directed graph edges have a direction (A → B is not B → A)
Twitter follows are directed: you can follow someone who doesn't follow you. Facebook friendships are undirected. A directed graph can have cycles; one without them is called a DAG.
57. How is a graph usually stored when it has many vertices but few edges?
Correct answer: As an adjacency list: each vertex with its neighbors
An adjacency list takes O(V + E) memory, while a matrix always takes O(V²), which is wasteful for sparse graphs. The matrix is handy when the graph is dense or you need an O(1) "is there an edge?" check.
58. What does this adjacency list describe?
const graph = { A: ["B", "C"], B: ["C"], C: [], };Correct answer: A directed graph with edges A → B, A → C and B → C
Each key lists the vertices it has edges to. C has no outgoing edges, and nothing points to A. In an undirected graph each edge would appear in both lists.
59. What is the complexity of finding the maximum of an unsorted array?
Correct answer: O(n)
Any element could be the maximum, so each one must be checked at least once. One pass with a running maximum is optimal. Sorting first would be O(n log n), slower than needed.
60. Why can
Math.max(...arr)fail on a very large array?Correct answer: Every element becomes an argument, and engines limit their number
Arguments are placed on the stack, so hundreds of thousands of them can throw a RangeError. For big arrays use a simple loop or
reduce, which also stays O(n).61. How do you count how many times each word appears in a list in O(n)?
Correct answer: Use a
Mapfrom word to count and increment it in one passOne pass with
counts.set(w, (counts.get(w) ?? 0) + 1)is O(n) on average. Frequency counting with a hash map is one of the most common building blocks in interview problems.62. Two Sum: find two numbers in an unsorted array that add up to
target. What is the O(n) approach?Correct answer: Check whether
target - xis in a map of numbers seen so farOne pass: if
target - xwas seen before, the pair is found; otherwise rememberxand its index. Trying every pair is O(n²). Sorting gives O(n log n) and loses the original indices.63. What does "amortized O(1)" mean for
arr.push?Correct answer: Rare O(n) resizes average out to O(1) per push
When the internal buffer is full, the array allocates a bigger one (usually about double) and copies everything. Because the size doubles, these copies are rare, and the total cost of n pushes is O(n).
64. What is the time complexity of the
isPrimecheck below?function isPrime(n) { if (n < 2) return false; for (let i = 2; i * i <= n; i++) { if (n % i === 0) return false; } return true; }Correct answer: O(√n)
The loop stops when
i * i > n, so it runs at most √n times. A divisor larger than √n would pair with one smaller than √n, which the loop has already checked.65. What is the complexity of this loop?
for (let i = 1; i < n; i *= 2) { console.log(i); }Correct answer: O(log n)
idoubles each step: 1, 2, 4, 8... It reachesnafter about log₂ n iterations. Loops where the variable is multiplied or divided by a constant are logarithmic.66. What is the complexity of looking up a key in a plain JavaScript object,
obj[key]?Correct answer: O(1) on average
Engines store object properties in hash-table-like structures (or hidden classes for stable shapes), so access is constant time on average, just like
Map.67. What is a prefix sum array?
Correct answer: Element
iholds the sum of the firstioriginal elementsAfter one O(n) pass, the sum of any range
[l, r)isprefix[r] - prefix[l]in O(1). It's the go-to trick when the same array is queried for many range sums.68. What is the complexity of
arr.slice()(copying the whole array)?Correct answer: O(n)
A copy has to touch every element, so it's linear in time and memory. The same applies to
[...arr],Array.from(arr)andstructuredClone. Copying inside a loop easily turns an algorithm into O(n²).69. What is a matrix (2D grid) usually represented as in JavaScript?
Correct answer: An array of arrays, accessed as
grid[row][col]Grids show up in many problems: maps, game boards, images. Each cell often has up to four neighbors
(r±1, c)and(r, c±1), so a grid is also a graph that can be traversed with BFS or DFS.70. Why should you avoid
new Array(3).fill([])for a 3 × 3 grid?const grid = new Array(3).fill([]); grid[0].push(1);Correct answer: All three rows are the same shared array
fillputs the same object reference into every slot, sogrid[1]andgrid[2]also get the 1. Create separate rows instead:Array.from({ length: 3 }, () => []).71. What is a greedy algorithm?
Correct answer: One that makes the locally best choice at every step
Greedy algorithms are simple and fast, but they only give the optimal answer for some problems, such as making change with standard coins or picking non-overlapping intervals by earliest end. Trying every combination is brute force.
72. What does "brute force" mean for an algorithm?
Correct answer: Trying all possible candidates and checking each one
Brute force is usually the easiest correct solution and a good starting point in an interview. Then you look for repeated work to remove, for example with a hash map, sorting or two pointers.
73. An algorithm is O(n²). Roughly how much longer does it take when the input grows from 1,000 to 10,000 items?
Correct answer: About 100 times longer
The input grew 10 times, so n² grew 10² = 100 times. For O(n) it would be about 10 times, for O(log n) just a few extra steps.
74. Why is a
Setof objects not useful for removing duplicate objects with the same content?new Set([{ id: 1 }, { id: 1 }]).size;Correct answer: A
Setcompares objects by reference, so two different objects both stay (size 2)Setuses SameValueZero, which for objects means identity. To dedupe by content, key aMapby an identifying field:new Map(items.map((x) => [x.id, x])).75. How does
arr.splice(i, 1)in the middle of an array affect performance?Correct answer: It's O(n): elements after
ishift one position leftRemoving from the middle keeps the array dense, so everything after the index moves. Deleting many elements one by one in a loop is O(n²);
filterinto a new array is O(n).