Questions 101–120 of 200 · 0 of 20 on this page marked learned
101.javascript-0101Hardsenior
How do you write a deep clone function that handles circular references, Date, Map, Set, and RegExp?
Walk the value recursively and keep a WeakMap from each original object to its clone, so a reference seen again returns the existing clone instead of recursing forever. Create the right container for each type (Date, RegExp, Map, Set, Array, plain object), copy symbol keys too, and keep the prototype. In real code, structuredClone covers most of this, but it cannot copy functions or keep prototypes.
Full answer
A naive recursive clone loops forever on a cycle such as a.self = a. The fix is a memory of what has already been cloned: a WeakMap that maps each original object to its clone. Before cloning an object, look it up. If it is there, return the clone you already made. Create the empty clone and store it in the map before you copy the children, otherwise the cycle is not detected in time. A WeakMap is the right tool because it does not keep the originals alive after the clone is done.
Each type needs its own handling. A Date is rebuilt with new Date(value.getTime()). A RegExp is rebuilt from its source and flags, and lastIndex is copied. A Map and a Set are rebuilt by cloning their keys and values, which also preserves shared references inside them. An array is cloned by index. A plain object is created with Object.create(Object.getPrototypeOf(value)) so the prototype is kept, and then every own key from Reflect.ownKeys is copied, which includes symbol keys. Primitives and functions are returned as they are. Functions cannot be cloned in a meaningful way, so they are shared.
The built-in structuredClone already handles cycles, Date, Map, Set, RegExp, typed arrays, and more. It throws on functions and on DOM nodes, drops the prototype (class instances become plain objects), and ignores getters by reading their value. Write a custom clone only when you need to keep prototypes or treat functions in a special way.
Test the cases that fail most often: a cycle, two properties pointing to the same object (the clone must also share one object, not two), and a Map holding objects.
javascript
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== 'object') return value;
if (seen.has(value)) return seen.get(value);
if (value instanceof Date) return new Date(value.getTime());
if (value instanceof RegExp) {
const copy = new RegExp(value.source, value.flags);
copy.lastIndex = value.lastIndex;
return copy;
}
if (value instanceof Map) {
const copy = new Map();
seen.set(value, copy);
for (const [k, v] of value) copy.set(deepClone(k, seen), deepClone(v, seen));
return copy;
}
if (value instanceof Set) {
const copy = new Set();
seen.set(value, copy);
for (const v of value) copy.add(deepClone(v, seen));
return copy;
}
const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
seen.set(value, copy);
for (const key of Reflect.ownKeys(value)) {
if (Array.isArray(value) && key === 'length') continue;
copy[key] = deepClone(value[key], seen);
}
return copy;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
sum() { return this.x + this.y; }
}
const shared = { n: 1 };
const tag = Symbol('tag');
const original = {
when: new Date(0),
pattern: /ab+/gi,
list: [1, [2, 3]],
map: new Map([['k', { deep: true }]]),
set: new Set([1, 2]),
point: new Point(2, 3),
a: shared,
b: shared,
[tag]: 'symbol value',
};
original.self = original;
const copy = deepClone(original);
console.log('cycle kept:', copy.self === copy, copy !== original);
console.log('shared reference kept shared:', copy.a === copy.b, copy.a !== shared);
console.log('date and regexp:', copy.when instanceof Date, copy.when !== original.when, copy.pattern.flags);
console.log('map and set:', copy.map.get('k').deep, copy.map.get('k') !== original.map.get('k'), copy.set.has(2));
console.log('prototype kept:', copy.point instanceof Point, copy.point.sum());
console.log('symbol key copied:', copy[tag]);
console.log('nested array copied:', copy.list[1] !== original.list[1], copy.list);
const viaStructured = structuredClone(original);
console.log('structuredClone cycle:', viaStructured.self === viaStructured);
console.log('structuredClone loses prototype:', viaStructured.point instanceof Point, typeof viaStructured.point.sum);
try {
structuredClone({ run() {} });
} catch (error) {
console.log('structuredClone on a function:', error.name);
}
Run with Node.js v24.22.1 as js-101.js; two runs gave identical output.
Output:
cycle kept: true true
shared reference kept shared: true true
date and regexp: true true gi
map and set: true true true
prototype kept: true 5
symbol key copied: symbol value
nested array copied: true [ 1, [ 2, 3 ] ]
structuredClone cycle: true
structuredClone loses prototype: false undefined
structuredClone on a function: DataCloneError
Key points
A WeakMap from original to clone detects cycles and keeps shared references shared.
Store the clone in the map before copying children.
Rebuild Date, RegExp, Map, and Set explicitly; use Reflect.ownKeys and keep the prototype for plain objects.
Functions and primitives are returned as they are.
structuredClone covers most needs but loses prototypes and throws on functions.
Common mistakes
Forgetting the seen map and overflowing the stack on a cycle.
Registering the clone in the map after copying children.
Cloning objects with JSON.parse(JSON.stringify(...)), which breaks Date, Map, Set, undefined, and cycles.
Copying Object.keys only and dropping symbol keys.
Follow-ups
Why use a WeakMap instead of a Map for the seen record?
How would you clone a class instance that has private fields?
When would you prefer structuredClone over a custom function?
Tips
Mention the cycle problem first, then the WeakMap solution.
Test shared references, not only cycles.
Know structuredClone limits: functions, prototypes, DOM nodes.
102.javascript-0102Mediummid
How do you flatten a nested object into dot-notation keys and turn it back again?
Walk the object recursively, passing down the key path, and write each leaf value into a flat result under the joined path. Decide how to treat arrays, empty objects, and keys that contain the separator. To reverse it, split each key and create nested objects or arrays along the path, and block keys such as __proto__.
Full answer
Flattening turns { a: { b: 1 } } into { 'a.b': 1 }. It is used for form data, query strings, translation files, and logging. The core is a recursive function with a prefix. For each own key, build the path (prefix + '.' + key). If the value is a plain object or an array with content, recurse. Otherwise it is a leaf and you store it under the path.
Decisions to state out loud:
Arrays: use the index as the key (items.0), so the structure can be restored.
Empty objects and arrays: keep them as leaf values, otherwise the keys vanish and cannot be restored.
Dates and other class instances: treat anything that is not a plain object or array as a leaf.
Keys that already contain the separator: they make the result ambiguous. Choose another separator or escape it.
Cycles: this simple version would recurse forever, so mention a seen set if cycles are possible.
Unflattening reads each key, splits it by the separator, and walks down the result object, creating containers as needed. When the next part of the path is a number, create an array, otherwise an object. Finally assign the value at the last part. A security point matters here: if the input keys come from users, a key like __proto__.polluted would write to Object.prototype. Reject __proto__, constructor, and prototype parts, or build the result with Object.create(null).
Complexity is linear in the number of leaves, plus the cost of building the path strings.
Recurse with a path prefix and store leaves under the joined key.
Use indexes for arrays and keep empty objects and arrays as leaves.
Treat only plain objects and arrays as containers.
Unflatten by splitting keys and creating arrays for numeric parts.
Block __proto__, constructor, and prototype when unflattening untrusted keys.
Common mistakes
Dropping empty objects and arrays, so they disappear after a round trip.
Recursing into Date or class instances and producing nonsense keys.
Unflattening user keys without blocking __proto__.
Using a separator that appears inside real keys.
Follow-ups
How would you handle keys that contain the separator?
How would you support cycles in flatten?
How would you write the same function with an iterative stack instead of recursion?
Tips
State the rule for arrays and empty values before coding.
Mention the prototype pollution risk when unflattening input.
Give the complexity: linear in the number of leaves.
103.javascript-0103Easyfresher
How do you write chunk, zip, unzip, and range helper functions for arrays?
Chunk uses a loop with slice and a step, zip uses Array.from with the shortest length and index access, unzip is zip applied to the rows, and range uses Array.from with a length formula. Handle empty input, a size of zero or less, and uneven lengths on purpose.
Full answer
These four helpers appear in almost every coding screen, and each one is short when you know the right built-ins.
chunk(array, size) splits an array into groups. Loop with i += size and push array.slice(i, i + size). The last group can be shorter. Reject sizes below 1, otherwise the loop never ends. The result for an empty array is an empty array.
zip(a, b, ...) pairs items by index: zip([1, 2], ['a', 'b']) gives [[1, 'a'], [2, 'b']]. Decide what to do when lengths differ. The common choice is the shortest length (Python behaviour). The alternative is the longest length, filling with undefined. Build it with Array.from({ length }, (_, i) => arrays.map((array) => array[i])).
unzip reverses zip. It is the same function applied to the pairs: zip(...pairs). That works because transposing a matrix twice gives the original.
range(start, end, step) produces numbers. Array.from({ length: Math.ceil((end - start) / step) }, (_, i) => start + i * step) is clear and avoids the floating point drift of repeated addition. Support a single argument as the end, a negative step, and a step of zero as an error.
Details that interviewers check: the original arrays must not change, empty input must work, and the code must not use new Array(n) with map, because that array has holes that map skips.
javascript
function chunk(array, size) {
if (!Number.isInteger(size) || size < 1) throw new RangeError('size must be a positive integer');
const groups = [];
for (let i = 0; i < array.length; i += size) groups.push(array.slice(i, i + size));
return groups;
}
function zip(...arrays) {
if (arrays.length === 0) return [];
const length = Math.min(...arrays.map((array) => array.length));
return Array.from({ length }, (_, i) => arrays.map((array) => array[i]));
}
const unzip = (pairs) => (pairs.length === 0 ? [] : zip(...pairs));
function range(start, end, step = 1) {
if (end === undefined) [start, end] = [0, start];
if (step === 0) throw new RangeError('step must not be 0');
const length = Math.max(0, Math.ceil((end - start) / step));
return Array.from({ length }, (_, i) => start + i * step);
}
console.log(chunk([1, 2, 3, 4, 5], 2));
console.log(chunk([], 3), chunk([1, 2], 5));
try {
chunk([1], 0);
} catch (error) {
console.log('chunk size 0:', error.name);
}
console.log(zip([1, 2, 3], ['a', 'b']));
const pairs = zip([1, 2], ['x', 'y']);
console.log(pairs, unzip(pairs));
console.log(range(4), range(2, 6), range(10, 0, -3), range(0, 1, 0.25));
console.log(range(3, 3), zip(), new Array(3).map((_, i) => i));
chunk: loop in steps of size with slice; reject size below 1.
zip: build by index with Array.from; choose shortest or longest length on purpose.
unzip is zip applied to the pairs.
range: Array.from with a length formula; handle negative steps and reject a zero step.
Do not mutate the input and avoid holey arrays from new Array(n).
Common mistakes
Forgetting to reject a chunk size of 0, which makes an endless loop.
Building ranges with repeated floating point addition and getting drift.
Using new Array(n).map to create sequences.
Mutating the input arrays with splice.
Follow-ups
How would you make zip use the longest length and fill missing values?
How would you write range as a lazy generator?
How would you chunk by total string length instead of by item count?
Tips
Ask what to do with uneven lengths and bad sizes before coding.
Prefer Array.from with a length object for sequences.
Show one test for empty input.
104.javascript-0104Hardsenior
How do you implement curry so that it supports a placeholder for skipped arguments?
Collect arguments across calls in a closure, where each call fills the placeholder slots from the left first and then appends the rest. When the number of real (non-placeholder) arguments reaches fn.length, call the function. fn.length ignores rest parameters and default values, so allow an explicit arity.
Full answer
A basic curry collects arguments until their count reaches fn.length, then calls fn. A placeholder, such as lodash's _, lets a caller skip an argument and supply it later: curried(_, 2)(1) is the same as curried(1, 2).
How to implement it. Keep an array of the arguments collected so far. On each call, create a new array: for every earlier slot that is still a placeholder, take the next new argument; after that, append what is left. Then count how many slots are real values. A slot counts as filled only when it is not the placeholder. Also the array length must be at least the arity, because a trailing placeholder is still missing. When all slots are filled, call fn with them. Otherwise return a new curried function that remembers the merged array. Each step returns a new closure, so the intermediate functions can be reused without sharing state: const add1 = curried(1) can be called many times.
Details:
fn.length is the number of parameters before the first default value or rest parameter. A function like (a, b = 2) => ... has length 1. Accept an optional arity argument for these cases.
Use a unique placeholder, a Symbol, so that no legitimate value equals it. If you export a placeholder, make sure callers import the same one.
Preserve this if the function is used as a method, by capturing it with a regular function and apply.
Currying helps partial application and building pipelines. The cost is readability for people who do not know it, and an extra closure per call.
javascript
const _ = Symbol('placeholder');
function curry(fn, arity = fn.length) {
function collect(received) {
return function (...args) {
const merged = received.slice();
let next = 0;
for (let i = 0; i < merged.length && next < args.length; i++) {
if (merged[i] === _) merged[i] = args[next++];
}
while (next < args.length) merged.push(args[next++]);
const filled = merged.slice(0, arity).filter((value) => value !== _).length;
if (merged.length >= arity && filled >= arity) return fn.apply(this, merged);
return collect(merged);
};
}
return collect([]);
}
const volume = curry((length, width, height) => `${length} x ${width} x ${height} = ${length * width * height}`);
console.log(volume(2, 3, 4));
console.log(volume(2)(3)(4));
console.log(volume(2, 3)(4));
console.log(volume(_, 3, 4)(2));
console.log(volume(_, _, 4)(2)(3));
console.log(volume(_, 3)(_, 4)(2));
const withTwo = volume(2);
console.log(withTwo(3, 4), withTwo(10, 10));
const greet = curry((greeting, name, punctuation = '!') => `${greeting}, ${name}${punctuation}`, 2);
console.log(greet('Hello')('Asha'));
console.log(((a, b = 1) => 0).length, ((...rest) => 0).length);
Run with Node.js v24.22.1 as js-104.js; two runs gave identical output.
Output:
2 x 3 x 4 = 24
2 x 3 x 4 = 24
2 x 3 x 4 = 24
2 x 3 x 4 = 24
2 x 3 x 4 = 24
2 x 3 x 4 = 24
2 x 3 x 4 = 24 2 x 10 x 10 = 200
Hello, Asha!
1 0
Key points
Collect arguments in a closure and call fn when all required slots are filled.
Fill earlier placeholder slots first, then append new arguments.
A slot is filled only if it is not the placeholder; trailing placeholders still count as missing.
fn.length ignores defaults and rest parameters, so allow an explicit arity.
Each step returns a new closure so partially applied functions are reusable.
Common mistakes
Relying on fn.length for functions with default or rest parameters.
Using undefined as the placeholder, so real undefined arguments are skipped.
Mutating the shared argument array, so partially applied functions affect each other.
Counting a trailing placeholder as a supplied argument.
Follow-ups
What is the difference between currying and partial application?
How would you make a curried function that accepts all remaining arguments at once?
How does compose or pipe work with curried functions?
Tips
Explain the fill-from-left rule with one example before coding.
Mention fn.length limits and a Symbol placeholder.
Show that partially applied functions are reusable.
105.javascript-0105Hardsenior
How do you build an async task queue with a concurrency limit and task priorities?
Keep a pending list ordered by priority (first in, first out for equal priority), a counter of running tasks, and a pump function that starts tasks while the counter is below the limit. add returns a promise for the task result, a rejected task must not stop the queue, and a promise that resolves when the queue is idle is useful. Running tasks are never interrupted by a higher priority one.
Full answer
This is the scheduler behind many upload, crawler, and API clients. It combines three ideas: a concurrency limit, a priority order, and results returned through promises.
Design:
add(task, priority = 0) wraps the task in a promise and stores { task, priority, order, resolve, reject }. The return value is a promise for the result, so callers can await their own task.
The pending list is ordered by higher priority first. For equal priority, a growing order number keeps first in, first out. A sorted insert or a binary heap keeps this efficient. For small queues, a sorted array insert is fine and easier to read.
#pump() runs while running < concurrency and the pending list is not empty. It takes the first item, increments running, runs the task, and in finally decrements running and pumps again.
A failing task rejects its own promise only. The queue continues. Never let one task's error escape into the pump.
onIdle() returns a promise that resolves when nothing is running or pending. It is useful for tests and for shutdown.
Behaviors worth stating: priority only changes the order in which waiting tasks start. A task that is already running is not interrupted. Adding a high priority task when all slots are busy puts it at the front of the waiting list, so it starts as soon as a slot is free.
Production features that you can mention: cancellation with AbortSignal, timeouts per task, pause and resume, retries, and a limit on the pending list size for back pressure.
Run with Node.js v24.22.1 as js-105.js; two runs gave identical output.
Output:
start order: A B D E C F
[ 'A done', 'B done', 'C done', 'D done', 'E failed', 'F done' ]
Key points
add returns a promise for the task's own result.
Pending list sorted by priority, with an order counter for FIFO among equals.
The pump starts tasks while running is below the limit and pumps again when one finishes.
A rejected task rejects only its own promise; the queue keeps going.
Priority does not interrupt running tasks; onIdle helps tests and shutdown.
Common mistakes
Letting a task error break the pump so queued tasks never start.
Sorting the whole list on each add and losing first in, first out order for equal priority.
Forgetting to call the pump again when a task finishes.
Expecting a new high priority task to cancel running tasks.
Follow-ups
How would you add cancellation with AbortSignal?
How would you replace the sorted array with a heap, and when does it matter?
How would you add a per-task timeout and retry?
Tips
State the three parts: limit, order, result promises.
Say clearly that running tasks are not preempted.
Mention onIdle for tests and graceful shutdown.
106.javascript-0106Hardsenior
How do you implement a rate limiter in JavaScript, and what is the difference between a token bucket and a sliding window?
A token bucket holds up to a capacity of tokens that refill at a steady rate, and each request takes one token, which allows short bursts but a steady average. A sliding window log stores timestamps and allows at most a limit of requests in any window, which is exact but uses more memory. Inject the clock so the limiter is testable.
Full answer
A rate limiter protects a service or an API client from too many requests. Two common algorithms differ in memory use and in how they treat bursts.
Token bucket: the bucket has a capacity and a refillPerSecond rate. Each request needs one token. Tokens are not added by a timer. Instead, on each call, compute the elapsed time since the last check, add elapsed * rate tokens, and cap the total at the capacity. If at least one token is available, take it and allow the request. The state is two numbers per client, so it is cheap. It allows a burst up to the capacity, and then a steady rate. Many public APIs use it.
Sliding window log: keep the timestamps of accepted requests in an array. On each call, drop timestamps older than now - windowMs, then allow the request only if fewer than limit remain. It is exact: no window ever holds more than the limit. The cost is memory proportional to the limit per client. A cheaper approximation is a fixed window counter, which has a known flaw: a client can send a full limit at the end of one window and again at the start of the next, doubling the rate for a moment.
Practical points:
Pass the clock in as a function (now = () => Date.now()), so tests can control time. Prefer performance.now() for in-process timing since it does not jump when the system clock changes.
Use one limiter per key, for example per user id or IP address, in a Map, and remove idle keys to avoid a memory leak.
A single Node.js process works as is. With several servers, the state has to live in a shared store such as Redis, and the check and update must be atomic, for example in a Lua script.
Return how long to wait (retryAfterMs), so servers can send a Retry-After header.
Run with Node.js v24.22.1 as js-106.js; two runs gave identical output.
Output:
bucket: ok, ok, ok, wait 1000, wait 500, ok, wait 1000, ok, ok, ok, wait 1000
window: ok, ok, ok, wait 700, wait 1, ok, ok, ok, wait 700
fixed window allows: 6 sliding window allows: 3
Key points
Token bucket: capacity plus refill rate; allows bursts and a steady average; two numbers of state.
Refill lazily on each call from the elapsed time, capped at capacity.
Sliding window log: exact per window but stores timestamps; fixed window counters allow a double burst at boundaries.
Inject the clock for tests; keep one limiter per key and clean up idle keys.
Several servers need shared atomic state, such as Redis.
Common mistakes
Using setInterval to add tokens instead of computing the refill from elapsed time.
Letting the token count grow past the capacity after a long pause.
Using fixed window counters and allowing double bursts at window boundaries.
Keeping limiter state per user in a Map forever.
Follow-ups
How would you share this limiter across several servers?
What is a leaky bucket and how is it different from a token bucket?
How would you test a limiter without waiting in real time?
Tips
Name both algorithms and the trade-off: memory against exactness and burst behavior.
Inject the clock and say why.
Mention Retry-After and shared state for several servers.
107.javascript-0107Mediummid
How do you write a memoize function with a time-to-live that also works for async functions?
Store results in a Map under a key built from the arguments, together with an expiry time, and check the expiry on every read. For async functions, cache the promise itself so concurrent calls share one request, and remove it from the cache if it rejects. Inject the clock for tests and cap the size to avoid unbounded memory.
Full answer
Plain memoization stores fn(args) the first time and returns the stored value later. A TTL (time to live) adds a lifetime: an entry older than ttl milliseconds is stale and must be computed again.
Implementation points:
Key: JSON.stringify(args) works for simple arguments. Accept a key option for objects, functions, or large arguments.
Entry: { value, expires }. On a call, read the entry. If it exists and now() < expires, return the value. Otherwise compute, store, and return. Lazy expiry on read is simple and needs no timers, so nothing keeps the process alive.
Async functions: store the promise, not the resolved value. Then two callers that arrive while the request is in flight share one call (this is called request deduplication). If the promise rejects, delete the entry so an error is not cached for the full TTL.
Memory: a cache without a limit is a memory leak. Add a maxSize and drop the oldest entry when full. A Map keeps insertion order, so the first key is the oldest.
Testing: pass now as an option so a test can move the clock.
Extras: a clear() method, a delete(key) method, and stale-while-revalidate (return the old value while a refresh runs) for latency-sensitive reads.
A caveat is this: use a regular function and fn.apply(this, args) if the memoized function is used as a method. Also never memoize functions with side effects, or functions that depend on hidden state, such as the current time or random numbers, unless that is what you want.
javascript
function memoizeWithTtl(fn, { ttl, maxSize = 100, key = (...args) => JSON.stringify(args), now = () => Date.now() }) {
const cache = new Map();
function memoized(...args) {
const id = key(...args);
const entry = cache.get(id);
if (entry && now() < entry.expires) return entry.value;
cache.delete(id);
const value = fn.apply(this, args);
cache.set(id, { value, expires: now() + ttl });
if (cache.size > maxSize) cache.delete(cache.keys().next().value);
if (value instanceof Promise) {
value.catch(() => {
if (cache.get(id)?.value === value) cache.delete(id);
});
}
return value;
}
memoized.clear = () => cache.clear();
memoized.size = () => cache.size;
return memoized;
}
let clock = 0;
let calls = 0;
const slowSquare = memoizeWithTtl((n) => (calls++, n * n), { ttl: 1000, now: () => clock });
console.log(slowSquare(4), slowSquare(4), 'calls:', calls);
clock = 999;
slowSquare(4);
console.log('before expiry, calls:', calls);
clock = 1000;
slowSquare(4);
console.log('at expiry, calls:', calls);
const limited = memoizeWithTtl((n) => n, { ttl: 10000, maxSize: 2, now: () => clock });
limited(1); limited(2); limited(3);
console.log('size capped at', limited.size());
async function main() {
let fetches = 0;
let fail = true;
const load = memoizeWithTtl(
async (id) => {
fetches++;
await new Promise((resolve) => setTimeout(resolve, 5));
if (fail) throw new Error('network down');
return { id };
},
{ ttl: 1000, now: () => clock },
);
const [first, second] = await Promise.allSettled([load(1), load(1)]);
console.log('shared in-flight call:', fetches, first.status, second.status);
await Promise.resolve();
fail = false;
console.log('after failure the error is not cached:', await load(1), 'fetches:', fetches);
await load(1);
console.log('success is cached:', fetches);
}
main();
Run with Node.js v24.22.1 as js-107.js; two runs gave identical output.
Output:
16 16 calls: 1
before expiry, calls: 1
at expiry, calls: 2
size capped at 2
shared in-flight call: 1 rejected rejected
after failure the error is not cached: { id: 1 } fetches: 2
success is cached: 2
Key points
Cache entries hold a value and an expiry; check expiry on each read.
Build the key from the arguments, or accept a custom key function.
For async functions, cache the promise so concurrent calls share one request, and delete on rejection.
Add a size cap, since an unbounded cache leaks memory.
Inject the clock for tests; do not memoize impure functions.
Common mistakes
Caching the resolved value of an async function, so parallel calls all hit the network.
Caching a rejected promise for the whole TTL.
Using JSON.stringify for keys with functions, undefined, or circular objects.
Leaving the cache unbounded.
Follow-ups
How would you add stale-while-revalidate behavior?
What is the difference between this and an LRU cache?
How would you share a cache across several servers?
Tips
Say that you cache the promise for async work and why.
Mention expiry on read, a size cap, and an injected clock.
Warn against memoizing impure functions.
108.javascript-0108Hardsenior
How does a virtual DOM diff work, and how would you build a minimal version that updates only what changed?
A virtual DOM is a plain object tree that describes the UI. On each update, a diff compares the old and new trees and applies only the differences to the real DOM: replace nodes of a different type, change text, set or remove attributes, and add or remove children. Keys let the algorithm match moved list items instead of recreating them.
Full answer
Real DOM updates are not free, and rewriting innerHTML throws away state such as focus and scroll position. A virtual DOM keeps a light description of the UI as plain objects, such as { type: 'li', props: { class: 'a' }, children: [...] }. Rendering becomes a pure function of state to a tree, and the library finds the smallest set of real changes.
The minimal algorithm compares nodes pair by pair at the same position:
No old node: create the new element and append it.
No new node: remove the old element.
Different type (or one is text and the other an element, or the texts differ): replace the whole node.
Same element type: update the attributes (set changed ones, remove missing ones), then diff the children by index, up to the longer of the two lists.
This is a linear walk, not the general tree edit distance, which would be far too slow. It relies on two assumptions, which React also makes: elements of different types produce different trees, and a developer can give list items a stable key.
The limitation of index matching is lists. If you insert an item at the start, every following item looks changed, and inputs can keep the wrong state. With keys, the algorithm builds a map from key to old node, reuses the node for the same key, and moves it instead of rebuilding it. The mini version below does not implement keys, and says so.
Real libraries add much more: event handler props, batching updates, scheduling, components with state, and fine-grained alternatives like Svelte and Solid that skip the virtual tree and update exact nodes. A virtual DOM is not always faster than direct DOM updates, but it makes updates predictable and avoids a lot of manual code.
javascript
const h = (type, props, ...children) => ({ type, props: props || {}, children: children.flat() });
const log = [];
function create(vnode) {
if (typeof vnode === 'string') return document.createTextNode(vnode);
const el = document.createElement(vnode.type);
for (const [name, value] of Object.entries(vnode.props)) el.setAttribute(name, value);
vnode.children.forEach((child) => el.appendChild(create(child)));
return el;
}
const changed = (a, b) => typeof a !== typeof b || (typeof a === 'string' && a !== b) || a.type !== b.type;
function patchProps(el, oldProps, newProps) {
for (const name of Object.keys({ ...oldProps, ...newProps })) {
if (!(name in newProps)) {
el.removeAttribute(name);
log.push(`remove attr ${name}`);
} else if (oldProps[name] !== newProps[name]) {
el.setAttribute(name, newProps[name]);
log.push(`set attr ${name}=${newProps[name]}`);
}
}
}
function update(parent, newNode, oldNode, index = 0) {
const el = parent.childNodes[index];
if (oldNode === undefined) {
parent.appendChild(create(newNode));
log.push('create ' + (newNode.type || 'text'));
} else if (newNode === undefined) {
parent.removeChild(el);
log.push('remove ' + (oldNode.type || 'text'));
} else if (changed(newNode, oldNode)) {
parent.replaceChild(create(newNode), el);
log.push('replace ' + (oldNode.type || 'text') + ' with ' + (newNode.type || 'text'));
} else if (typeof newNode !== 'string') {
patchProps(el, oldNode.props, newNode.props);
const length = Math.max(newNode.children.length, oldNode.children.length);
// walk children from the end so removals do not shift the indexes still to visit
for (let i = length - 1; i >= 0; i--) update(el, newNode.children[i], oldNode.children[i], i);
}
}
const view = (state) =>
h('div', { id: 'app', class: state.dark ? 'dark' : 'light' },
h('h1', null, 'Todos: ' + state.items.length),
h('ul', null, state.items.map((text) => h('li', null, text))),
state.error ? h('p', { role: 'alert' }, state.error) : h('span', null, 'ok'));
const root = document.body;
let current = view({ dark: false, items: ['milk', 'eggs'], error: '' });
root.appendChild(create(current));
console.log(root.innerHTML);
const next = view({ dark: true, items: ['milk', 'eggs', 'tea'], error: 'offline' });
const ulBefore = root.querySelector('ul');
update(root, next, current);
current = next;
console.log(log.join('\n'));
console.log(root.innerHTML);
console.log('same ul element reused:', root.querySelector('ul') === ulBefore);
log.length = 0;
const shorter = view({ dark: true, items: ['eggs'], error: 'offline' });
update(root, shorter, current);
console.log(log.join('\n'));
console.log(root.innerHTML);
Written for a browser console or script tag; checked here with Node.js v24.22.1 and jsdom, two runs with identical output.
Output:
<div id="app" class="light"><h1>Todos: 2</h1><ul><li>milk</li><li>eggs</li></ul><span>ok</span></div>
set attr class=dark
replace span with p
create li
replace text with text
<div id="app" class="dark"><h1>Todos: 3</h1><ul><li>milk</li><li>eggs</li><li>tea</li></ul><p role="alert">offline</p></div>
same ul element reused: true
remove li
remove li
replace text with text
replace text with text
<div id="app" class="dark"><h1>Todos: 1</h1><ul><li>eggs</li></ul><p role="alert">offline</p></div>
Key points
A virtual DOM is a plain object tree; rendering is a function from state to that tree.
The diff compares old and new nodes by position: create, remove, replace on type change, update props, recurse into children.
Linear time works because it assumes different types give different trees.
Index matching breaks for reordered lists; keys fix that by reusing nodes with the same key.
Fine-grained frameworks update exact nodes without a virtual tree.
Common mistakes
Replacing the whole tree with innerHTML and losing focus, scroll position, and input state.
Matching list items by index without keys when the list can reorder.
Comparing children without handling lists of different length.
Using array index as the key for lists that reorder.
Follow-ups
How do keys change the algorithm for lists?
Why is a virtual DOM not always faster than updating the DOM directly?
How do Svelte or Solid avoid a virtual DOM?
Tips
Describe the four cases (create, remove, replace, update) first.
Say that linear diffing depends on the types and keys assumptions.
Name the list problem and how keys solve it.
109.javascript-0109Hardsenior
How would you build a minimal Observable with map, filter, take, and unsubscribe support?
An Observable is a function that, when subscribed, starts producing values to an observer (next, error, complete) and returns a teardown function. Operators such as map and filter return new Observables that subscribe to the source and transform what passes through. It is lazy and can be cancelled, unlike a Promise, which is eager and delivers one value.
Full answer
An Observable describes a stream of values over time. It does nothing until someone subscribes, and each subscription runs the producer again (a cold observable). It is the model behind RxJS and the proposed standard Observable.
Core pieces:
Constructor: takes a subscribe function (observer) => teardown. The function pushes values with observer.next(value), can fail with observer.error(err), and ends with observer.complete(). It may return a cleanup function, for example one that calls clearTimeout or removeEventListener.
subscribe(observerOrFn): wraps the observer in a safe object. After error or complete, or after unsubscribe, the wrapper ignores further calls. That guarantee is important. It returns { unsubscribe }, which marks the wrapper closed and runs the teardown.
Operators: map(fn) returns new Observable((observer) => source.subscribe({ next: (v) => observer.next(fn(v)), error, complete })). filter calls next only if the predicate passes. take(n) completes after n values and unsubscribes from the source. Each operator returns the inner subscription's unsubscribe as its teardown, so cancelling the end of the chain cancels the start.
pipe(...operators) applies functions from left to right.
Compared with a Promise: an Observable can emit many values, is lazy, can be cancelled, and supports operators for composition. A Promise is eager, resolves once, and cannot be cancelled. Compared with an event emitter: the Observable composes with operators and has a clean completion and cleanup contract.
For production code, use RxJS, which also handles error propagation inside operators, schedulers, subjects for multicasting, and many more operators such as switchMap and debounceTime.
Run with Node.js v24.22.1 as js-109.js; two runs gave identical output.
Output:
value 20
value 40
value 60
array done
first subscriber 2
first subscriber 3
second subscriber 2
second subscriber 3
timer cleaned up
tick 0
tick 1
tick 2
take(3) complete
timer cleaned up
Key points
An Observable wraps a subscribe function that pushes next, error, and complete and returns a teardown.
It is lazy and cold: each subscription starts the producer.
The subscriber wrapper ignores calls after complete, error, or unsubscribe.
Operators return new Observables that subscribe to their source and pass the teardown down the chain.
Unlike Promises, Observables emit many values and can be cancelled.
Common mistakes
Not stopping the producer on unsubscribe, which leaves timers and listeners running.
Letting values pass after complete or error.
Treating an Observable as eager like a Promise.
Forgetting that each subscription runs the producer again.
Follow-ups
What is the difference between a cold and a hot Observable, and how does a Subject make one hot?
How would switchMap cancel a previous inner request?
When would you choose an Observable over async iterators?
Tips
Explain laziness and teardown first; they are the point of the design.
Show one operator and say that all others follow the same shape.
Compare with Promises and event emitters in one sentence each.
110.javascript-0110Hardsenior
How would you write a parser and evaluator for a small arithmetic expression language without using eval?
Split the text into tokens, then parse them with recursive descent, with one function per precedence level: expression for plus and minus, term for multiply and divide, power for exponent, and a unary and primary level for numbers, variables, function calls, and parentheses. The parser builds an AST that a separate function evaluates. Never use eval for untrusted input.
Full answer
Evaluating 2 + 3 * 4 correctly needs precedence and parentheses, and eval on user input is a security hole. A small parser is the safe answer, and it shows how real parsers work.
Step 1, tokenize: scan the text and produce tokens such as { type: 'num', value: 3 }, operators, parentheses, commas, and identifiers. A regular expression with the sticky flag (y) that matches at the current position is a short way to do it. Throw an error with the position on an unknown character.
Step 2, parse with recursive descent. The grammar, from lowest to highest precedence:
expression = term (('+' | '-') term)*
term = unary (('*' | '/') unary)*
unary = '-' unary | power
power = primary ('^' unary)?, which is right associative, so 2^3^2 is 2^(3^2)
Each rule is a function. A loop handles left associative operators, so 10 - 4 - 3 becomes (10 - 4) - 3. A higher precedence rule is called from a lower one, which is how the precedence is enforced without a table. The functions return AST nodes such as { type: 'binary', op, left, right }.
Step 3, evaluate: a recursive function with a switch on the node type, using a variables object and an allow list of functions (max, min, sqrt). Unknown names throw an error. Never look up names with eval or new Function.
Good error messages need the token position. Also test the edge cases: unary minus (-(2+3), 2 * -3), nested parentheses, missing closing parenthesis, and division by zero (which gives Infinity in JavaScript, so decide whether to throw).
javascript
function tokenize(text) {
const pattern = /\s*(?:(\d+(?:\.\d+)?)|([A-Za-z_]\w*)|(.))/y;
const tokens = [];
while (pattern.lastIndex < text.length) {
const match = pattern.exec(text);
if (!match) break;
const [whole, num, name, other] = match;
const lexeme = num ?? name ?? other;
const pos = match.index + whole.length - lexeme.length;
if (num !== undefined) tokens.push({ type: 'num', value: Number(num), pos });
else if (name !== undefined) tokens.push({ type: 'name', value: name, pos });
else if ('+-*/^(),'.includes(other)) tokens.push({ type: other, pos });
else throw new SyntaxError(`Unexpected character "${other}" at ${pos}`);
}
return tokens;
}
function parse(text) {
const tokens = tokenize(text);
let i = 0;
const peek = () => tokens[i]?.type;
const eat = (type) => {
if (peek() !== type) throw new SyntaxError(`Expected ${type} but found ${peek() ?? 'end of input'}`);
return tokens[i++];
};
function expression() {
let node = term();
while (peek() === '+' || peek() === '-') node = { type: 'binary', op: tokens[i++].type, left: node, right: term() };
return node;
}
function term() {
let node = unary();
while (peek() === '*' || peek() === '/') node = { type: 'binary', op: tokens[i++].type, left: node, right: unary() };
return node;
}
function unary() {
if (peek() === '-') { i++; return { type: 'neg', arg: unary() }; }
return power();
}
function power() {
const base = primary();
if (peek() === '^') { i++; return { type: 'binary', op: '^', left: base, right: unary() }; }
return base;
}
function primary() {
const token = tokens[i];
if (!token) throw new SyntaxError('Unexpected end of input');
if (token.type === 'num') { i++; return { type: 'num', value: token.value }; }
if (token.type === 'name') {
i++;
if (peek() !== '(') return { type: 'var', name: token.value };
i++;
const args = [];
if (peek() !== ')') {
do { args.push(expression()); } while (peek() === ',' && i++);
}
eat(')');
return { type: 'call', name: token.value, args };
}
if (token.type === '(') { i++; const inner = expression(); eat(')'); return inner; }
throw new SyntaxError(`Unexpected ${token.type} at ${token.pos}`);
}
const ast = expression();
if (i < tokens.length) throw new SyntaxError(`Unexpected ${tokens[i].type} at ${tokens[i].pos}`);
return ast;
}
const FUNCTIONS = { max: Math.max, min: Math.min, sqrt: Math.sqrt };
function evaluate(node, vars = {}) {
switch (node.type) {
case 'num': return node.value;
case 'var':
if (!Object.hasOwn(vars, node.name)) throw new ReferenceError('Unknown variable ' + node.name);
return vars[node.name];
case 'neg': return -evaluate(node.arg, vars);
case 'call':
if (!Object.hasOwn(FUNCTIONS, node.name)) throw new ReferenceError('Unknown function ' + node.name);
return FUNCTIONS[node.name](...node.args.map((arg) => evaluate(arg, vars)));
case 'binary': {
const a = evaluate(node.left, vars);
const b = evaluate(node.right, vars);
return { '+': a + b, '-': a - b, '*': a * b, '/': a / b, '^': a ** b }[node.op];
}
}
}
const calc = (text, vars) => evaluate(parse(text), vars);
console.log(calc('2 + 3 * 4'), calc('(2 + 3) * 4'), calc('10 - 4 - 3'), calc('2 ^ 3 ^ 2'));
console.log(calc('-(2 + 3)'), calc('2 * -3'), calc('-2 ^ 2'), calc('2 ^ -1'));
console.log(calc('max(1, x * 2, 3) + sqrt(16)', { x: 5 }));
console.log(JSON.stringify(parse('1 + 2 * 3')));
for (const bad of ['2 +', '(1 + 2', '2 $ 3', 'foo + 1', 'eval(1)', '1 2']) {
try {
calc(bad);
} catch (error) {
console.log(JSON.stringify(bad), '->', error.name + ': ' + error.message);
}
}
Run with Node.js v24.22.1 as js-110.js; two runs gave identical output.
Output:
14 20 3 512
-5 -6 -4 0.5
14
{"type":"binary","op":"+","left":{"type":"num","value":1},"right":{"type":"binary","op":"*","left":{"type":"num","value":2},"right":{"type":"num","value":3}}}
"2 +" -> SyntaxError: Unexpected end of input
"(1 + 2" -> SyntaxError: Expected ) but found end of input
"2 $ 3" -> SyntaxError: Unexpected character "$" at 2
"foo + 1" -> ReferenceError: Unknown variable foo
"eval(1)" -> ReferenceError: Unknown function eval
"1 2" -> SyntaxError: Unexpected num at 2
Key points
Three steps: tokenize, parse to an AST, evaluate; eval is unsafe for untrusted input.
One parsing function per precedence level; loops give left associativity.
Exponent is right associative; unary minus sits between multiplication and power.
Evaluate with an allow list of functions and a variables object.
Report errors with positions and test unary minus, nesting, and missing parentheses.
Common mistakes
Using eval or new Function on user input.
Making all operators one precedence level and ignoring the grammar.
Parsing left associative operators with recursion and getting the wrong grouping.
Looking up function names on a plain object without hasOwn, which exposes inherited properties.
Follow-ups
How would the Pratt parsing technique replace the precedence functions?
How would you add comparison operators and a ternary operator?
How would you report line and column numbers for errors?
Tips
Write the grammar first, lowest precedence at the top.
Say that loops give left associativity and right recursion gives exponent associativity.
Always mention why eval is not acceptable.
111.javascript-0111Easyfresher
How do you check whether two strings are anagrams, and how do you group a list of words by anagram?
Two strings are anagrams when they have the same letters with the same counts. Either sort the letters of both and compare, which is simple and takes O(n log n), or count letters in a Map or array, which takes O(n). To group words, use the sorted letters (or a count signature) as a key in a Map.
Full answer
An anagram uses exactly the same characters in a different order, such as "listen" and "silent". Start by asking the rules: ignore case and spaces or not, and which characters are allowed. A common choice is to lowercase the text and remove everything that is not a letter or digit.
Approach 1, sort: [...text].sort().join('') gives a canonical form. Two strings are anagrams when the canonical forms are equal. It is short and easy to read. The cost is O(n log n) for the sort.
Approach 2, count: build a count of each character for the first string, subtract for the second, and check that every count is zero. A quick length check first rejects most non-matches. The cost is O(n) time and O(k) space, where k is the number of different characters. For only lowercase a to z, a fixed array of 26 numbers works and is fast.
Grouping: words that are anagrams share the same canonical form, so use it as a key. Loop over the words, compute the key, and push the word into map.get(key). The result is [...map.values()]. This is O(n * k log k) for n words of length k with the sort key. For very long words, a count signature, such as the counts joined into a string, avoids the sort.
Unicode note: [...text] iterates by code point, which is better than splitting by code unit. Accented letters can have two forms, so call normalize('NFC') first if the input can contain them.
javascript
const clean = (text) => text.toLowerCase().normalize('NFC').replace(/[^\p{L}\p{N}]/gu, '');
function isAnagramSort(a, b) {
return [...clean(a)].sort().join('') === [...clean(b)].sort().join('');
}
function isAnagramCount(a, b) {
const x = [...clean(a)];
const y = [...clean(b)];
if (x.length !== y.length) return false;
const counts = new Map();
for (const ch of x) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const ch of y) {
const left = counts.get(ch);
if (!left) return false;
counts.set(ch, left - 1);
}
return true;
}
function groupAnagrams(words) {
const groups = new Map();
for (const word of words) {
const key = [...clean(word)].sort().join('');
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(word);
}
return [...groups.values()];
}
console.log(isAnagramSort('Listen', 'Silent'), isAnagramCount('Listen', 'Silent'));
console.log(isAnagramSort('Dormitory', 'Dirty room'), isAnagramCount('Dormitory', 'Dirty room'));
console.log(isAnagramSort('aab', 'abb'), isAnagramCount('aab', 'abb'));
console.log(isAnagramSort('', ''), isAnagramCount('abc', 'abcd'));
console.log(groupAnagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']));
console.log(isAnagramCount('caf\u00e9', 'cafe\u0301'));
Run with Node.js v24.22.1 as js-111.js; two runs gave identical output.
Output:
true true
true true
false false
true false
[ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ]
true
Key points
Anagrams have the same characters with the same counts; clarify case and spaces first.
Sort both and compare: simple, O(n log n).
Count characters with a Map or a 26-slot array: O(n) time.
Group by using the canonical form as a Map key.
Use code point iteration and normalize for Unicode text.
Common mistakes
Forgetting to ignore case or spaces when the question expects it.
Comparing only lengths or only the set of characters, so "aab" and "abb" pass.
Sorting with split('') and breaking surrogate pairs in emoji or rare characters.
Using an object as a counter for arbitrary keys without thinking about inherited names.
Follow-ups
What is the time complexity of each approach, and when is the count version better?
How would you find all anagram positions of a word inside a longer text?
How would you build the group key without sorting?
Tips
Ask about case, spaces, and character set before coding.
Offer sort first, then the O(n) count version as the improvement.
Show grouping with a Map keyed by the canonical form.
112.javascript-0112Easyfresher
How do you check whether a string or a number is a palindrome, and how would you find the longest palindromic substring?
Normalize the text, then compare characters from both ends moving inwards with two pointers, which is O(n) time and O(1) extra space, or compare it with its reverse. For numbers, reverse the digits arithmetically. For the longest palindromic substring, expand around each center, which is O(n squared).
Full answer
A palindrome reads the same forwards and backwards. First clarify the rules. Do case, spaces, and punctuation count? A common version ignores them: "A man, a plan, a canal: Panama" is a palindrome.
Simple version: normalize (lowercase, keep only letters and digits), then compare with the reversed text: clean === [...clean].reverse().join(''). It is easy to read and uses extra memory.
Two pointer version: set left = 0 and right = length - 1, compare, and move inwards until they meet. It stops early on the first mismatch and needs no extra string. If you must skip punctuation without a separate cleaning step, move each pointer past characters that are not letters or digits.
Numbers: a negative number is not a palindrome because of the sign. A fast way avoids strings: reverse the number with reversed = reversed * 10 + n % 10 and compare. The string approach String(n) === [...String(n)].reverse().join('') is acceptable in an interview if you say so.
Longest palindromic substring: every palindrome has a center, either one character (odd length) or the gap between two characters (even length). For each of the 2n - 1 centers, expand outwards while the characters match, and remember the longest. The time is O(n squared), which is acceptable for typical inputs. Manacher's algorithm gets O(n), and is rarely expected.
Unicode: reversing by code unit breaks emoji and accented letters. Use [...text] for code points, and normalize('NFC'), and mention grapheme clusters (Intl.Segmenter) when asked about perfect handling.
javascript
const normalize = (text) => text.toLowerCase().replace(/[^\p{L}\p{N}]/gu, '');
function isPalindrome(text) {
const chars = [...normalize(text)];
for (let left = 0, right = chars.length - 1; left < right; left++, right--) {
if (chars[left] !== chars[right]) return false;
}
return true;
}
function isPalindromeNumber(n) {
if (n < 0 || !Number.isInteger(n)) return false;
let reversed = 0;
for (let rest = n; rest > 0; rest = Math.floor(rest / 10)) reversed = reversed * 10 + (rest % 10);
return reversed === n;
}
function longestPalindrome(text) {
let best = '';
const expand = (left, right) => {
while (left >= 0 && right < text.length && text[left] === text[right]) {
left--;
right++;
}
return text.slice(left + 1, right);
};
for (let center = 0; center < text.length; center++) {
for (const candidate of [expand(center, center), expand(center, center + 1)]) {
if (candidate.length > best.length) best = candidate;
}
}
return best;
}
console.log(isPalindrome('A man, a plan, a canal: Panama'), isPalindrome('race a car'), isPalindrome(''));
console.log(isPalindromeNumber(12321), isPalindromeNumber(123), isPalindromeNumber(-121), isPalindromeNumber(10));
console.log(longestPalindrome('babad'), longestPalindrome('cbbd'), longestPalindrome('a'), JSON.stringify(longestPalindrome('')));
console.log([...'ab\u{1F600}'].reverse().join('') === '\u{1F600}ba', 'ab\u{1F600}'.split('').reverse().join('') === '\u{1F600}ba');
Run with Node.js v24.22.1 as js-112.js; two runs gave identical output.
Output:
true false true
true false false false
bab bb a ""
true false
Key points
Clarify whether case, spaces, and punctuation are ignored, then normalize.
Two pointers from both ends: O(n) time, O(1) extra space, stops at the first mismatch.
Numbers: negatives are not palindromes; reverse digits with arithmetic.
Longest palindromic substring: expand around 2n minus 1 centers, O(n squared).
Use code point iteration for Unicode text.
Common mistakes
Not normalizing case and punctuation when the problem expects it.
Reversing with split('') and breaking emoji.
Treating a negative number such as -121 as a palindrome.
Checking only the first and last character.
Follow-ups
How would you check palindromes without creating a new string?
What is the time complexity of expand around center, and what does Manacher's algorithm improve?
How would you check whether any permutation of a string is a palindrome?
Tips
Ask about case and punctuation first.
Present two pointers as the answer that avoids extra memory.
Mention that palindromes have odd and even centers.
113.javascript-0113Mediummid
How do you find the length of the longest substring without repeating characters in O(n) time?
Use a sliding window with two pointers and a Map from each character to its last index. Move the right pointer one step at a time, and when the character was seen inside the current window, move the left pointer just past its previous position. Track the longest window, which gives O(n) time and O(k) space.
Full answer
The brute force approach checks every substring, which is O(n cubed) with a naive uniqueness check and O(n squared) at best. A sliding window does it in one pass.
Idea: keep a window [left, right] that never contains a repeated character. Move right forward. If the new character appeared before at index last and that index is inside the window (last >= left), a repeat would occur, so set left = last + 1. Record the current character's index in a Map. After each step, the window length is right - left + 1, and the answer is the maximum of those lengths.
Why it is O(n): right visits every position once, and left only moves forward, never back. Each map operation is O(1) on average. Space is O(k), where k is the size of the alphabet or the number of different characters in the window.
The check last >= left is the subtle part. The map may hold an old index that is already outside the window. Without that check, left could move backward and give wrong answers, for example on "abba": when the second a is read, its last index 0 is smaller than left (which moved to 2 after the second b), so it must be ignored.
Variations: return the substring itself (store the start index of the best window), or limit to at most k distinct characters (use a count Map and shrink the window while there are too many keys). The same window pattern solves many "longest or shortest range with a condition" problems.
Unicode: iterating by index uses UTF-16 code units, so for emoji use [...text].
javascript
function longestUnique(text) {
const lastSeen = new Map();
let left = 0;
let best = { length: 0, start: 0 };
const chars = [...text];
chars.forEach((ch, right) => {
if (lastSeen.has(ch) && lastSeen.get(ch) >= left) left = lastSeen.get(ch) + 1;
lastSeen.set(ch, right);
if (right - left + 1 > best.length) best = { length: right - left + 1, start: left };
});
return { length: best.length, text: chars.slice(best.start, best.start + best.length).join('') };
}
function longestAtMostKDistinct(text, k) {
const counts = new Map();
let left = 0;
let best = 0;
for (let right = 0; right < text.length; right++) {
counts.set(text[right], (counts.get(text[right]) ?? 0) + 1);
while (counts.size > k) {
const ch = text[left++];
counts.set(ch, counts.get(ch) - 1);
if (counts.get(ch) === 0) counts.delete(ch);
}
best = Math.max(best, right - left + 1);
}
return best;
}
for (const input of ['abcabcbb', 'bbbbb', 'pwwkew', 'abba', '', 'dvdf']) {
console.log(JSON.stringify(input), longestUnique(input));
}
console.log(longestAtMostKDistinct('eceba', 2), longestAtMostKDistinct('aaaa', 1), longestAtMostKDistinct('abc', 0));
Sliding window with left and right pointers, plus a Map of last seen indexes.
On a repeat inside the window, move left to last index plus one.
Always check that the last index is at least left; "abba" shows why.
O(n) time because both pointers only move forward; O(k) space.
The pattern extends to at most k distinct characters and similar window problems.
Common mistakes
Moving left back to an old index because the left check is missing.
Resetting the whole window on a repeat, which makes the solution O(n squared).
Confusing substring (contiguous) with subsequence.
Returning the start index of the window as its length.
Follow-ups
How would you return the substring and not only its length?
How does the solution change for at most k distinct characters?
What changes if the input is a very long stream you cannot index into?
Tips
Draw the window on "abba" and show why the left check is needed.
State why the pointers give O(n).
Name the pattern: sliding window with a hash map.
114.javascript-0114Easyfresher
How do you solve two-sum in O(n) time, and what other problems use the same hashing idea?
Walk the array once and keep a Map from each value you have seen to its index. For each number, check whether target minus the number is already in the Map, and if so return both indexes. This turns an O(n squared) search into O(n) time with O(n) space, and the same idea finds duplicates, counts, and subarrays with a given sum.
Full answer
Two-sum asks for the indexes of two numbers in an array that add up to a target. The brute force version tries every pair, which is O(n squared). A hash lookup replaces the inner loop.
Algorithm: create an empty Map named seen. For each index i with value n, compute need = target - n. If seen has need, return [seen.get(need), i]. Otherwise store seen.set(n, i). Because you check before you store, an element is never paired with itself, and duplicates work: for [3, 3] with target 6, the second 3 finds the first. Time is O(n), space is O(n).
If the array is sorted, two pointers also work in O(1) space, but sorting an unsorted array first loses the original indexes.
Questions to ask: is there always exactly one answer, can the same element be used twice, are values negative or fractional, and what to return when there is no answer (usually null or an empty array).
The same idea, remembering what you have seen, solves many problems:
Contains duplicate: a Set and an early return.
First non-repeating character: count with a Map, then scan.
Subarray sum equals k: store prefix sums and how often each occurred.
Most frequent element: count in a Map.
Intersection of two arrays: put one in a Set and filter the other.
Choose Map and Set over plain objects for these, because keys of any type work and there are no inherited property surprises such as constructor. Note that Map keys use SameValueZero, so NaN matches NaN.
javascript
function twoSum(numbers, target) {
const seen = new Map();
for (let i = 0; i < numbers.length; i++) {
const need = target - numbers[i];
if (seen.has(need)) return [seen.get(need), i];
seen.set(numbers[i], i);
}
return null;
}
const hasDuplicate = (items) => new Set(items).size !== items.length;
function firstUniqueChar(text) {
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const [index, ch] of [...text].entries()) if (counts.get(ch) === 1) return index;
return -1;
}
function subarraySumCount(numbers, k) {
const prefixCounts = new Map([[0, 1]]);
let sum = 0;
let count = 0;
for (const n of numbers) {
sum += n;
count += prefixCounts.get(sum - k) ?? 0;
prefixCounts.set(sum, (prefixCounts.get(sum) ?? 0) + 1);
}
return count;
}
const intersection = (a, b) => {
const set = new Set(a);
return [...new Set(b.filter((x) => set.has(x)))];
};
console.log(twoSum([2, 7, 11, 15], 9), twoSum([3, 2, 4], 6), twoSum([3, 3], 6), twoSum([1, 2], 10));
console.log(hasDuplicate([1, 2, 3, 1]), hasDuplicate([1, 2, 3]));
console.log(firstUniqueChar('leetcode'), firstUniqueChar('aabb'));
console.log(subarraySumCount([1, 1, 1], 2), subarraySumCount([1, 2, 3], 3), subarraySumCount([1, -1, 0], 0));
console.log(intersection([1, 2, 2, 1], [2, 2, 3]));
Run with Node.js v24.22.1 as js-114.js; two runs gave identical output.
Output:
[ 0, 1 ] [ 1, 2 ] [ 0, 1 ] null
true false
0 -1
2 2 3
[ 2 ]
Key points
Check target minus current in a Map of seen values, then store the current value.
Check before storing so an element is not paired with itself; duplicates still work.
O(n) time and O(n) space, against O(n squared) for pairs.
Clarify uniqueness, reuse of elements, and the no-answer return value.
Same pattern: duplicates, counts, prefix sums, intersections; prefer Map and Set to plain objects.
Common mistakes
Storing the current value before checking, which pairs an element with itself.
Using a nested loop and accepting O(n squared) without mentioning the hash version.
Sorting first and losing the original indexes.
Using plain objects as hash maps and getting inherited keys such as constructor.
Follow-ups
How would you solve two-sum when the array is sorted and you want O(1) space?
How would you return all pairs and avoid duplicate pairs?
How does the prefix sum idea find subarrays that sum to k?
Tips
Describe the brute force, then the hash version, then the cost trade-off.
Say check-then-store and why it matters.
Mention that Map and Set work for any key type.
115.javascript-0115Mediummid
What is the two-pointer technique, and how do you use it for sorted pairs, in-place deduplication, and the container with most water?
Two pointers means walking an array with two indexes, either from both ends inwards or both from the front at different speeds, so a nested loop becomes a single O(n) pass. It works when moving a pointer has a predictable effect, such as on a sorted array. Typical uses are pair sums, removing duplicates in place, partitioning, and the container with most water.
Full answer
Many array problems look like they need two nested loops. If the data has an order, or the answer depends only on a relation between two positions, two indexes can replace the second loop.
Pattern 1, opposite ends: start left = 0 and right = n - 1 on a sorted array. For a target sum, compute sum = a[left] + a[right]. If it is too small, move left up to get a larger value. If it is too large, move right down. Each step discards at least one position, so the loop is O(n) and uses O(1) extra space. It only works because the array is sorted.
Pattern 2, same direction (slow and fast): write marks where the next kept value goes, and read scans ahead. For removing duplicates from a sorted array in place, copy a[read] to a[write] only when it differs from the last kept value. The first write items are the result, and the function returns the new length. Moving zeroes to the end and removing a value in place use the same shape.
Pattern 3, greedy contraction: for the container with most water, the area is min(height[left], height[right]) * (right - left). Moving the taller side can never help, because the width shrinks and the height is limited by the shorter side. So always move the pointer at the shorter line. This is O(n), compared with O(n squared) for all pairs.
Also useful: the fast and slow pointer idea for finding the middle of a linked list or detecting a cycle, and partitioning for the Dutch national flag problem.
When explaining, state the invariant: what is true about the part of the array already processed.
javascript
function pairWithSum(sorted, target) {
let left = 0;
let right = sorted.length - 1;
while (left < right) {
const sum = sorted[left] + sorted[right];
if (sum === target) return [left, right];
if (sum < target) left++;
else right--;
}
return null;
}
function dedupeSortedInPlace(a) {
if (a.length === 0) return 0;
let write = 1;
for (let read = 1; read < a.length; read++) {
if (a[read] !== a[write - 1]) a[write++] = a[read];
}
return write;
}
function moveZeroesToEnd(a) {
let write = 0;
for (let read = 0; read < a.length; read++) {
if (a[read] !== 0) {
[a[write], a[read]] = [a[read], a[write]];
write++;
}
}
return a;
}
function maxArea(heights) {
let left = 0;
let right = heights.length - 1;
let best = 0;
while (left < right) {
best = Math.max(best, Math.min(heights[left], heights[right]) * (right - left));
if (heights[left] < heights[right]) left++;
else right--;
}
return best;
}
console.log(pairWithSum([1, 2, 4, 7, 11, 15], 15), pairWithSum([1, 2, 3], 10));
const numbers = [1, 1, 2, 2, 2, 3, 5, 5];
const length = dedupeSortedInPlace(numbers);
console.log(length, numbers.slice(0, length), numbers);
console.log(moveZeroesToEnd([0, 1, 0, 3, 12]));
console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]), maxArea([1, 1]));
Run with Node.js v24.22.1 as js-115.js; two runs gave identical output.
Output:
[ 2, 4 ] null
4 [ 1, 2, 3, 5 ] [
1, 2, 3, 5,
2, 3, 5, 5
]
[ 1, 3, 12, 0, 0 ]
49 1
Key points
Replace a nested loop with two indexes that move in a predictable way, giving O(n).
Opposite ends on a sorted array: move left when the sum is too small, right when too large.
Same direction: write marks the kept prefix, read scans; used for in-place dedupe and removals.
Container with most water: always move the pointer at the shorter line.
State the invariant and note that sorting is often the precondition.
Common mistakes
Using the opposite-ends pattern on an unsorted array.
Forgetting that in-place deduplication leaves stale values after the returned length.
Moving the taller line in the container problem.
Using splice inside the loop, which turns an O(n) task into O(n squared).
Follow-ups
How would you solve three-sum with two pointers?
How do slow and fast pointers detect a cycle in a linked list?
How would you prove that moving the shorter line is safe in the container problem?
Tips
Name the pattern and say what makes it valid, usually sorted data.
Describe the invariant before the code.
Avoid splice in loops; write and read indexes are cheaper.
116.javascript-0116Hardsenior
How do you find the maximum of every window of size k in an array in O(n) time?
Keep a deque of indexes whose values are in decreasing order. For each new element, drop indexes from the back while their values are not larger than the new one, push the new index, drop the front if it left the window, and read the maximum from the front. Each index enters and leaves once, so the total is O(n), compared with O(n times k) for the naive approach.
Full answer
The naive solution scans each window of k elements for the maximum: O(n times k). A heap gives O(n log n) but needs lazy deletion of items that leave the window. A monotonic deque does it in O(n).
Idea: maintain a double-ended queue of indexes such that the values at those indexes are strictly decreasing from front to back. The front always holds the index of the current maximum.
For each index i:
Remove from the back while a[back] <= a[i]. Those elements can never be the maximum of any window that includes i, because a[i] is at least as large and stays in the window longer.
Push i at the back.
If the front index is i - k or older, remove it, because it left the window.
Once i >= k - 1, the first full window is complete, so record a[front].
Why it is O(n): every index is pushed once and removed at most once, from the back or the front. So the total work over all steps is at most 2n operations.
In JavaScript there is no built-in deque. Array.prototype.shift is O(n) in the worst case, so a long input could be slow. Use an index pointer (head) into an array and advance it instead of shifting, as the snippet does. Or implement a small ring buffer.
The same monotonic queue pattern solves the shortest subarray with a given sum and constrained dynamic programming problems. A monotonic stack, which is the same idea with one end, solves "next greater element" and "largest rectangle in a histogram".
Edge cases: k equal to 1, k equal to the array length, k larger than the array, and equal values, which is why the comparison uses <=.
javascript
function slidingWindowMax(a, k) {
if (!Number.isInteger(k) || k < 1 || k > a.length) return [];
const deque = []; // indexes, values decreasing
let head = 0; // front of the deque, advanced instead of calling shift
const result = [];
for (let i = 0; i < a.length; i++) {
while (deque.length > head && a[deque[deque.length - 1]] <= a[i]) deque.pop();
deque.push(i);
if (deque[head] <= i - k) head++;
if (i >= k - 1) result.push(a[deque[head]]);
}
return result;
}
function naive(a, k) {
const out = [];
for (let i = 0; i + k <= a.length; i++) out.push(Math.max(...a.slice(i, i + k)));
return out;
}
console.log(slidingWindowMax([1, 3, -1, -3, 5, 3, 6, 7], 3));
console.log(slidingWindowMax([9, 8, 7, 6], 2), slidingWindowMax([1, 2, 3, 4], 4), slidingWindowMax([5], 1));
console.log(slidingWindowMax([2, 2, 2], 2), slidingWindowMax([1, 2], 3));
// compare with the naive version on pseudo-random data (seeded generator, same every run)
let seed = 12345;
const random = () => ((seed = (seed * 1664525 + 1013904223) % 4294967296) / 4294967296);
let allMatch = true;
for (let round = 0; round < 200; round++) {
const data = Array.from({ length: 1 + Math.floor(random() * 30) }, () => Math.floor(random() * 20) - 10);
const k = 1 + Math.floor(random() * data.length);
if (JSON.stringify(slidingWindowMax(data, k)) !== JSON.stringify(naive(data, k))) allMatch = false;
}
console.log('matches the naive version on 200 random cases:', allMatch);
Run with Node.js v24.22.1 as js-116.js; two runs gave identical output.
Output:
[ 3, 3, 5, 5, 6, 7 ]
[ 9, 8, 7 ] [ 4 ] [ 5 ]
[ 2, 2 ] []
matches the naive version on 200 random cases: true
Key points
Keep a deque of indexes with decreasing values; the front is the window maximum.
Pop from the back while values are not larger than the new value; pop the front when its index leaves the window.
Each index enters and leaves once, so the time is O(n).
Array shift is slow; use a head pointer or a ring buffer.
The pattern also gives next greater element and histogram solutions with a monotonic stack.
Common mistakes
Using strict less-than when popping from the back, which keeps equal values and wastes work.
Storing values and not indexes, so there is no way to tell when an element left the window.
Calling shift in a loop on large inputs.
Recording results before the first full window is complete.
Follow-ups
How does a monotonic stack solve next greater element?
How would you solve this with a heap, and what is the cost?
How would you implement an O(1) deque in JavaScript?
Tips
Explain why dropping smaller elements from the back is safe.
State the amortized argument: each index enters and leaves once.
Mention that Array shift is a performance trap.
117.javascript-0117Mediummid
How would you implement a publish and subscribe system with topics, wildcards, and unsubscribe?
A broker keeps a Map from topic patterns to sets of handlers. Publishing a topic finds every pattern that matches it, including wildcards such as "user.*" and "#", and calls each handler. Subscribe returns an unsubscribe function, and one failing handler must not stop the others. Unlike the observer pattern, publishers and subscribers do not know each other.
Full answer
Publish and subscribe (pub/sub) decouples senders from receivers through a broker. A publisher sends a message to a topic name, such as order.created. A subscriber registers interest in a topic. Neither side holds a reference to the other. This differs from the plain observer pattern, where the subject keeps its own list of observers and calls them directly. It also differs from EventEmitter, which is a similar tool but usually has no wildcard matching.
Design:
Store patterns: Map<string, Set<handler>>. A Set prevents the same handler being added twice for one pattern.
subscribe(pattern, handler) adds the handler and returns a function that removes it. Returning the remover is more convenient than a separate off and works with anonymous handlers. Delete the empty Set so the Map does not grow without limit.
Wildcards: topics are segments separated by dots. * matches exactly one segment, and # matches zero or more segments, as in AMQP and MQTT style brokers. Convert the pattern to a regular expression or compare segment by segment. Escape the dots.
publish(topic, payload) loops over all patterns, calls the handlers of each match, and returns the number of handlers called. Take a copy of the handler set before calling, because handlers can unsubscribe themselves while running.
Error isolation: wrap each handler call in try and catch, and report errors, so one bad subscriber does not break the rest.
once(pattern, handler) is a subscribe that unsubscribes itself on the first call.
Choices to mention: synchronous or asynchronous delivery (asynchronous delivery with queueMicrotask avoids re-entrancy surprises), retained messages for late subscribers, and ordering guarantees. Across processes, use a real broker such as Redis or MQTT.
javascript
class PubSub {
#patterns = new Map();
subscribe(pattern, handler) {
if (!this.#patterns.has(pattern)) this.#patterns.set(pattern, new Set());
this.#patterns.get(pattern).add(handler);
return () => {
const handlers = this.#patterns.get(pattern);
if (!handlers) return;
handlers.delete(handler);
if (handlers.size === 0) this.#patterns.delete(pattern);
};
}
once(pattern, handler) {
const off = this.subscribe(pattern, (topic, payload) => {
off();
handler(topic, payload);
});
return off;
}
publish(topic, payload) {
let called = 0;
for (const [pattern, handlers] of this.#patterns) {
if (!PubSub.matches(pattern, topic)) continue;
for (const handler of [...handlers]) {
called++;
try {
handler(topic, payload);
} catch (error) {
console.log(`handler for "${pattern}" failed: ${error.message}`);
}
}
}
return called;
}
static matches(pattern, topic) {
const p = pattern.split('.');
const t = topic.split('.');
const walk = (i, j) => {
if (i === p.length) return j === t.length;
if (p[i] === '#') return walk(i + 1, j) || (j < t.length && walk(i, j + 1));
if (j === t.length) return false;
return (p[i] === '*' || p[i] === t[j]) && walk(i + 1, j + 1);
};
return walk(0, 0);
}
get patternCount() {
return this.#patterns.size;
}
}
const bus = new PubSub();
const seen = [];
const offExact = bus.subscribe('order.created', (topic, p) => seen.push(`exact ${p}`));
bus.subscribe('order.*', (topic, p) => seen.push(`star ${topic}`));
bus.subscribe('#', (topic) => seen.push(`all ${topic}`));
bus.subscribe('order.created', () => { throw new Error('bad subscriber'); });
bus.once('order.shipped', (topic) => seen.push('once ' + topic));
console.log('handlers called:', bus.publish('order.created', 'A1'));
console.log('handlers called:', bus.publish('order.shipped', 'A1'));
console.log('handlers called:', bus.publish('order.shipped', 'A2'));
console.log('handlers called:', bus.publish('order.items.added', 'A1'));
offExact();
console.log('after unsubscribe:', bus.publish('order.created', 'A3'));
console.log(seen);
console.log(['a.b', 'a.*', 'a.#', '#', '*', 'a.*.c'].map((p) => `${p}:${PubSub.matches(p, 'a.b')}`).join(' '));
console.log('patterns stored:', bus.patternCount);
Run with Node.js v24.22.1 as js-117.js; two runs gave identical output.
Output:
handler for "order.created" failed: bad subscriber
handlers called: 4
handlers called: 3
handlers called: 2
handlers called: 1
handler for "order.created" failed: bad subscriber
after unsubscribe: 3
[
'exact A1',
'star order.created',
'all order.created',
'star order.shipped',
'all order.shipped',
'once order.shipped',
'star order.shipped',
'all order.shipped',
'all order.items.added',
'star order.created',
'all order.created'
]
a.b:true a.*:true a.#:true #:true *:false a.*.c:false
patterns stored: 3
Key points
A broker with Map of patterns to Sets of handlers decouples publishers and subscribers.
subscribe returns an unsubscribe function; remove empty Sets.
Wildcards: star matches one segment, hash matches many; match by segments.
Copy the handlers before calling and isolate errors per handler.
Choose sync or async delivery; use a real broker across processes.
Common mistakes
Letting one failing handler stop delivery to the rest.
Iterating the live handler Set while handlers unsubscribe themselves.
Forgetting to remove empty entries, so unsubscribed topics leak memory.
Building wildcard regular expressions without escaping the dots.
Follow-ups
How is pub/sub different from the observer pattern and from EventEmitter?
How would you add retained messages for late subscribers?
How would you make delivery asynchronous without changing the order of messages?
Tips
Contrast pub/sub with observer: the broker removes direct references.
Return an unsubscribe function from subscribe.
State the wildcard rules clearly before coding them.
118.javascript-0118Mediummid
How do you convert a callback-based function to a promise (promisify) and a promise-based function back to a callback (callbackify)?
Promisify returns a function that wraps the call in a new Promise and passes a Node-style callback (error first) that rejects on an error and resolves with the result. Callbackify does the reverse: it calls the promise function and passes the outcome to a final callback. Keep this binding, handle functions with several results, and make sure a callback is never called twice.
Full answer
Node.js APIs use the error-first callback convention: fn(...args, (err, result) => {}). Modern code prefers promises, so conversion is a common task, and a good first coding question about promises.
promisify(fn) returns a new function. When it is called, it returns new Promise((resolve, reject) => ...) and calls fn with the original arguments plus a callback. The callback rejects with err when it is truthy, otherwise resolves with result. Details that matter:
Preserve this: return a regular function and call fn.apply(this, args), so methods like obj.read still work.
Callbacks that give several results, such as (err, a, b), cannot be expressed by one resolved value. Resolve with an array or an object, or use a custom symbol as Node does with util.promisify.custom.
If fn throws synchronously, the Promise constructor catches it and rejects, which is what you want.
Some APIs call the callback more than once. A Promise settles only once, so later calls are ignored. That is fine for one-shot calls and wrong for events.
callbackify(fn) goes the other way. It returns a function that takes the original arguments and a final callback. It calls fn(...args), then calls callback(null, value) on success or callback(error) on failure. Call the callback outside the promise chain, for example in queueMicrotask or process.nextTick, so an exception thrown by the callback is not swallowed by the promise and turned into a second callback call.
In real Node.js code, use util.promisify and util.callbackify, or the built-in promise APIs such as fs/promises, and use these hand-made versions to explain how they work. For browser callback APIs that do not use error-first style, write a custom wrapper.
javascript
function promisify(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn.call(this, ...args, (error, ...results) => {
if (error) reject(error);
else resolve(results.length > 1 ? results : results[0]);
});
});
};
}
function callbackify(fn) {
return function (...args) {
const callback = args.pop();
fn.apply(this, args).then(
(value) => queueMicrotask(() => callback(null, value)),
(error) => queueMicrotask(() => callback(error)),
);
};
}
// a callback style function that is async on purpose
function divide(a, b, callback) {
setTimeout(() => {
if (b === 0) callback(new Error('division by zero'));
else callback(null, a / b);
}, 5);
}
const counter = {
base: 100,
addAsync(n, callback) {
setTimeout(() => callback(null, this.base + n, 'extra'), 1);
},
};
async function main() {
const divideAsync = promisify(divide);
console.log(await divideAsync(10, 4));
try {
await divideAsync(1, 0);
} catch (error) {
console.log('rejected:', error.message);
}
counter.addPromise = promisify(counter.addAsync);
console.log('keeps this and many results:', await counter.addPromise(5));
const asyncSquare = async (n) => {
if (n < 0) throw new RangeError('negative');
return n * n;
};
const squareCb = callbackify(asyncSquare);
await new Promise((done) => {
squareCb(7, (error, value) => { console.log('callback result:', error, value); done(); });
});
await new Promise((done) => {
squareCb(-1, (error, value) => { console.log('callback error:', error.name, value); done(); });
});
const { promisify: nodePromisify } = require('node:util');
console.log('util.promisify gives the same answer:', await nodePromisify(divide)(9, 3));
}
main();
Run with Node.js v24.22.1 as js-118.js; two runs gave identical output.
Output:
2.5
rejected: division by zero
keeps this and many results: [ 105, 'extra' ]
callback result: null 49
callback error: RangeError undefined
util.promisify gives the same answer: 3
Key points
Promisify wraps the call in a new Promise and passes an error-first callback that rejects or resolves.
Preserve this with a regular function and apply; synchronous throws become rejections.
Several callback results need an array or object; a Promise settles only once.
Callbackify calls the callback outside the promise chain to avoid double calls.
Prefer util.promisify, util.callbackify, and fs/promises in real code.
Common mistakes
Forgetting to bind this and breaking methods.
Resolving with only the first value when the callback passes several results.
Calling the final callback inside the then handler, so an exception in the callback triggers a second call through the catch handler.
Promisifying APIs that call the callback many times, such as event listeners.
Follow-ups
What does util.promisify.custom do?
Why does fs/promises exist, and when would you still use callbacks?
How would you promisify an API where the callback is not the last argument?
Tips
Show the error-first convention and the Promise wrapper in a few lines.
Mention this binding and multiple results.
Say that real code should use util.promisify or fs/promises.
119.javascript-0119Easyfresher
What are the ways to remove duplicates from an array, including an array of objects by key?
For primitives, the shortest way is [...new Set(array)], which keeps the first occurrence and is O(n). The filter with indexOf approach works but is O(n squared). For objects, Set compares by reference, so use a Map or a Set of keys to keep the first object for each key. Decide which occurrence to keep and how to compare values.
Full answer
The fastest and clearest way for primitive values is a Set: [...new Set(items)], or Array.from(new Set(items)). A Set keeps only unique values, and keeps the order of first insertion. It uses SameValueZero equality, so NaN equals NaN (unlike ===), and +0 and -0 are the same value.
The older approach is items.filter((x, i) => items.indexOf(x) === i). It also keeps the first occurrence, but indexOf scans the array each time, so it is O(n squared). It also never finds NaN, because indexOf uses strict equality, so every NaN is dropped.
For an array of objects, a Set does not work, because two objects with the same content are different references. Choose the key that defines "same", for example id, and track the keys you have seen: loop over the items, and keep an item if its key is not in the seen Set. To keep the last occurrence instead, build a Map from key to item and let later items overwrite earlier ones: [...new Map(items.map((x) => [x.id, x])).values()]. Note that this keeps the position of the first insertion of the key, but the value of the last item.
Comparing whole objects by content needs a canonical key such as JSON.stringify with sorted keys, or a deep equal function. JSON.stringify depends on property order and cannot represent some values, so use it only for simple data.
State what is kept (first or last) and whether the original array may change. These methods create a new array and do not mutate the input.
[...new Set(items)] is the shortest and fastest for primitives; it keeps the first occurrence.
Set treats NaN as equal to NaN; indexOf cannot find NaN.
filter with indexOf is O(n squared).
For objects, track a key in a Set to keep the first, or use a Map to keep the last.
Content comparison needs a canonical key or a deep equal function.
Common mistakes
Using a Set on objects and expecting content comparison.
Using filter with indexOf on large arrays.
Expecting indexOf to handle NaN.
Not stating whether the first or the last duplicate should win.
Follow-ups
What is the difference between SameValueZero and strict equality?
How would you remove duplicates in place without creating a new array?
How would you deduplicate a very large stream without keeping all values in memory?
Tips
Start with the Set one-liner, then explain the objects case.
Mention first versus last occurrence.
Know that indexOf misses NaN.
120.javascript-0120Easyfresher
How do you compute Fibonacci numbers and factorials in JavaScript, and why is the naive recursive Fibonacci slow?
Naive recursive Fibonacci recomputes the same values and takes exponential time, O(2 to the n). Memoization or a simple loop brings it down to O(n), and a loop with two variables uses O(1) space. Numbers beyond 2 to the 53 minus 1 lose precision, so use BigInt for large results, and remember recursion depth limits.
Full answer
The Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, and each number is the sum of the previous two.
Naive recursion, fib(n) = fib(n - 1) + fib(n - 2), looks like the definition, but it calls itself twice and repeats the same subproblems. The number of calls grows exponentially, roughly 1.6 to the power of n. fib(40) already takes noticeable time, and fib(100) would never finish.
Better versions:
Memoization: store computed values in a Map or an array. Each value is computed once, so time is O(n), and space is O(n) for the cache and the call stack.
Iteration: keep two variables, a and b, and update them in a loop. Time is O(n) and space is O(1). This is the version to prefer in practice.
Fast doubling or matrix exponentiation gives O(log n) arithmetic steps, and is a good bonus answer.
Factorial, n! = n * (n - 1) * ... * 1, is naturally recursive, but a loop is just as clear and avoids stack overflow for large inputs. Define 0! = 1, and reject negative and non-integer inputs.
Number limits: JavaScript numbers are 64-bit floats and are exact only up to Number.MAX_SAFE_INTEGER (2 to the 53 minus 1). fib(79) is already beyond the safe range, and 171! overflows to Infinity. Use BigInt for exact large results, with the n suffix and BigInt(...) for conversion. Note that you cannot mix BigInt and Number in one expression.
For recursive solutions, mention the call stack limit, about ten thousand frames, and that JavaScript engines do not guarantee tail call optimization.
javascript
let naiveCalls = 0;
function fibNaive(n) {
naiveCalls++;
return n < 2 ? n : fibNaive(n - 1) + fibNaive(n - 2);
}
function fibMemo(n, memo = new Map()) {
if (n < 2) return n;
if (memo.has(n)) return memo.get(n);
const value = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
memo.set(n, value);
return value;
}
function fibLoop(n) {
let [a, b] = [0n, 1n];
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}
function factorial(n) {
if (!Number.isInteger(n) || n < 0) throw new RangeError('n must be a non-negative integer');
let result = 1n;
for (let i = 2n; i <= BigInt(n); i++) result *= i;
return result;
}
console.log([0, 1, 2, 3, 4, 5, 10, 20].map((n) => fibMemo(n)));
fibNaive(20);
console.log('naive calls for n = 20:', naiveCalls);
naiveCalls = 0;
fibNaive(25);
console.log('naive calls for n = 25:', naiveCalls);
console.log(fibLoop(90), fibLoop(300).toString().length + ' digits');
console.log('number version loses precision:', fibMemo(90), 'versus BigInt', fibLoop(90));
console.log(factorial(0), factorial(5), factorial(20), String(factorial(25)));
console.log('171! as a Number:', Number(factorial(171)), 'safe limit:', Number.MAX_SAFE_INTEGER);
try {
factorial(-1);
} catch (error) {
console.log(error.name);
}
Run with Node.js v24.22.1 as js-120.js; two runs gave identical output.
Output:
[
0, 1, 1, 2,
3, 5, 55, 6765
]
naive calls for n = 20: 21891
naive calls for n = 25: 242785
2880067194370816120n 63 digits
number version loses precision: 2880067194370816000 versus BigInt 2880067194370816120n
1n 120n 2432902008176640000n 15511210043330985984000000
171! as a Number: Infinity safe limit: 9007199254740991
RangeError
Key points
Naive recursive Fibonacci is exponential because it repeats subproblems.
Memoization gives O(n); a loop with two variables gives O(n) time and O(1) space.
Fast doubling gives O(log n) steps.
Numbers lose exactness past 2 to the 53 minus 1; use BigInt for large results and do not mix types.
Recursion depth is limited and tail calls are not guaranteed, so prefer loops for large inputs.
Common mistakes
Using naive recursion for large n.
Mixing BigInt and Number in one expression and getting a TypeError.
Forgetting that 0! is 1 and that negative input must be rejected.
Trusting results beyond Number.MAX_SAFE_INTEGER.
Follow-ups
How does fast doubling compute Fibonacci in O(log n)?
What is the call stack limit, and what happens when recursive factorial exceeds it?
Why do JavaScript engines not guarantee tail call optimization?
Tips
Show the call count to prove why the naive version is slow.
Present the loop as the practical answer and memoization as the teaching answer.