Big O and Problem Solving for JavaScript Interviews
Introduction
Lesson 1 of chapter 9 applies Big O and a problem-solving method to JavaScript coding interviews. These original OnLevelUp exercises cover the communication, pseudocode, data structure, and algorithm skills taught in the ninth course of the Meta Front-End Developer pathway. Coding Interview Preparation (opens in a new tab)
Everything you built so far (components, hooks, forms, tests) showed that you can write code. A technical interview checks something slightly different: whether you can understand a problem, talk through a plan, write correct code under time pressure, and reason about its cost. This lesson gives you a repeatable method for the first three and the vocabulary for the fourth: time and space complexity.
Learning objectives
By the end of this lesson you can:
- Restate a problem in your own words and ask clarifying questions about inputs, outputs, and constraints.
- Work through concrete examples, including edge cases, before writing code.
- Write pseudocode that separates the plan from language syntax.
- Describe a brute-force solution first, then improve it deliberately.
- Estimate time and space complexity using Big O notation for loops, nested loops, and halving strategies.
- Test a solution by tracing it by hand.
- Explain your reasoning aloud in a structured, calm way.
1. A repeatable method
Use this five-step sequence to make your reasoning visible. The suggested times are for practice.
| Step | What you do | Typical time |
|---|---|---|
| 1. Understand | Restate the problem, ask questions, confirm inputs and outputs | 2–3 min |
| 2. Examples | Build 2–3 small examples plus edge cases | 2–3 min |
| 3. Plan | Describe brute force, then a better idea, in pseudocode | 3–5 min |
| 4. Code | Translate the plan into JavaScript, naming things clearly | 10–15 min |
| 5. Verify | Trace an example by hand, discuss complexity, mention tests | 3–5 min |
Confirm the requirements and outline the plan before coding. Adjust the timing to the interview and the problem.
Step 1: understand and clarify
Imagine the prompt: "Given a list of workshop bookings, return the names of customers who booked more than once."
Good clarifying questions:
- What is the shape of a booking? An object
{ customer, workshopId }? Iscustomera string? - Is the comparison case-sensitive? Is
"Sam"the same as"sam"? - Can the list be empty? Can it be very large (thousands, millions of items)?
- Should the result be unique names, in any order, or in order of first appearance?
- Should the input be modified, or must it stay unchanged?
Answer these questions in the example by assuming a dense array of objects with string customer values, exact case-sensitive matching, output ordered by the second occurrence, and no input mutation. The output order affects the algorithm, so test a case where the first name in the input repeats later than another name.
Step 2: examples and edge cases
Write examples before code:
Input: [{customer:"Sam"}, {customer:"Ana"}, {customer:"Sam"}, {customer:"Lee"}, {customer:"Ana"}, {customer:"Sam"}]
Output: ["Sam", "Ana"] // unique, order of first repeat
Input: [] -> []
Input: [{customer:"Sam"}] -> [] // one booking is not a repeat
Input: [{customer:"Sam"}, {customer:"sam"}] -> [] // case-sensitive matchingTypical edge cases to check every time:
- Empty input.
- A single element.
- All elements identical.
- Already sorted or reverse-sorted data.
- Duplicates, negative numbers, zero, very large values.
- Invalid input (
null, wrong type), if the interviewer cares.
Step 3: plan with pseudocode
Pseudocode is a plain-language description of the steps, without exact syntax. It keeps you from getting lost in semicolons and lets the interviewer correct the plan cheaply.
function repeatedCustomers(bookings):
counts = empty map
result = empty list
for each booking in bookings:
add 1 to counts[booking.customer]
if counts[booking.customer] is exactly 2:
append booking.customer to result
return resultNotice the detail "exactly 2": it prevents adding a name a third time. Writing the plan exposed that subtle point before any JavaScript existed.
Step 4: code
function repeatedCustomers(bookings) {
const counts = new Map();
const result = [];
for (const { customer } of bookings) {
const next = (counts.get(customer) ?? 0) + 1;
counts.set(customer, next);
if (next === 2) {
result.push(customer);
}
}
return result;
}The first example returns ["Sam", "Ana"]. Sam reaches two bookings at the third item, and Ana at the fifth. With names Sam, Ana, Ana, Sam, the answer is ["Ana", "Sam"] because Ana repeats first.
Step 5: verify
Trace with a small input and say each state out loud:
bookings: Sam, Ana, Sam
after Sam: counts {Sam:1} result []
after Ana: counts {Sam:1, Ana:1} result []
after Sam: counts {Sam:2, Ana:1} result ["Sam"]Then state the complexity (next sections) and name one or two additional tests.
2. Brute force first, then improve
A strong habit: describe the simplest correct solution first, even if slow. It proves you understand the problem and gives you a safe fallback.
For a direct comparison with the map solution, scan each prefix of the input and emit the name at its second occurrence.
function repeatedCustomersSlow(bookings) {
const result = [];
for (let i = 0; i < bookings.length; i++) {
const { customer } = bookings[i];
let earlier = 0;
for (let j = 0; j < i && earlier < 2; j++) {
if (bookings[j].customer === customer) earlier++;
}
if (earlier === 1) result.push(customer);
}
return result;
}With 10,000 distinct customers, the prefix scan does 10,000 × 9,999 / 2 = 49,995,000 comparisons, so its worst-case time is O(n²). It uses O(1) working space excluding the output. The Map version is expected O(n) time under the usual hash-table model and uses O(u) working space for u distinct customers.
3. Time complexity and Big O
Big O notation gives an asymptotic upper bound on growth as input size n increases. State the input size, cost model, and case being bounded. In these examples we count operations on fixed-size values or assume bounded key sizes. We use expected constant-time access and amortized insertion for the hash-table model. ECMAScript requires average sublinear access for Map and Set, which allows other implementations. ECMAScript keyed collections (opens in a new tab)
| Notation | Name | Typical example | Rough work for n = 1,000 |
|---|---|---|---|
| O(1) | Constant | Read a dense array slot or look up a key under the hash-table model | 1 |
| O(log n) | Logarithmic | Binary search on sorted data | about 10 |
| O(n) | Linear | One loop over the array | 1,000 |
| O(n log n) | Linearithmic | Efficient sorting (merge sort) | about 10,000 |
| O(n²) | Quadratic | Loop inside a loop over the same data | 1,000,000 |
| O(2ⁿ) | Exponential | Doing one constant-cost action per subset | astronomically large |
How to read the cost of code
- A single loop over
nitems with constant work inside: O(n). - Two sequential loops: O(n) + O(n) = O(2n), simplified to O(n).
- A loop nested in a loop, both over
n: O(n²). - A loop that halves the remaining range each time: O(log n).
- An n-step loop that scans or copies up to n elements on each iteration can take O(n²) time. Check the size of the searched array or copied range before multiplying costs.
A single visible loop can still make many comparisons. Revisit JavaScript array methods and immutable updates when identifying scans and copies in array methods.
// O(n²): includes() scans the result array each time
function uniqueSlow(items) {
const out = [];
for (const x of items) {
if (!out.includes(x)) out.push(x);
}
return out;
}
// Expected O(n) time under the hash-table model
function unique(items) {
return [...new Set(items)];
}Worst, average, and best case
Worst, average, and best case describe which inputs or probability model you are analyzing. Big O can bound any of them. An unsorted search uses O(n) time in the worst case when the target is last or absent, and O(1) time when it is first. Average-case reasoning requires an assumption about the input distribution.
Space complexity
For auxiliary space, count working memory beyond the input and state whether you exclude the returned output. Include the call stack for recursive functions.
repeatedCustomersstores aMapwith up toudistinct customers. Working space is O(u), and the result can also grow to O(u).- Reversing an array in place with two indices uses O(1) extra space.
- Creating a new array with
mapor the spread operator uses O(n) space. - Recursion uses stack space: a recursive function that goes
nlevels deep uses O(n) stack.
Often you trade time for space. The Map solution uses more memory to save time. Naming the trade-off explicitly is a mark of a strong answer.
4. Worked example: from slow to fast
Problem. A booking page has a sorted-by-time list of n workshop session start times (integer minutes since the start of a multi-day program). Return true if any two sessions start at exactly the same minute.
Step 1: clarify. Are times sorted? The statement says sorted by time. Can n be 0 or 1? Yes. Is the list large? Assume up to 100,000.
Step 2: examples.
[540, 600, 600, 660] -> true
[540, 600, 660] -> false
[] -> false
[540] -> falseStep 3: plan.
Option A (brute force): compare every pair. O(n²) time, O(1) space. Option B (Set): store seen values, stop when one repeats. Expected O(n) time under the hash-table model and O(n) space in the worst case. Option C (use the sorted property): duplicates in a sorted list are adjacent, so compare each element with its neighbor. O(n) time, O(1) space.
Option C is best because the sorted guarantee removes the need for extra memory.
Step 4: code.
function hasDuplicateStart(times) {
for (let i = 1; i < times.length; i++) {
if (times[i] === times[i - 1]) {
return true;
}
}
return false;
}Step 5: verify. Trace [540, 600, 600, 660]: i=1 compares 600 and 540, no; i=2 compares 600 and 600, return true. For [] and [540] the loop never runs, so the result is false, as required.
Why the other choices are weaker. A can do almost 5 billion comparisons for 100,000 distinct start times. The adjacent scan takes at most 99,999 comparisons on that sorted input. B is correct and fast but wastes memory because the input already carries the structure we need. For unsorted data, a Set trades memory for expected linear time under the same model. Sorting then scanning is another option if changing order or allocating a copy is acceptable. The correct choice depends on the guarantees you confirmed in step 1, which is why clarifying questions matter.
5. Naming and structure while you code
Interviewers read your code as they would in a code review. Small habits help:
- Use descriptive names:
seenIds,left,right, nota,b,tmp2. - Keep functions short and give them one job. Extract a helper if a block needs a comment to explain it.
- Handle edge cases at the top with early returns.
- Prefer
const; usefor...ofor array methods when they read clearly. - Do not mutate input unless you agreed it is acceptable.
- Say what you are about to do before you do it: "I'll keep two indices, one at each end."
// Clear: early return handles the empty case
function firstLongSession(sessions, minMinutes) {
if (sessions.length === 0) return null;
for (const session of sessions) {
if (session.durationMin >= minMinutes) return session;
}
return null;
}6. Communicating when you are stuck
Everyone gets stuck. Interviewers often care more about how you recover than whether you recover instantly.
- Say what you know: "I have the brute force; it is quadratic."
- Name the bottleneck: "The repeated scan inside the loop is the expensive part."
- Ask a targeted question: "Can I assume the values fit in memory? Is the input sorted?"
- Try a smaller case by hand and look for a pattern.
- Consider a data structure that gives faster lookup (
Map,Set), or sorting to expose adjacency. - If time is short, finish a correct but slower solution and discuss the improvement verbally.
Avoid long silences. Thinking aloud, in short sentences, lets the interviewer help you and see your reasoning.
7. Interview practice tips
State the bounds and assumptions. For example, “I scan n bookings once. Under the hash-table model the time is expected O(n), and I keep O(u) entries for u customers.”
Compare options on the same axes: time, space, readability, and input assumptions.
Common pitfalls:
- Starting to code before restating the problem, then solving a different problem.
- Forgetting empty and single-element inputs.
- Treating
includes,indexOf,slice,splice, and string concatenation in a loop as free operations. - Calling a solution O(n) when it hides a nested linear call.
- Treating expected hash-table lookup cost as a worst-case or language guarantee.
- Optimizing too early; correct first, fast second.
- Silently rewriting the whole solution when a one-line fix would do.
- Memorizing solutions instead of the method; a small change to the prompt exposes memorization.
8. Mini case study: the slow search suggestion
Situation. Harbor Workshops has 20,000 workshop titles. A search box suggests titles that contain what the user typed. The developer wrote:
function suggestions(titles, query) {
const results = [];
for (const title of titles) {
if (title.toLowerCase().includes(query.toLowerCase())) {
if (!results.includes(title)) results.push(title);
}
}
return results;
}Users report lag on every keystroke. Analyze the cost and propose improvements.
Solution, commented.
- Cost. The loop repeats query normalization and substring matching for every title. When all 20,000 titles are distinct and match, the duplicate check compares the new title with every earlier result. That is 199,990,000 equality checks before accounting for string lengths. Substring matching adds its own cost, which depends on the title, query, and engine.
- Prepare the data. Deduplicate exact title strings and store their lowercase forms when the list changes. Keep the original text for display. This makes repeated queries reuse normalization work while preserving the first occurrence of each exact title.
- Do less work per query. Normalize the query once and stop after the result limit. A rare or absent query can still scan the full list. The limit bounds output size.
- Measure UI latency. Measure the scan and render separately. Debouncing reduces how often a search is started, and React's
useDeferredValuecan prioritize typing over a slow result render. Deferring leaves the scan's algorithmic cost unchanged. Read more about measuring React performance before optimizing.
function buildIndex(titles) {
return [...new Set(titles)].map((title) => ({ title, lower: title.toLowerCase() }));
}
function suggestions(index, query, limit = 8) {
const q = query.trim().toLowerCase();
if (!q || !Number.isInteger(limit) || limit < 1) return [];
const out = [];
for (const entry of index) {
if (entry.lower.includes(q)) {
out.push(entry.title);
if (out.length === limit) break;
}
}
return out;
}
const index = buildIndex(['Pottery', 'Woodwork', 'Pottery', 'Wheel pottery']);
suggestions(index, 'POT', 2); // ['Pottery', 'Wheel pottery']This example searches for a case-insensitive substring using simple lowercase conversion. Agree on language and accent matching before changing that behavior. If measurement shows that scanning dominates at your scale, evaluate an index designed for substring lookup. A prefix trie supports a different query unless the requirement changes to prefix matching.
Key terms
- Pseudocode: a plain-language plan of steps without exact syntax.
- Brute force: the simplest correct approach, often slow.
- Big O notation: a description of how cost grows with input size, ignoring constants.
- Time complexity: growth of the number of operations.
- Space complexity: growth of extra memory.
- Edge case: an unusual input at the boundary, such as empty or single-element.
- Trade-off: gaining one benefit (speed) at the cost of another (memory).
- Bottleneck: the part of the solution that dominates the cost.
Summary checklist
- I restate the problem and ask about inputs, outputs, and constraints.
- I write examples and edge cases before code.
- I write pseudocode and agree the plan first.
- I describe brute force, then improve it on purpose.
- I can classify O(1), O(log n), O(n), O(n log n), O(n²).
- I spot hidden linear calls inside loops.
- I state both time and space complexity and name the trade-off.
- I trace my solution by hand and think aloud when stuck.
Sources
- Coding Interview Preparation (official ninth course of the pathway): https://www.coursera.org/learn/coding-interview-preparation (opens in a new tab)
- Meta Front-End Developer Professional Certificate: https://www.coursera.org/professional-certificates/meta-front-end-developer (opens in a new tab)
- NIST, Big O notation (opens in a new tab)
- ECMAScript keyed collections (opens in a new tab)
- React useDeferredValue (opens in a new tab)
