JavaScript Algorithms: Binary Search, Sorting, and Recursion
Introduction
Lesson 3 of chapter 9 covers JavaScript algorithms for coding interviews. Trace binary search on a timetable, sort views without mutating React state, and use recursion or a sliding window when the problem calls for it. The original exercises practice algorithm skills from the Meta Front-End Developer pathway. Coding Interview Preparation (opens in a new tab)
Learning objectives
By the end of this lesson you can:
- Implement linear search and binary search and state when each applies.
- Avoid the common off-by-one and overflow-style mistakes in binary search.
- Explain bubble, insertion, merge, and quick sort and their complexities.
- Use
Array.prototype.sortcorrectly, including the comparator and its default string behavior. - Write recursive functions with a base case and a progress step.
- Convert between recursion and iteration and explain stack depth.
- Use memoization to remove repeated work in overlapping subproblems.
- Solve problems with sliding window and sort-then-scan patterns.
1. Linear search and binary search
Linear search checks items in order until it finds the target. For a dense array of n items with constant-cost equality checks, worst-case time is O(n) and working space is O(1).
Binary search on an ascending array discards about half of the candidate range per iteration. The example assumes finite numbers and returns any matching index when duplicates exist. It takes O(log n) worst-case time and O(1) working space. With 1,000,000 elements it makes at most about 20 midpoint probes.
function binarySearch(sorted, target) {
let low = 0;
let high = sorted.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (sorted[mid] === target) return mid;
if (sorted[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}Trace with [3, 8, 15, 21, 34, 55, 89] and target 34:
low=0 high=6 mid=3 -> 21 < 34 -> low=4
low=4 high=6 mid=5 -> 55 > 34 -> high=4
low=4 high=4 mid=4 -> 34 found, return 4Where binary search goes wrong
- Using
low < highinstead oflow <= highskips the case where one element remains. - Setting
low = midorhigh = midinstead ofmid + 1/mid - 1can loop forever. - Running it on unsorted data returns wrong answers without any error.
- Test the empty array. Here
high = -1skips the loop and returns-1. - Keep the midpoint as a normal numeric index. Bitwise operators coerce JavaScript numbers to 32-bit integers, which can corrupt large indexes.
Binary search for a boundary
Often you want the first position meeting a condition, such as the first session starting at or after 14:00 (840 minutes) in a sorted list.
function firstAtOrAfter(sortedTimes, minute) {
let low = 0;
let high = sortedTimes.length; // note: length, not length - 1
while (low < high) {
const mid = low + Math.floor((high - low) / 2);
if (sortedTimes[mid] < minute) low = mid + 1;
else high = mid;
}
return low; // length means "none"
}For [540, 660, 780, 900, 1020] and 840, the answer is index 3 (900). This lower-bound search works with a half-open search range [low, high). When the midpoint qualifies, it can be the answer, so high = mid keeps it as a boundary candidate. On termination, low === high is the first qualifying index or length.
2. Sorting
Sorting puts items in order so that later steps (binary search, duplicates, merging) become cheap.
| Algorithm | Best | Average | Worst | Extra space | Stable | Idea |
|---|---|---|---|---|---|---|
| Bubble sort with early exit | O(n) | O(n²) | O(n²) | O(1) | Yes | Stop when a pass makes no swaps |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes | Insert each item into the sorted prefix |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes | Split, sort halves, merge |
| In-place quicksort, two recursive calls | O(n log n) | O(n log n) for distinct keys and randomized pivots | O(n²) | O(log n) expected, O(n) worst-case stack | Usually no | Partition around a pivot and sort the remaining ranges |
A sort is stable when items that compare equal keep their original relative order. A stable sort by level can retain the title order established within each level. The table assumes constant-cost comparisons. Space for insertion sort describes the in-place algorithm, and the example allocates O(n) for its input copy.
Insertion sort
function insertionSort(items) {
const a = [...items]; // do not mutate the input
for (let i = 1; i < a.length; i++) {
const value = a[i];
let j = i - 1;
while (j >= 0 && a[j] > value) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = value;
}
return a;
}Good for tiny or nearly sorted lists; poor for large random data.
Merge sort
Divide and conquer: split the array in half, sort each half recursively, then merge two sorted halves.
function mergeSort(items) {
if (items.length <= 1) return items.slice(); // fresh result even for 0 or 1 item
const mid = Math.floor(items.length / 2);
const left = mergeSort(items.slice(0, mid));
const right = mergeSort(items.slice(mid));
return merge(left, right);
}
function merge(left, right) {
const out = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) out.push(left[i++]); // <= keeps it stable
else out.push(right[j++]);
}
return out.concat(left.slice(i), right.slice(j));
}There are O(log n) levels. Across each level, splitting and merging process O(n) items. The total time is O(n log n) and peak extra array storage is O(n), plus O(log n) call frames. The code is stable for numbers because equal values are taken from the left half first.
Quick sort in words
Partition around a pivot, then recurse on the ranges that still need sorting. Discuss how the partition handles equal values. Balanced splits give O(n log n) work. Repeatedly isolating one element gives O(n²) time and can build a stack of depth n. Recursing into the smaller side and iterating over the larger one can bound stack use even when partition work stays quadratic. MIT OpenCourseWare, sorting (opens in a new tab)
Array.prototype.sort in JavaScript
ECMAScript requires Array.prototype.sort to be stable when the comparator is consistent. The specification leaves the sorting algorithm and its time and memory costs to the implementation. State assumptions when using O(n log n) as a comparison-sort estimate. ECMAScript Array sort (opens in a new tab)
[10, 9, 1, 100].sort(); // [1, 10, 100, 9] - converts to strings!
[10, 9, 1, 100].sort((a, b) => a - b); // [1, 9, 10, 100]For the numeric example, the default compares string representations in lexicographic UTF-16 code-unit order. A comparator returns a negative value when a precedes b, a positive value when b precedes a, and zero for a tie. sort mutates its array and returns the same reference. Copy state first or use toSorted on supported runtimes. Revisit JavaScript array methods and copying.
const sorted = [...workshops].sort((a, b) => a.title.localeCompare(b.title));localeCompare applies locale-aware collation. Choose a locale and options if the app needs a particular order for accents, case, or numbers. toSorted(compare) produces a shallow sorted copy. MDN Array toSorted (opens in a new tab)
3. Recursion
To make a recursive algorithm terminate, define a stopping condition and show how each call gets closer to it. For sumTo, assume a nonnegative integer and an exact result within JavaScript's safe integer range.
The two parts are:
- A base case that returns directly.
- A recursive case that moves toward the base case.
function sumTo(n) {
if (n <= 0) return 0; // base case
return n + sumTo(n - 1); // progress: n shrinks
}Trace sumTo(3):
sumTo(3) = 3 + sumTo(2)
= 3 + (2 + sumTo(1))
= 3 + (2 + (1 + sumTo(0)))
= 3 + (2 + (1 + 0)) = 6Each suspended call in sumTo keeps a stack frame. This gives O(n) stack space. The maximum depth and error type vary by engine. A loop for the same sum uses O(1) working space. MDN recursion errors (opens in a new tab)
Recursion on nested data
Recursion shines where the data is nested, such as comment threads or a file tree.
function countComments(comment) {
let total = 1;
for (const reply of comment.replies) total += countComments(reply);
return total;
}
countComments({
text: 'Great class',
replies: [{ text: 'Agree', replies: [] }, { text: 'Which room?', replies: [{ text: 'B2', replies: [] }] }],
}); // 4Flatten a nested array
function flatten(value) {
const out = [];
function visit(items) {
for (const item of items) {
if (Array.isArray(item)) visit(item);
else out.push(item);
}
}
visit(value);
return out;
}
flatten([1, [2, [3, 4]], 5]); // [1, 2, 3, 4, 5]For dense, acyclic nested arrays, the accumulator visits each entry once and avoids copying each subtree into every ancestor. It uses O(h) stack space for depth h plus the output. array.flat(Infinity) also flattens dense arrays and skips holes in sparse arrays. For unbounded depth, use an explicit stack and define limits on the input size.
4. Worked example: Fibonacci and memoization
Problem. Return the nth Fibonacci number, where fib(0) = 0, fib(1) = 1, and fib(n) = fib(n-1) + fib(n-2). The examples assume an integer n from 0 through 78 for exact Number results. Larger exact Fibonacci values need a different numeric representation such as BigInt, whose arithmetic cost grows with the operands.
Naive recursion.
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}Analysis. fib(5) calls fib(4) and fib(3); fib(4) calls fib(3) again. The same subproblems are recomputed many times. The call count grows exponentially. O(2ⁿ) is an upper bound, and the tight exponential base is the golden ratio, about 1.618. Runtime also depends on the engine and hardware.
Fix 1: memoization. Cache results by input.
function fibMemo(n, cache = new Map()) {
if (n <= 1) return n;
if (cache.has(n)) return cache.get(n);
const value = fibMemo(n - 1, cache) + fibMemo(n - 2, cache);
cache.set(n, value);
return value;
}Each non-base index is computed once per cache. Under the expected constant-time map model, that gives O(n) expected time and O(n) space for the cache and stack.
Fix 2: iteration.
function fibIter(n) {
let previous = 0;
let current = 1;
for (let i = 0; i < n; i++) {
[previous, current] = [current, previous + current];
}
return previous;
}O(n) time, O(1) space. Trace fibIter(4): (0,1) → (1,1) → (1,2) → (2,3) → (3,5), returns 3.
Why the alternatives are weaker. Naive recursion is correct but unusable beyond small inputs. Memoization is excellent when subproblems overlap and the recursion is natural. Iteration is best when only the final value is needed and memory matters. Your interview answer should name all three and recommend one for the stated constraints.
Front-end connection. useMemo can reuse a calculation while its dependencies match. React.memo can skip some renders when props compare equal. These tools are render optimizations. Measure whether they help, using React profiling and memoization.
5. Sliding window and sort-then-scan
Sliding window
A sliding window keeps a contiguous range and moves it one step at a time, updating a running value instead of recomputing it.
Problem. Given daily visitor counts whose sums fit in the safe integer range, find the highest total over any k consecutive days. Return null when k is not an integer from 1 through the number of days.
function bestWindow(counts, k) {
if (!Number.isInteger(k) || k < 1 || k > counts.length) return null;
let windowSum = 0;
for (let i = 0; i < k; i++) windowSum += counts[i];
let best = windowSum;
for (let i = k; i < counts.length; i++) {
windowSum += counts[i] - counts[i - k]; // add new day, drop oldest
best = Math.max(best, windowSum);
}
return best;
}
bestWindow([4, 9, 2, 7, 5, 1], 3); // 18 (9 + 2 + 7)
bestWindow([4, 9, 2], 0); // nullThe window uses O(n) time and O(1) working space. Recomputing each sum takes O((n − k + 1)·k) time, which is also O(n) for a fixed k but repeats additions. For the sample the consecutive totals are 15, 18, 14, and 13.
Sort, then scan
Sorting turns many "compare everything" problems into a single pass.
Problem. Merge booking intervals that overlap or touch at an endpoint. Each interval contains finite numbers with start at or before end. For example, [[9,12],[11,14],[16,18]] becomes [[9,14],[16,18]].
function mergeIntervals(intervals) {
const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
const merged = [];
for (const [start, end] of sorted) {
const last = merged[merged.length - 1];
if (last && start <= last[1]) last[1] = Math.max(last[1], end);
else merged.push([start, end]);
}
return merged;
}The scan is O(n). With an O(n log n) sorting algorithm and constant-cost comparison, total time is O(n log n). The built-in sort cost depends on the engine. The copied input uses O(n) array slots, and the returned intervals are new arrays. Use Math.max to keep the widest end, such as [1,10] when followed by [2,3]. The <= condition also merges adjacent ranges. Use < if the requirement is strict overlap for half-open bookings.
6. Choosing between iteration and recursion
| Question | Prefer recursion | Prefer iteration |
|---|---|---|
| Data is naturally nested (trees, folders) | Yes | Possible with an explicit stack |
| Depth can be very large | No (stack overflow) | Yes |
| Overlapping subproblems | Yes, with memoization | Yes, bottom-up |
| Simplicity of explanation | Often | Sometimes |
JavaScript engines do not reliably optimize tail calls, so do not rely on "tail recursion" to avoid stack growth.
7. Interview practice tips
For exact binary search, state the sorted-input precondition and the invariant that a possible match remains between low and high, inclusive.
For recursion, state the base case and explain why each call moves toward it.
Pitfalls:
- Calling
sort()on numbers without a comparator. - Mutating state with
sortorreversein React. - Infinite recursion from a missing or unreachable base case.
- Binary search on unsorted data, or an off-by-one in the bounds.
- Using recursion for a very deep structure without considering stack limits.
- Memoizing with a cache that never gets cleared in a long-running app (memory growth).
- Assuming quick sort is always O(n log n).
- Forgetting that
slicein a recursive function copies and adds cost.
8. Mini case study: the sorted, searchable price list
Situation. Harbor Workshops shows up to 50,000 sessions sorted by start time. Requirements: (1) jump to the first session at or after a chosen time; (2) show a list sorted by price, ties broken by title; (3) a developer proposes computing a nested menu depth with recursion on user-uploaded data.
Solution, commented.
- Jump to a time. The data is already sorted, so binary search for the boundary (
firstAtOrAfter, section 1). Cost O(log n) ≈ 16 comparisons instead of scanning up to 50,000 items on every click. - Sort by price, then title. Use one comparator that handles both keys. The built-in stable sort preserves input order if both keys compare equal.
const byPriceThenTitle = (a, b) =>
a.price - b.price || a.title.localeCompare(b.title);
const view = [...sessions].sort(byPriceThenTitle);Copy the array before sorting. Include comparator cost if titles are long. If profiling shows repeated sorts are expensive, use useMemo with sessions as a dependency and update sessions immutably.
- Recursion on uploaded data. Validate the uploaded tree's shape, node count, and depth before traversal. The example assumes a validated acyclic tree with
childrenarrays, ornullfor an empty tree. Iteration avoids deep JavaScript call stacks and uses explicit working memory for queued nodes.
function maxDepth(root) {
if (root === null) return 0;
let best = 0;
const stack = [[root, 1]];
while (stack.length > 0) {
const [node, depth] = stack.pop();
best = Math.max(best, depth);
for (const child of node.children) stack.push([child, depth + 1]);
}
return best;
}- Verification. Test empty lists, a single session, times before the first and after the last session (expect index
0andlength), equal prices with different titles, and a deliberately deep tree.
Key terms
- Binary search: halving a sorted range to find a value in O(log n).
- Stable sort: equal items keep their original order.
- Comparator: a function that defines ordering for
sort. - Divide and conquer: split a problem, solve parts, combine.
- Base case: the input at which recursion stops.
- Call stack: memory that tracks active function calls.
- Memoization: caching function results by input.
- Sliding window: a moving range updated incrementally.
Summary checklist
- I can write binary search without off-by-one errors and state its precondition.
- I can compare bubble, insertion, merge, and quick sort.
- I always pass a comparator to
sortfor numbers and copy before sorting state. - I write recursion with a clear base case and progress step.
- I recognize overlapping subproblems and apply memoization.
- I can use sliding window and sort-then-scan to avoid O(n²).
- I can explain when to prefer iteration to avoid stack overflow.
Sources
- Coding Interview Preparation (official course): https://www.coursera.org/learn/coding-interview-preparation (opens in a new tab)
- MDN
Array.prototype.sort: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort (opens in a new tab) - MIT OpenCourseWare, sorting algorithms (opens in a new tab)
- MIT OpenCourseWare, recursion (opens in a new tab)
- MDN safe integer range (opens in a new tab)
- React useMemo (opens in a new tab)
- React memo (opens in a new tab)
