Airbnb Frontend Developer (Junior Level) Interview Preparation Guide
Airbnb's frontend developer interview process consists of 6 stages: an initial recruiter screening, an online technical assessment with algorithmic problems, and a 4-round virtual onsite (Engineering Loop) that evaluates coding proficiency, system design fundamentals, code quality and testing practices, and cultural fit. The entire process typically spans 4-6 weeks from application to offer decision. For junior-level candidates, the focus is on demonstrating solid fundamentals, ability to work independently with occasional guidance, and alignment with Airbnb's 'belong anywhere' culture.
Interview Rounds
Recruiter Screening
What to Expect
Initial call with Airbnb recruiter lasting 20-30 minutes to assess your background, motivation for the role, salary expectations, and general communication skills. This is a culture fit and logistics screening round. The recruiter will also validate your technical level and availability. For junior candidates, recruiters look for genuine interest in Airbnb, understanding of the company, and realistic expectations about junior-level work. No technical questions are asked, but clear communication about your experience and goals is critical.
Tips & Advice
Research Airbnb thoroughly—know their mission, recent products, and engineering culture. Prepare a 2-minute elevator pitch about your frontend experience and why you want to join Airbnb. Have specific examples of projects you've built. Be honest about your junior level and express enthusiasm for learning. Ask thoughtful questions about the team, projects, and engineering culture. This round is often the easiest—do not underestimate it as it can be a gate-keeper.
Focus Topics
Salary Expectations and Logistics
Have a realistic salary range researched (use Levels.fyi, Glassdoor), confirm availability for interview process, and clarify any logistical constraints.
Practice Interview
Study Questions
Airbnb's Mission and Product Knowledge
Demonstrate familiarity with Airbnb's core product (listings, bookings, payments), recent features, and the company's 'belong anywhere' mission.
Practice Interview
Study Questions
Communication and Professional Maturity
Speak clearly, answer questions directly without rambling, ask clarifying questions when needed, and handle curveballs gracefully.
Practice Interview
Study Questions
Motivation for Airbnb and Role Understanding
Articulate why you want to work at Airbnb specifically, what attracts you to the company, and what you understand about the frontend role's scope and impact.
Practice Interview
Study Questions
Background and Experience Overview
Clearly articulate your 1-2 years of frontend experience, key projects you've built, technologies you've worked with, and what you learned from each role.
Practice Interview
Study Questions
Online Technical Assessment
What to Expect
This is a critical technical filter conducted on platforms like HackerRank. You'll solve 2-3 algorithmic coding problems in 90-120 minutes. Problems focus on core data structures (arrays, linked lists, trees, graphs) and algorithms (searching, sorting, dynamic programming, recursion). For junior level, expect medium-difficulty LeetCode problems. You write functional code that passes test cases. This round is unproctored but monitored for plagiarism. Strong performance significantly improves your chances of advancing to the onsite loop.
Tips & Advice
Solve problems methodically: read carefully, identify the data structure/algorithm needed, write pseudocode first, then implement. Test with edge cases (empty inputs, single elements, duplicates). For junior level, a working solution is better than an optimized solution that you can't complete. If stuck, explain your thinking to the AI or mock interviewer. Manage time—don't spend more than 30-40 minutes per problem. Use JavaScript as your language. Reference typical Airbnb problems: two pointers, binary search, tree traversals, linked list operations, basic dynamic programming.
Focus Topics
Dynamic Programming and Recursion
Solve problems using recursion and memoization; identify overlapping subproblems; classic problems like fibonacci, coin change, and longest common subsequence.
Practice Interview
Study Questions
Linked Lists
Understand linked list operations: traversal, insertion, deletion, reversal, detection of cycles, and merging two sorted lists.
Practice Interview
Study Questions
JavaScript-Specific Implementation
Write clean JavaScript code using native methods, handle edge cases, write efficient loops, and debug syntax errors quickly under time pressure.
Practice Interview
Study Questions
Arrays and Strings
Master manipulation of arrays and strings including two-pointer technique, sliding window, prefix sums, and common operations like reversing, rotating, merging.
Practice Interview
Study Questions
Trees and Graphs
Proficiency with binary trees (traversals: inorder, preorder, postorder), binary search trees, graph representation, DFS, BFS, and basic shortest path problems.
Practice Interview
Study Questions
Problem-Solving Methodology
Approach: understand problem → identify patterns → choose algorithm → write pseudocode → implement → test with edge cases. Communicate each step.
Practice Interview
Study Questions
Onsite Round 1: Coding Interview
What to Expect
First onsite round (45-60 minutes) conducted by an Airbnb frontend engineer. You'll solve 1-2 algorithmic coding problems, similar to the online assessment but often slightly more complex or with real-world context. You'll be coding in a shared editor (like CoderPad or Repl.it) while screen-sharing. The interviewer observes your problem-solving process, code quality, communication, and ability to handle feedback. For junior level, interviewers expect you to solve at least one problem completely and demonstrate clear thinking. Partial solutions with good explanations are acceptable.
Tips & Advice
Treat this as a conversation with the interviewer, not a solo challenge. Think out loud—explain your approach before coding. Ask clarifying questions about edge cases and constraints. Write clean, readable code with meaningful variable names. If you get stuck, don't panic—ask for hints or pivot to a suboptimal solution and explain tradeoffs. For junior level, solving one problem well is often enough; solving both partially is acceptable if communication is clear. Mention relevant frontend contexts when possible (e.g., 'this is similar to rendering a component tree'). Test your code with examples before declaring it complete.
Focus Topics
Time Management
Complete one problem fully rather than rush both; if stuck, explain your approach and move to the next problem if time allows.
Practice Interview
Study Questions
Accepting Feedback and Iterating
When the interviewer suggests improvements or points out a bug, respond positively, adjust quickly, and explain your changes. Show adaptability.
Practice Interview
Study Questions
Code Quality and Readability
Write clean code with proper variable names, comments where non-obvious, consistent indentation, and logical organization. Avoid one-liners that sacrifice clarity.
Practice Interview
Study Questions
Verbal Communication and Problem-Solving Narration
Talk through your thought process: what the problem is asking, which data structure/algorithm fits, why you chose it, and what tradeoffs exist. Explain as you code.
Practice Interview
Study Questions
Edge Case Handling
Proactively think of edge cases: empty arrays, single elements, duplicates, negative numbers, null values. Test your solution against 2-3 edge cases.
Practice Interview
Study Questions
Onsite Round 2: System Design Interview
What to Expect
45-60 minute round evaluating your ability to think about scalable systems at a basic level. You'll be asked to design or architect a simple feature or system relevant to Airbnb's business (e.g., 'Design a property listing search system', 'Design a recommendation system for listings', or 'How would you architect a real-time notification system for bookings?'). For junior level, the focus is on understanding basic concepts like client-server architecture, API design, database choice rationale, and simple scalability trade-offs. You're not expected to know advanced distributed systems or micro-services; rather, demonstrate that you can break down a problem, ask clarifying questions, and make reasonable architectural decisions with justification.
Tips & Advice
Start by asking clarifying questions about scale, user base, and requirements. Sketch diagrams (client, server, database, cache, etc.) while explaining. For junior level, a simple monolithic architecture with a few thoughtful optimizations is perfectly acceptable. Discuss trade-offs explicitly (e.g., 'SQL vs NoSQL: SQL for consistency in bookings, NoSQL for flexible schema in reviews'). Mention technologies relevant to your experience (React on frontend, Node.js or Python on backend, PostgreSQL, Redis, Elasticsearch). Connect your design to real Airbnb features (listings, bookings, search, ratings). If unsure, ask the interviewer for guidance—this is valued at junior level. Do not over-engineer; keep it practical and explainable.
Focus Topics
Diagram Visualization and Explanation
Sketch boxes for components, arrows for communication, labels for data flow. Explain verbally as you draw to keep interviewer engaged.
Practice Interview
Study Questions
Scalability at a Basic Level
Understand caching (Redis for frequently accessed listings), indexing (faster search), and simple load distribution. Know why these help but don't need to design Kafka pipelines.
Practice Interview
Study Questions
Database Selection and Tradeoffs
When to use relational (PostgreSQL) vs document (MongoDB): consistency vs flexibility, structured vs unstructured data. For bookings use SQL; for user reviews use NoSQL.
Practice Interview
Study Questions
API Design and Frontend Integration
Design simple REST endpoints (GET /listings, POST /bookings) that frontend consumes. Think about data format, pagination, error handling.
Practice Interview
Study Questions
Client-Server Architecture Basics
Understand separation of concerns: frontend (React), backend APIs (REST or GraphQL), databases (SQL vs NoSQL), and how they communicate. Draw simple diagrams.
Practice Interview
Study Questions
Asking Clarifying Questions
Before designing, ask: How many users? Read vs write heavy? Real-time requirements? Geographic distribution? This shapes your architecture.
Practice Interview
Study Questions
Onsite Round 3: Code Review and Quality
What to Expect
45-60 minute round where you'll review a code sample or pull request (typically 50-100 lines) provided by the interviewer and identify issues, suggest improvements, and discuss best practices. At Airbnb, this often focuses on frontend code quality. Example topics: reviewing a star-rating widget form, a React component with lifecycle issues, CSS that's not responsive, JavaScript with accessibility gaps, or a component missing proper error handling. For junior level, you're expected to spot obvious bugs, suggest readable naming, identify accessibility concerns, catch potential edge cases, and explain your feedback clearly. You're not expected to catch every subtle issue, but demonstrating attention to detail is critical.
Tips & Advice
Read the code carefully first; don't rush. Organize feedback into categories: bugs, readability, performance, accessibility, testing, edge cases. For each issue, explain why it matters and suggest a fix. Be constructive and kind in tone—this is practice for real code reviews. Ask clarifying questions about the context if unclear. For junior level, spot 5-8 legitimate issues thoughtfully rather than trying to find 20. Reference best practices you've learned. Mention testing: 'I'd add unit tests for edge cases like zero or non-integer ratings.' For accessibility: 'This component should use ARIA labels for screen readers.' This round values practical engineering judgment over theoretical perfection.
Focus Topics
Performance Optimization Opportunities
Spot performance issues: unnecessary DOM manipulations, inefficient loops, missing memoization, lazy loading gaps. Suggest optimizations aligned with junior level understanding.
Practice Interview
Study Questions
Testing and Error Handling
Identify missing test coverage, unhandled edge cases (null values, empty arrays, network errors), and suggest where tests should be added.
Practice Interview
Study Questions
Accessibility Standards (WCAG, ARIA)
Identify missing accessibility features: semantic HTML, ARIA labels, keyboard navigation, focus management, color contrast. Suggest improvements for inclusivity.
Practice Interview
Study Questions
CSS and Responsive Design Issues
Spot CSS problems: missing media queries, hard-coded sizes, poor mobile responsiveness, inconsistent spacing, unused styles. Suggest responsive solutions.
Practice Interview
Study Questions
React Component Design and Lifecycle
Review React components for: proper hook usage, unnecessary re-renders, missing dependencies in useEffect, prop drilling, state management, and component reusability.
Practice Interview
Study Questions
JavaScript Code Quality and Best Practices
Identify issues: unused variables, inconsistent naming, overly complex logic, missing error handling, type safety gaps, and suggest refactoring for clarity.
Practice Interview
Study Questions
Onsite Round 4: Behavioral and Culture Fit
What to Expect
45-60 minute round conducted by an Airbnb engineering manager or senior engineer focused on culture fit, collaboration, and past experiences. You'll be asked questions like: 'Tell me about a time you worked in a diverse team', 'What does belong anywhere mean to you?', 'Describe a time you received critical feedback', 'Tell me about a project you're proud of', 'How do you handle ambiguity?', 'Describe a conflict with a teammate and how you resolved it'. For junior level, interviewers assess your emotional intelligence, coachability, alignment with Airbnb's values, ability to work in teams, and growth mindset. You don't need perfect stories—authenticity and reflection on what you learned matter more.
Tips & Advice
Prepare 4-6 strong stories using the STAR method (Situation, Task, Action, Result) showcasing collaboration, learning from failure, ownership, and growth. For junior candidates, it's perfectly fine if your examples are from school projects, internships, or side projects. Connect your stories to Airbnb's values when possible. For 'belong anywhere', share an experience where you made someone feel welcome or learned from cultural differences. Practice speaking about these stories naturally—avoid sounding robotic. At the end, ask thoughtful questions about the team, projects, and mentorship opportunities. Smile, maintain eye contact (if video), and be genuinely interested. This round is easier than technical rounds for most junior developers; use it to build rapport and show cultural alignment.
Focus Topics
Technical Communication and Helping Others
Share an experience where you explained a technical concept to a non-technical person or helped a teammate solve a problem. Show patience and clarity.
Practice Interview
Study Questions
Project Ownership and Initiative
Share an example of a project you led or drove, even if small. Show you took ownership, handled blockers, and delivered results. Highlight what you learned.
Practice Interview
Study Questions
Handling Ambiguity and Uncertainty
Describe a situation with unclear requirements or changing scope. Show how you asked questions, communicated, and adapted. Avoid describing paralysis.
Practice Interview
Study Questions
Airbnb's 'Belong Anywhere' Value and Cultural Alignment
Understand Airbnb's mission of belonging and inclusion. Articulate how you embody this value in your work and life. Share an example of fostering diversity or inclusion.
Practice Interview
Study Questions
Teamwork and Collaboration
Share specific stories of working well in teams, handling disagreements professionally, supporting teammates, and contributing to team success beyond individual contributions.
Practice Interview
Study Questions
Learning from Failure and Feedback
Describe a time you failed or received harsh feedback, what you learned, and how you improved. Show resilience and growth mindset, not defensiveness.
Practice Interview
Study Questions
Frequently Asked Frontend Developer Interview Questions
Give two or three analogies you could use to explain eventual consistency to a non-technical stakeholder. For each, note one point where the analogy could mislead them.
Sample Answer
Direct answer
Eventual consistency means that after writes stop, all copies of the data will eventually agree, but there's a window, sometimes milliseconds, sometimes longer, during which different readers can see different, both "correct at the time" answers. For a non-technical stakeholder, the useful line is: the system prioritizes staying responsive everywhere over making everyone see the same thing at the exact same instant. Below are three analogies for that idea, each with the one place it will mislead if you don't say it out loud.
Choosing the analogy and what to omit
- Pick an analogy where the delay AND the reconciliation are both visible, not just the delay. Many weak analogies (mail, gossip) only show that news travels slowly; they hide the harder part, what happens when two people acted on different information during that delay.
- Decide up front which mechanism you're omitting: you're almost always omitting HOW the system decides which write wins when two conflict. Say that you're leaving it out, rather than letting the analogy imply there's no rule for it at all.
- Check understanding by asking them to predict a scenario, not recite the definition back: "if two people edit this at the same moment from different offices, what do you think happens?" A correct prediction means the model landed; an answer that assumes instant sync means you need to go back to the delay itself.
- The same shape, plain definition, one concrete example, why it matters, holds for any jargon-heavy term a non-technical audience needs defined on the spot: ETL vs ELT (does the transformation happen before or after loading), ACID vs BASE (strict correctness vs eventual, available correctness, which is this same idea from the database's side), or REST vs GraphQL (fetch a fixed shape of data vs ask for exactly the fields you need). Same competency, different vocabulary each time.
Worked example
1. A group chat where one person's phone is off. You send a message to a group chat; everyone online sees it in under a second. Someone whose phone died an hour ago won't see it until they turn it back on, at which point it downloads and they're caught up. What it shows well: the "everyone gets there eventually, but not at the same time" shape, and that being offline doesn't break the system, it just delays that one reader. Where it misleads: it implies messages simply queue up in order. If two people update the SAME piece of shared data while a third is disconnected, there can be a genuine conflict to resolve, not just a backlog to deliver, and the chat analogy has no equivalent of "two people edited the same message."
2. A retail chain updating a sale price across stores. Head office cuts a price. Each store's system checks for updates on its own schedule, so for a few minutes Store A shows the new price and Store B still shows the old one. What it shows well: the same data existing in multiple places, each catching up on its own timeline, with no single moment where everyone updates at once. Where it misleads: it suggests the only direction of change is head office to stores, one writer, many readers. Real eventually consistent systems often allow writes at multiple locations at once, a customer changing their address from two devices, and that's where the interesting conflicts and reconciliation rules actually come from.
3. Watering one end of a long garden bed. You water one end of a dry garden bed and moisture visibly spreads down the row over the next hour until it's evenly damp. What it shows well: gradual, automatic convergence toward one final state with no single "sync" event. Where it misleads: soil moisture always converges smoothly. Some real systems can get stuck in a genuine conflict that never resolves on its own, two writes with no way to tell which should win, and need a rule, or a human, to break the tie. "It'll just even out" is the sentence most likely to leave a stakeholder with a false sense of safety.
Trade-offs and pitfalls
The single biggest risk in any of these analogies is implying the temporary disagreement is harmless. For some products it is, a slightly stale follower count. For others it isn't, two systems both believing they hold the last unit of inventory. Say plainly which case you're in. Also resist stacking all three analogies in one conversation; one that survives a follow-up question beats three shallow ones, use the extra two only if the first one visibly didn't land.
Tell me about the biggest professional setback of your career so far. What happened, how did you handle it at the time, and what did you do over the months that followed?
Sample Answer
Direct answer
My biggest professional setback wasn't a failed project, it was being laid off eight months into a role I had taken a real pay cut to join. What mattered afterward wasn't recovering my mood, it was deliberately rebuilding credibility with the specific people whose trust I needed for what came next, and being honest with myself about how the experience changed my risk tolerance rather than pretending it hadn't.
What happened and how I handled it at the time
I joined a smaller company for a role with more scope than my previous job, partly because I believed in the product, and took a meaningful pay cut to do it. Eight months in, the company went through a reduction in force tied to a division reorg, and my role was eliminated, unrelated to my own performance but no less disruptive for that. In the moment I did the practical things: filed for what support was available, gave two specific colleagues an honest, unemotional account of what happened so the story wasn't left to guesswork, and gave myself a short, bounded window, about a week, to actually feel bad about it before moving into job search mode.
What I did over the following months
The harder work happened over the following months. I reached out individually to three former colleagues and managers, not to ask for referrals immediately but to stay genuinely useful to them, answering a question here, reviewing something there, so that when I eventually did ask for a reference, it came from someone I had stayed real with rather than someone I was reappearing to only when I needed something. That rebuilding of specific relationships mattered more than any general networking. It also changed how I evaluate opportunities now: I ask much more directly about a company's financial runway and reorg history before joining, not because I think every company will do the same thing, but because I learned firsthand that being right about the product doesn't protect you from being wrong about the business underneath it.
Trade-offs and pitfalls
The pitfall in a story like this is either sounding bitter about circumstances that genuinely weren't my fault, or sanding the story down so much it loses any real reflection. I try to hold both things true at once: the layoff wasn't a reflection of my work, and it still taught me something real about how I choose where to work next.
You own the migration of a system, service, or tool that many people depend on to a new platform, framework, or format: this could be a data warehouse, a shared library, a CI/CD pipeline, a testing framework, a monitoring stack, or similar shared infrastructure. Create a migration plan covering: an inventory of what needs to move, your compatibility and parallel-run testing strategy, a cutover checklist, a rollback plan, your communication plan for dependent teams, and how you'll verify parity (nothing regressed) after the migration completes.
Sample Answer
Direct answer
Owning a migration that many people depend on is fundamentally a sequencing and risk-management problem, not a technology problem. You inventory what is actually affected before touching anything, prove the new platform can do what the old one does on a small slice before committing the whole system, cut over in a way you can reverse, and you do not call it done until you have actively verified nothing regressed, rather than waiting to see if anyone complains.
Structured elaboration
A migration plan for shared infrastructure has six parts:
- Inventory. Enumerate every consumer, integration point, and edge-case usage of the current system, not just the documented ones. The single biggest risk in a migration like this is the undocumented dependency nobody remembers until it breaks.
- Compatibility and parallel-run strategy. Before migrating anything real, prove the new platform matches the old one's behavior on a representative slice, ideally by running old and new side by side on the same input and diffing the output (comparing the two outputs field-by-field to spot any mismatch), so you find divergence before anyone actually depends on the new path.
- Sequencing and cutover checklist. Migrate the lowest-risk, most self-contained consumer first, not the biggest or most visible one, to build confidence and catch problems cheaply. Each cutover step needs an explicit go or no-go checkpoint tied to a measurable signal, not a calendar date.
- Rollback plan. For every cutover step, know in advance, before you need it, exactly how you would reverse it and how long that reversal takes. A rollback plan you have not thought through until the moment you need it does not really exist.
- Communication plan. Dependent teams need to know what is changing, when, what (if anything) they need to do on their end, and how to reach you if something breaks. Give enough lead time that nobody is surprised, and confirm the message landed rather than just broadcasting it.
- Parity verification. After cutover, actively check that outputs, behavior, and performance match the old system's, on real traffic where possible, rather than waiting for a complaint. Absence of complaints is not evidence of parity.
Worked example
Take migrating a shared internal library used by a dozen services to a new major version with breaking changes.
Inventory turned up 12 documented consumers plus two undocumented ones found by searching for actual usage, one of which called a function everyone assumed was already retired. The parallel-run phase put the new version behind a flag in the three lowest-risk consumers first, running both code paths against the same inputs for two weeks and comparing outputs before trusting the new path alone. The cutover checklist then moved the remaining nine consumers in two more batches, each batch gated on the prior batch showing no divergence for a full week, rather than moving everyone at once. The rollback plan kept the old version available at each step for a window matching that same soak period (the week-long stretch of watching a batch for divergence before trusting it and moving to the next one), so any batch could revert without a redeploy of every consumer. Communication gave each consuming team two weeks of notice, a migration guide, a named point of contact, and one specific action to take, a config flag to flip, and the plan tracked an explicit acknowledgment from each team lead rather than assuming an email had been read. After full cutover, parity verification compared error rate and latency for each consumer against its own pre-migration baseline for two more weeks before the project was closed, since a subtle regression is more likely to look like a slow drift than an outage.
Trade-offs and pitfalls
The most common failure is starting with the most important consumer to "prove it fast," which puts your first, least-proven attempt on the path with the largest blast radius (the widest set of dependent consumers or systems it could break if the attempt goes wrong). A second is treating communication as a one-time announcement instead of a confirmed, two-way acknowledgment, since silence is not the same as consent. A third is skipping parity verification because nothing broke immediately, when many real regressions show up as gradually rising latency or a rare edge case rather than a clean outage. And a rollback plan that exists only on paper, never rehearsed, is close to having no rollback plan at all, because its first real use will be under the worst possible time pressure.
You're evaluating a third-party UI library that increases velocity but lacks proper ARIA support for several widgets. Describe how you'd evaluate risks and benefits, propose mitigation strategies (wrappers, polyfills, contributing upstream), and explain how you'd decide with engineering and product stakeholders whether to adopt, extend, or avoid the library.
Sample Answer
Direct answer. Evaluating a velocity-improving but ARIA-deficient third-party UI library is a real trade-off, not a simple reject-or-accept decision: weigh the specific gaps against your actual usage (a library missing ARIA on a rarely-used component matters less than one missing it on your primary navigation), and consider wrapper components or contributed upstream fixes as mitigation before ruling the library out entirely.
Evaluating risks and benefits. Audit specifically which of the library's components you'll actually use and test THOSE for accessibility gaps directly (with axe and a manual keyboard pass), rather than trusting the library's general reputation or documentation claims; weigh the velocity gain against the actual remediation cost for just the gaps that affect your usage, not a worst-case reading of every component in the library.
Mitigation strategies.
- Wrapper components: build a thin accessible wrapper around the library's component that adds the missing ARIA attributes and keyboard handlers, isolating the fix in one place so a library upgrade doesn't require re-patching every usage site individually.
- Polyfills: for structural gaps, a small utility that post-processes the rendered DOM to add missing attributes can work as a stopgap, though it's more fragile since it depends on the library's internal markup staying stable across versions.
- Contributing upstream: filing the specific issue and, where feasible, submitting the fix yourself benefits every future version and every other consumer of the library, and is worth attempting even if it's slower than a local wrapper, since the wrapper approach accumulates technical debt that upstream contribution avoids.
- Vendor pressure: for a commercially-licensed library, raising the specific gap with the vendor and citing your organization's own compliance obligations sometimes gets a faster fix than a community open-source contribution would.
A worked instance. Concretely: suppose the audit finds the library's date-picker component renders no aria-expanded on its popover trigger button and never moves focus into the calendar grid when it opens. The wrapper fix is small: wrap the library's <DatePicker> in your own component that sets aria-expanded={isOpen} on the trigger button and, in an onOpen callback the library already exposes, calls .focus() on the calendar grid's first focusable date cell. That is roughly a day of engineering time including a manual keyboard-and-axe re-test, against a multi-week cost to build a compliant date-picker from scratch, exactly the kind of concrete number that makes "adopt-with-wrapper" comparable to "adopt as-is" and "avoid" rather than abstract.
Deciding with engineering and product stakeholders. Bring the audit findings, gap severity, and remediation-cost estimate to a single structured decision session with both groups rather than making the call unilaterally: engineering is the right owner of the remediation-cost and timeline estimate (how long a wrapper or upstream fix realistically takes), while product owns the velocity/timeline trade-off (what shipping later actually costs the roadmap) and typically the user-impact call (how many affected users, how central the broken components are to primary flows). Frame the decision as three concrete options, adopt as-is, adopt-with-wrapper, or avoid, each with its cost and risk stated in the same terms, so the group is choosing between comparable options rather than debating in the abstract.
When to walk away. If the gaps are in components central to your primary user flows and no combination of wrapper/upstream-fix is realistic on your timeline, the velocity gain isn't worth shipping something genuinely broken for a meaningful user population; that's a legitimate reason to choose a different library or build the component in-house despite the extra cost.
Trade-offs and pitfalls. Adopting the library first and deciding to "fix accessibility later" is a common trap, since the wrapper/patch work is easiest to design correctly BEFORE the library is deeply integrated across the codebase, and gets progressively more expensive to retrofit the more usage sites accumulate.
Tell me about a cross-team initiative you were part of that didn't meet its goals because of a breakdown in how the teams worked together. What did you learn, and what actually changed afterward?
Sample Answer
Direct answer
A cross-team initiative I was part of missed its goals because of how, not what, we coordinated: unclear ownership across the teams involved, and assumptions that stayed unstated until they caused real problems. The lasting change wasn't a one-time apology or a single retro action item; it was a concrete shift in how the teams handed work to each other afterward, and I could point to whether that same failure mode recurred as the real evidence it stuck.
Structured elaboration
What broke, specifically
Swap in whatever cross-team dependency applies in your own world (a shared data pipeline, an API contract, a joint launch). In this skeleton, a project spanning several teams missed its deadline and caused repeated problems during a pilot phase because of two gaps: an unstated assumption about how a downstream team's dependency actually worked, and no clear escalation path when a blocking issue crossed a team boundary, so problems sat for days before the right people even knew about them.
How I ran the postmortem
- Built a timeline from evidence (incident counts, missed dates, rollback frequency), not memory or opinion.
- Separated the technical root causes from the collaboration root causes, since they needed different fixes.
- Named my own part in the failure to the group first, rather than only pointing at others' misses.
What actually changed afterward, and how I know
Concrete artifacts, not intentions: a documented dependency map required before a cross-team project kicks off, a clear ownership assignment per milestone naming who is accountable for what, and a pre-cutover checklist signed off by every team with something at stake, not just the owning team.
When the real obstacle is culture, not process
Sometimes the harder problem isn't a missing checklist, it's shifting a broader culture away from punitive postmortems toward ones people are actually honest in, particularly when some teams still default to blame. Modeling that shift means naming your own contribution to the failure before asking anyone else to, keeping the review focused on the system and the decision points rather than individuals, and treating a later postmortem where someone from a still-blame-oriented team volunteers a candid mistake as the real signal that the culture is moving, not just a nice-to-have.
Worked example
A multi-team initiative to consolidate several systems onto a shared platform missed its timeline and caused a string of problems during a pilot rollout. The retro traced the root cause to two things: application teams weren't told about a change in how long access credentials would remain valid under the new platform, and there was no agreed escalation path when a blocking issue spanned two teams. The concrete changes that came out of it were a mandatory dependency map and sign-off checklist before any team's cutover, and a named escalation contact per team for the duration of the rollout. A better signal of real progress on culture came from a smaller moment: at the next postmortem, a team that had previously stayed quiet about its own mistakes volunteered, unprompted, that a missed step on their side had contributed to a separate incident, which said more about the blame reflex fading than anything written in a process document.
Trade-offs and pitfalls
- A postmortem that produces only reflections ('we should communicate better') without a concrete, checkable change is the most common failure of this kind of story; the interviewer is listening for what's different in the next project, not what was learned.
- Owning your own part in the failure has to be genuine, not a rhetorical move before pivoting to blame others; if it reads as performative, it undercuts the whole story.
- A culture shift away from blame doesn't happen from one retro; it shows up gradually, in whether people volunteer uncomfortable information without being asked, and that takes sustained modeling, not a single well-run session.
- Watch for a story that only describes what changed for the team that failed, rather than what changed structurally for how all the involved teams hand off work to each other, since the initiative broke because more than one team was involved.
Discuss the time-space trade-offs between using a hash map (dictionary) versus sorting the data when you need to count occurrences or detect duplicates in a dataset. Include complexity, memory overhead, stability, and practical considerations for data scientist workflows.
Sample Answer
Direct answer
A hash map counts occurrences or detects duplicates in O(n) time using O(n) auxiliary space (n = number of elements, or the number of distinct elements if that's smaller), at the cost of losing the original relative order between distinct keys unless that order is tracked separately. Sorting does the same job in O(n log n) time, using O(1) to O(n) auxiliary space depending on the sort algorithm, but naturally groups equal elements adjacently, and a stable sort additionally preserves the relative order of equal elements from the input. The right default for "count occurrences" or "detect duplicates" is the hash map, because its time complexity is strictly better; sorting earns its keep when the data must end up ordered anyway, or when memory for an auxiliary hash structure is the binding constraint.
Structured elaboration
Where the time complexity gap comes from. A hash map answers "have I seen this key, and how many times" in expected O(1) time per lookup/update, so processing n elements is O(n) total. A comparison-based sort cannot do better than O(n log n) in the worst case: this follows from the recurrence a typical divide-and-conquer sort like merge sort satisfies, T(n) = 2*T(n/2) + O(n) (split into two halves, recursively sort each, then merge in linear time), which by the Master theorem resolves to T(n) = Theta(n log n), since the work of combining subproblems (O(n) per level) matches the growth rate of the recursive branching exactly (a = 2 subproblems of size n/b = n/2, and n^(log_b(a)) = n^1, matching f(n) = O(n)). Concretely, doubling n from, say, 1,000 to 2,000 elements roughly doubles the hash-map approach's work, but more than doubles the sort's work (2,000 * log2(2,000) is proportionally larger than 1,000 * log2(1,000)), and this gap widens as n grows.
Memory overhead. A hash map's O(n) space is not just n data slots: a hash table typically keeps its load factor (fraction of slots occupied) below some threshold to keep lookups fast, meaning it holds some fraction of empty slots as overhead, plus per-entry bookkeeping (a stored hash code, pointers for collision chains, or open-addressing probe metadata) beyond the raw key and count value. An in-place comparison sort (like heapsort or an in-place quicksort variant) can use O(1) auxiliary space instead, though a stable sort like merge sort (or Python's Timsort, which is stable) typically needs O(n) auxiliary space to merge into, so "sorting uses less memory" is only true for the specific unstable, in-place sort algorithms, not sorting in general.
Stability. A stable sort preserves the relative order of elements that compare equal; this matters when equal-looking rows carry other differing fields the caller cares about (say, sorting purchase records by customer ID while wanting same-customer records to stay in their original timestamp order). A hash map used purely for counting or membership-testing has no concept of "relative order" of distinct keys at all, though a Python dict (used since Python 3.7) specifically preserves the insertion order of its keys, meaning a dict-based deduplication pass naturally reports first-occurrence order for free without needing a separate ordered structure.
Practical considerations for data scientist workflows. pandas.Series.value_counts() is hash-based internally and defaults to returning results ordered by count (its sort parameter defaults to True, sorted descending by count, i.e. ascending=False), which is a presentation-time sort layered on top of a hash-based count, not evidence that counting itself needs sorting. Similarly, DataFrame.groupby() defaults to sort=True for its output group-key ordering (verified against pandas 3.0.3), which again is an ordering choice applied after a hash-based grouping operation, and can be turned off (sort=False) when the caller only needs the aggregated result and doesn't care about output key order, trading a small amount of avoided sort work for unordered output.
Worked example
Pinned data (n = 8 elements), comparing the hash-based approach (pandas value_counts(), which uses a hash table internally) against a manual sort-then-scan approach, and an explicit order-of-growth comparison for n = 8:
import pandas as pd
import math
data = [7, 3, 7, 1, 3, 3, 9, 1] # n = 8, pinned
s = pd.Series(data)
counts_hash = s.value_counts() # hash-based; default sort=True (by count, descending)
print("value_counts() (hash-based):", counts_hash.to_dict())
first_seen_order = list(dict.fromkeys(data))
print("first-occurrence order via dict-based dedup:", first_seen_order)
sorted_data = sorted(data)
print("sorted array:", sorted_data)
sort_counts = {}
i = 0
while i < len(sorted_data):
j = i
while j < len(sorted_data) and sorted_data[j] == sorted_data[i]:
j += 1
sort_counts[sorted_data[i]] = j - i
i = j
print("counts via sort-then-scan:", sort_counts)
print("both methods agree on counts:", set(counts_hash.items()) == set(sort_counts.items()))
n = len(data)
print(f"n = {n}")
print(f"hash-map approach: ~{n} O(1) operations (one dict update per element)")
print(f"comparison-sort approach: work scales with n * log2(n) = {n} * {math.log2(n):.0f} = {n * math.log2(n):.0f} (order-of-growth illustration, not a literal comparison count)")
Output (actual run, pandas 3.0.3):
value_counts() (hash-based): {3: 3, 7: 2, 1: 2, 9: 1}
first-occurrence order via dict-based dedup: [7, 3, 1, 9]
sorted array: [1, 1, 3, 3, 3, 7, 7, 9]
counts via sort-then-scan: {1: 2, 3: 3, 7: 2, 9: 1}
both methods agree on counts: True
n = 8
hash-map approach: ~8 O(1) operations (one dict update per element)
comparison-sort approach: work scales with n * log2(n) = 8 * 3 = 24 (order-of-growth illustration, not a literal comparison count)
Both approaches agree on the actual counts ({1: 2, 3: 3, 7: 2, 9: 1}, just presented in different key order), confirming they're computing the same underlying answer. value_counts() sorts by count descending, the manual sort-then-scan naturally produces sorted-key order, and the dict-based dedup preserves original first-occurrence order ([7, 3, 1, 9]), a third distinct ordering, none of which is "more correct" than another since the underlying counts are identical.
Trade-offs and pitfalls
- Defaulting to sorting out of habit, when the task is purely "count" or "detect duplicates" with no downstream need for ordered output, pays an unnecessary
O(n log n)versusO(n)cost; naming the hash-map option first and explaining why it wins on pure counting is the stronger answer. - Conversely, if the output must be presented in sorted order regardless (a leaderboard, a sorted report), sorting isn't optional overhead added on top of counting, it's part of the actual requirement, so comparing "hash map wins" against a workflow that needs sorted output anyway is comparing the wrong things; the honest framing is "hash map for the counting step, sort only if and when order is actually required downstream."
- Memory overhead from a hash table's load-factor slack and per-entry bookkeeping is real but usually small relative to sorting's own auxiliary needs for a stable algorithm; the actual crossover point depends on implementation details (language, specific hash table and sort implementation) rather than a fixed rule of thumb.
pandas.Series.value_counts()'s default sort behavior is a common source of confusion: it does NOT mean the counting itself requires a sort. Passingsort=Falseavoids the extra ordering step when only the counts matter, not the presentation order.- Relying on
dictkey-insertion-order preservation for "first occurrence order" is a real, documented Python behavior (since Python 3.7) worth naming, but it is language-specific; the same trick cannot be assumed in a language whose hash-map implementation makes no ordering guarantee.
An inline link in a navigation list needs padding, a fixed height and a click area as large as its box. Which display behaviour would you choose and why? Contrast block, inline and inline-block layout, and explain how hiding an element with display none differs from visibility hidden and opacity zero for layout, clicks and screen readers.
Sample Answer
Direct answer
Make the link display: inline-block (or block when it should fill its own row, or the link a flex item with display: block). An inline element ignores width and height, and its vertical padding paints outside the line box (the invisible strip of fixed height that holds one line of text, which sets how tall the line is) without pushing anything, so a padded inline link overlaps its neighbours. inline-block flows in a line like text yet accepts width, height, padding and margin on all sides, so the click area equals the box you sized. For hiding: display: none removes the element from layout, clicks and the accessibility tree (the simplified copy of the page that the browser builds for assistive technology such as screen readers); visibility: hidden keeps the space but removes it from clicks and the accessibility tree; opacity: 0 keeps the space, stays clickable, stays focusable and stays in the accessibility tree.
The three display behaviours
| Behaviour | Starts a new line? | Honors width/height? | Vertical padding/margin affect neighbours? | Typical use |
|---|---|---|---|---|
block | yes, and fills the row when width is auto | yes | yes | Sections, paragraphs, a link that should be a full-width row |
inline | no | no | no (it paints, but line height is unchanged) | Words inside text: a, span, em |
inline-block | no | yes | yes | Buttons-in-a-line, pill links, badges |
Worked example: the nav link, measured
The first loop puts the same two links in a nav with padding: 12px 16px; height: 60px; width: 120px; box-sizing: border-box and changes only display. The second loop hides a button three ways and records layout, hit-testing (elementFromPoint: which element a click at that point would land on), the accessibility snapshot, and the first Tab stop.
import { chromium, firefox, webkit } from 'playwright';
// Part 1: how a nav link behaves under each display value.
const navCss = (d) => `
body { margin: 0; padding-top: 30px; font: 16px/20px sans-serif; }
nav { background: #eee; }
a { display: ${d}; box-sizing: border-box; padding: 12px 16px; height: 60px; width: 120px; }`;
const nav = `<nav>
<a href="#" id="one">One</a>
<a href="#" id="two">Two</a>
</nav>`;
// Part 2: three ways to hide a button.
const hideCss = (rule) => `body{margin:0;font:16px/20px sans-serif} span,button{display:block;height:20px} #x{${rule}}`;
const hide = `<span>before</span><button id="x">Hidden</button><button id="y">After</button>`;
for (const type of [chromium, firefox, webkit]) {
const browser = await type.launch();
const page = await browser.newPage({ viewport: { width: 800, height: 400 } });
console.log(type.name());
for (const d of ['inline', 'inline-block', 'block']) {
await page.setContent(`<style>${navCss(d)}</style>${nav}`);
const m = await page.evaluate(() => {
const r = (id) => document.getElementById(id).getBoundingClientRect();
const a = r('one'), b = r('two');
const hit = document.elementFromPoint(a.left + 2, a.top + 2);
return { w: a.width, h: a.height, nav: document.querySelector('nav').getBoundingClientRect().height,
hit: hit.tagName, next: b.top >= a.bottom ? 'stacked below' : `gap ${(b.left - a.right).toFixed(1)}` };
});
const size = d === 'inline' ? `${Math.round(m.w)}x${Math.round(m.h)} (60 ignored)` : `${m.w}x${m.h}`;
console.log(` a{display:${d}}`.padEnd(26), `${size}`.padEnd(32), `nav height ${m.nav}`.padEnd(15), `corner click hits ${m.hit}`.padEnd(20), m.next);
}
for (const rule of ['', 'display:none', 'visibility:hidden', 'opacity:0']) {
await page.setContent(`<style>${hideCss(rule)}</style>${hide}`);
const m = await page.evaluate(() => {
const y = document.getElementById('y').getBoundingClientRect();
const x = document.getElementById('x').getBoundingClientRect();
const hit = document.elementFromPoint(x.left + 5, x.top + 10);
return { yTop: y.top, hit: x.width ? '#' + (hit.id || hit.tagName) : 'nothing (no box)' };
});
const tree = JSON.stringify(await page.accessibility.snapshot());
await page.keyboard.press('Tab');
const first = await page.evaluate(() => document.activeElement.id);
console.log(` hide with ${(rule || '(nothing)')}`.padEnd(28), `next button top ${m.yTop} click lands on ${m.hit} in a11y tree ${tree.includes('Hidden')} first Tab stop #${first}`);
}
await browser.close();
}
Output:
chromium
a{display:inline} 62x41 (60 ignored) nav height 20 corner click hits A gap 4.5
a{display:inline-block} 120x60 nav height 60 corner click hits A gap 4.5
a{display:block} 120x60 nav height 120 corner click hits A stacked below
hide with (nothing) next button top 40 click lands on #x in a11y tree true first Tab stop #x
hide with display:none next button top 20 click lands on nothing (no box) in a11y tree false first Tab stop #y
hide with visibility:hidden next button top 40 click lands on #BODY in a11y tree false first Tab stop #y
hide with opacity:0 next button top 40 click lands on #x in a11y tree true first Tab stop #x
firefox
a{display:inline} 60x45 (60 ignored) nav height 20 corner click hits A gap 4.8
a{display:inline-block} 120x60 nav height 60 corner click hits A gap 4.8
a{display:block} 120x60 nav height 120 corner click hits A stacked below
hide with (nothing) next button top 40 click lands on #x in a11y tree true first Tab stop #x
hide with display:none next button top 20 click lands on nothing (no box) in a11y tree false first Tab stop #y
hide with visibility:hidden next button top 40 click lands on #BODY in a11y tree false first Tab stop #y
hide with opacity:0 next button top 40 click lands on #x in a11y tree true first Tab stop #x
webkit
a{display:inline} 61x44 (60 ignored) nav height 20 corner click hits A gap 5.0
a{display:inline-block} 120x60 nav height 60 corner click hits A gap 5.0
a{display:block} 120x60 nav height 120 corner click hits A stacked below
hide with (nothing) next button top 40 click lands on #x in a11y tree true first Tab stop #x
hide with display:none next button top 20 click lands on nothing (no box) in a11y tree false first Tab stop #y
hide with visibility:hidden next button top 40 click lands on #BODY in a11y tree false first Tab stop #y
hide with opacity:0 next button top 40 click lands on #x in a11y tree true first Tab stop #x
What each row shows:
inline: the 60px height is ignored (the box is about 41 to 45px tall, depending on the engine's font metrics: line text plus 12px padding above and below). Thenavstays 20px tall, so the link's padding paints outside the line box and overlaps whatever is above and below. The padding corner still hits theA(clicks work), but the layout around it does not make room.inline-block: exactly 120x60 and thenavgrows to 60. The corner of the padding is clickable. There is a 4.5 to 5px gap between the links. It comes from the space character in the HTML between the two<a>tags, so it is the width of a space in the current font, which is why it differs slightly per engine.block: 120x60, and each link sits on its own row (thenavis 120). Because the width is set to 120px it does not fill the row; remove thatwidthand a block link spans the container, which is usually what you want for a mobile menu item.- Hiding:
display:nonehas no box: the next button moves up from top 40 to top 20, there is nothing to click, the node is absent from the accessibility tree, and Tab skips to#y.visibility:hiddenkeeps the space (top stays 40), the click falls through toBODY, it is absent from the accessibility tree and Tab skips it.opacity:0changes nothing but looks: it keeps its space, a click still lands on#x, it is in the accessibility tree and it is still the first Tab stop.
MDN confirms the two accessibility rows: "Using a display value of none on an element will remove it from the accessibility tree", and for visibility: hidden the box "still affects layout as normal" and "will remove it from the accessibility tree". These are the browsers' accessibility trees; what a particular screen reader then announces is up to that software.
Side by side, from the measured rows above (Chromium, Firefox and WebKit agree):
| Technique | Takes up space | Receives a click | Reachable with Tab | In the accessibility tree |
|---|---|---|---|---|
display: none | no | no | no | no |
visibility: hidden | yes | no | no | no |
opacity: 0 | yes | yes | yes | yes |
Choosing for the nav
nav ul { display: flex; gap: 8px; margin: 0; padding: 0; list-style: none; }
nav a { display: block; padding: 12px 16px; min-height: 44px; box-sizing: border-box; }
The ul as a flex container removes the whitespace gap without hacks (flex items ignore whitespace text), and each a is a block box inside its flex item, so the whole padded rectangle is the click target. min-height rather than height lets a wrapped label grow instead of overflowing. This second script measures that flex nav and also checks the visually-hidden CSS used in the pitfalls below (elementFromPoint returns the element a click at a given point would hit):
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const css = `
body { margin: 0; font: 16px/20px sans-serif; }
nav ul { display: flex; gap: 8px; margin: 0; padding: 0; list-style: none; }
nav a { display: block; padding: 12px 16px; min-height: 44px; box-sizing: border-box; }
.visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0;
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }`;
const html = `<nav><ul>
<li><a href="#" id="one">One</a></li>
<li><a href="#" id="two">Two</a></li>
</ul></nav>
<a href="#main" class="visually-hidden" id="skip">Skip to content</a>`;
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage({ viewport: { width: 800, height: 400 } });
await page.setContent(`<style>${css}</style>${html}`);
const m = await page.evaluate(() => {
const a = document.getElementById('one').getBoundingClientRect();
const b = document.getElementById('two').getBoundingClientRect();
const hit = (x, y) => document.elementFromPoint(x, y)?.id;
return { h: a.height, gap: b.left - a.right,
topLeft: hit(a.left + 1, a.top + 1), bottomRight: hit(a.right - 1, a.bottom - 1) };
});
assert.deepEqual([m.h, m.gap, m.topLeft, m.bottomRight], [44, 8, 'one', 'one']);
const s = await page.evaluate(() => { const r = document.getElementById('skip').getBoundingClientRect(); return [r.width, r.height]; });
const tree = JSON.stringify(await page.accessibility.snapshot());
await page.keyboard.press('Tab'); await page.keyboard.press('Tab'); await page.keyboard.press('Tab');
const focused = await page.evaluate(() => document.activeElement.id);
assert.equal(focused, 'skip'); assert.ok(tree.includes('Skip to content'));
console.log(name.padEnd(9), `link ${m.h}px tall, gap ${m.gap}px, corner clicks hit #${m.topLeft}/#${m.bottomRight} | visually-hidden box ${s[0]}x${s[1]}, in a11y tree ${tree.includes('Skip to content')}, third Tab stop #${focused}`);
await browser.close();
}
Run in the same Playwright 1.48.2 container, it prints:
chromium link 44px tall, gap 8px, corner clicks hit #one/#one | visually-hidden box 1x1, in a11y tree true, third Tab stop #skip
firefox link 44px tall, gap 8px, corner clicks hit #one/#one | visually-hidden box 1x1, in a11y tree true, third Tab stop #skip
webkit link 44px tall, gap 8px, corner clicks hit #one/#one | visually-hidden box 1x1, in a11y tree true, third Tab stop #skip
Each link is 44px tall, the gap between links is exactly the 8px from gap with no whitespace gap, and clicks in the top-left and bottom-right corners of the padding land on the link.
Whitespace and ignored width: the two classic bugs
- Gaps between
inline-blockitems (measured above). Fixes: flex or grid on the parent (best),font-size: 0on the parent (brittle), or remove the whitespace in HTML. width/heighton aspanorathat has no effect because it is stillinline.
Pitfalls
- To hide something visually but keep it for screen readers use a visually-hidden technique, not
display: none(MDN notes the same: remove it visually but keep it available to assistive technology). The.visually-hiddenrule in the script above shrinks the element to a 1px box, clips it and takes it out of the flow, so nothing is drawn or pushed, while the element stays in the accessibility tree and keeps its place in the Tab order, as the printed1x1,trueand#skipshow. opacity: 0is a trap for modals and menus: invisible but still clickable and focusable.- For hiding with a transition,
displaycannot be tweened in the usual way, so people reach forvisibilityoropacity; remember what each leaves behind.
Running the code
# save the first listing as display.mjs and the nav script as navcheck.mjs, then, in the same folder:
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i --no-audit --no-fund playwright@1.48.2 && timeout 120 node display.mjs && timeout 60 node navcheck.mjs'
The image ships Chromium, Firefox and WebKit. The WebKit build here is Playwright's, not Safari on iOS.
Design the client-side state architecture for an e-commerce SPA with catalog browsing, a cart that responds instantly, live inventory updates and shared product entities. Which state lives where, and how does data flow for reads and writes?
Sample Answer
Direct answer
Split the state by who owns it and how long it lives, and give each kind exactly one home:
- Server-owned data (catalog lists, product details, live stock): fetched, cached, and stored normalized, meaning each product is stored once by id and every list or screen holds only ids. This is what makes "shared product entities" and live inventory updates cheap to keep correct.
- Client-owned shared state (the cart, as a list of pending operations on top of the server's last confirmed cart): lives in one store so the badge, the cart page and checkout agree.
- URL state (search text that was submitted, filters, sort, page, the open product): lives in the route so links, reload and the back button work.
- Local component state (a half-typed search box, an open dropdown, hover): stays in
useStateinside the component that uses it. - Derived state (cart count, line totals, "only 2 left"): computed from the above by selectors, never stored.
Reads flow one way: server or socket data goes through a reducer into the store, and components read slices through selectors. Writes flow as events: the UI dispatches an optimistic operation, the request goes out, and the server's answer confirms or rolls it back.
The vocabulary of that flow:
- Store. The one object that holds the shared state. It offers
get()(current state),subscribe(fn)(be told when state changes) anddispatch(action). - Action and dispatch. An action is a plain object describing what happened, such as
{ type: 'inventoryEvent', id: 'p2', stock: 4, version: 2 }. To dispatch is to hand it to the store. - Reducer. A pure function
(state, action) => next statethat returns a new state object instead of editing the old one. If it returns the same object, nothing changed and nobody is notified. - Selector. A function from the whole state to the one small value a component needs, such as
(s) => s.products[id].stock. A component re-renders only when what its selector returns changes. - Optimistic update. Showing the result of an action immediately, before the server has confirmed it, and undoing it if the server refuses.
- Request deduplication and background refetch. Several components asking for the same data trigger one request, and cached data is re-requested quietly while the old copy stays on screen.
A workable order for designing it: sort every piece of state by owner (the table in the next section), shape the server data as entities plus id lists, model the cart as confirmed plus pending operations, add versions to the socket messages, and finally decide what goes in the URL. The program below implements this core with a small hand-written store so every claim can be counted; in a production app the fetching layer would be a server-state library (cache, request deduplication, background refetch) feeding the same entity shape.
What lives where, and why
| State | Home | Reason |
|---|---|---|
| Product entities (title, price, stock, version) | normalized entity map keyed by id | One copy; list, detail and cart read the same record |
| Result lists ("all", "search: lamp") | arrays of ids | Reordering or filtering never duplicates entities |
| Cart | confirmed server cart plus a list of pending operations | Rollback is deleting an operation; no snapshots |
| Cart count, totals, displayed quantity | selectors over the two rows above | Derived values cannot drift out of sync |
| Search draft, dropdown open | useState in the component | No other part of the app needs it; changing it re-renders only that component |
| Filters, sort, page, selected product | URL | Shareable and survives reload |
Running implementation
The reducer holds entities, lists of ids and the cart. inventoryEvent is the WebSocket message (a WebSocket is a persistent two-way connection the server uses to push updates), and it carries a version so a late, older message cannot overwrite a newer one. The fake backend processes calls in order but lets the test deliver responses in any order, which is how real networks behave. The checks cover re-render counts (from the run), the optimistic cart, out-of-order replies, a server rejection (including one while another add is still pending), and a denormalized comparison at the end.
import { JSDOM } from 'jsdom';
import assert from 'node:assert/strict';
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost' });
globalThis.window = dom.window; globalThis.document = dom.window.document;
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
const React = (await import('react')).default;
const { render, act, cleanup, fireEvent } = await import('@testing-library/react');
const { useState, memo } = React;
const h = React.createElement;
// ================= 1. one store: normalized entities + lists of ids + cart as pending operations
const initial = { products: {}, lists: {}, cart: { confirmed: { version: 0, qty: {}, applied: [] }, ops: [], error: null } };
function reducer(s, a) {
switch (a.type) {
case 'listLoaded': { // entities by id; the list keeps ids only
const products = { ...s.products };
for (const p of a.products) products[p.id] = { ...products[p.id], ...p };
return { ...s, products, lists: { ...s.lists, [a.key]: a.products.map((p) => p.id) } };
}
case 'inventoryEvent': { // websocket: apply only if newer than what we hold
const cur = s.products[a.id];
if (!cur || a.version <= cur.version) return s;
return { ...s, products: { ...s.products, [a.id]: { ...cur, stock: a.stock, version: a.version } } };
}
case 'cartAddStarted': return { ...s, cart: { ...s.cart, error: null, ops: [...s.cart.ops, { opId: a.opId, id: a.id }] } };
case 'cartAddConfirmed': { // the server's cart replaces ours; ops it already includes are dropped
const c = s.cart;
if (a.cart.version <= c.confirmed.version) return { ...s, cart: { ...c, ops: c.ops.filter((o) => !a.cart.applied.includes(o.opId)) } };
return { ...s, cart: { ...c, confirmed: a.cart, ops: c.ops.filter((o) => !a.cart.applied.includes(o.opId)) } };
}
case 'cartAddFailed': return { ...s, cart: { ...s.cart, ops: s.cart.ops.filter((o) => o.opId !== a.opId), error: a.reason } };
default: return s;
}
}
function createStore() {
let state = initial; const subs = new Set();
return { get: () => state, subscribe: (f) => { subs.add(f); return () => subs.delete(f); },
dispatch: (a) => { const next = reducer(state, a); if (next !== state) { state = next; subs.forEach((f) => f()); } } };
}
// derived state is computed, never stored: displayed quantity = confirmed + pending operations
const qtyOf = (s, id) => (s.cart.confirmed.qty[id] || 0) + s.cart.ops.filter((o) => o.id === id).length;
const cartCount = (s) => Object.keys(s.products).reduce((n, id) => n + qtyOf(s, id), 0);
const cartTotal = (s) => Object.values(s.products).reduce((t, p) => t + p.priceCents * qtyOf(s, p.id), 0);
let store; const renders = {};
const hit = (k) => { renders[k] = (renders[k] || 0) + 1; };
const useSel = (sel) => React.useSyncExternalStore(store.subscribe, () => sel(store.get()));
// ================= 2. fake backend: processes calls in order, delivers responses when the test says so
function makeApi() {
const api = { stock: { p1: 3, p2: 5, p3: 0 }, cart: { version: 0, qty: {}, applied: [] }, held: [], calls: 0 };
api.addToCart = (opId, id) => { api.calls++;
if (api.stock[id] < 1) return Promise.reject(new Error('out of stock'));
api.cart = { version: api.cart.version + 1, qty: { ...api.cart.qty, [id]: (api.cart.qty[id] || 0) + 1 }, applied: [...api.cart.applied, opId] };
const snapshot = api.cart;
return new Promise((resolve) => api.held.push(() => resolve(snapshot))); };
api.deliver = async (index) => { await act(async () => { api.held.splice(index, 1)[0](); await Promise.resolve(); }); };
return api;
}
let opSeq = 0;
async function addToCart(api, id) { // optimistic path: dispatch first, then talk to the server
const opId = 'op' + ++opSeq;
store.dispatch({ type: 'cartAddStarted', opId, id });
try { store.dispatch({ type: 'cartAddConfirmed', cart: await api.addToCart(opId, id) }); }
catch (e) { store.dispatch({ type: 'cartAddFailed', opId, reason: e.message }); }
}
// ================= 3. components: each selects the smallest slice it needs
const ProductCard = memo(function ProductCard({ id }) {
const title = useSel((s) => s.products[id].title), stock = useSel((s) => s.products[id].stock);
hit('card ' + id);
return h('li', { 'data-card': id }, `${title} (${stock} left)`);
});
function Grid() { const ids = useSel((s) => s.lists.all.join(',')).split(','); hit('grid'); return h('ul', null, ids.map((id) => h(ProductCard, { key: id, id }))); }
function Detail({ id }) { const stock = useSel((s) => s.products[id].stock); hit('detail'); return h('p', { 'data-detail': true }, `detail ${id}: ${stock} left`); }
function CartBadge() { const n = useSel(cartCount), t = useSel(cartTotal), e = useSel((s) => s.cart.error); hit('badge');
return h('b', null, `cart ${n} / $${(t / 100).toFixed(2)}${e ? ' / ' + e : ''}`); }
function Search() { const [q, setQ] = useState(''); hit('search'); // local UI state: nothing outside this component needs it
return h('input', { 'aria-label': 'search', value: q, onChange: (e) => setQ(e.target.value) }); }
const App = () => h('div', null, h(Search), h(CartBadge), h(Grid), h(Detail, { id: 'p2' }));
// ================= 4. run it
store = createStore();
const api = makeApi();
store.dispatch({ type: 'listLoaded', key: 'all', products: [
{ id: 'p1', title: 'Mug', priceCents: 1200, stock: 3, version: 1 }, { id: 'p2', title: 'Lamp', priceCents: 4500, stock: 5, version: 1 },
{ id: 'p3', title: 'Desk', priceCents: 30000, stock: 0, version: 1 }] });
const { container } = render(h(App));
const text = (sel) => container.querySelector(sel).textContent;
const snap = () => ({ ...renders }); const diff = (a, b) => Object.fromEntries(Object.keys(b).map((k) => [k, b[k] - (a[k] || 0)]).filter(([, d]) => d));
let before = snap();
for (const v of ['l', 'la', 'lam']) fireEvent.change(container.querySelector('input'), { target: { value: v } });
console.log('typing 3 chars : re-renders', JSON.stringify(diff(before, renders)));
assert.deepEqual(diff(before, renders), { search: 3 });
before = snap();
await act(async () => store.dispatch({ type: 'inventoryEvent', id: 'p2', stock: 4, version: 2 }));
console.log('socket p2 stock 5->4 : re-renders', JSON.stringify(diff(before, renders)), '|', text('[data-card=p2]'), '|', text('[data-detail]'));
assert.deepEqual(diff(before, renders), { 'card p2': 1, detail: 1 });
assert.equal(text('[data-card=p2]'), 'Lamp (4 left)'); assert.equal(text('[data-detail]'), 'detail p2: 4 left');
before = snap();
await act(async () => store.dispatch({ type: 'inventoryEvent', id: 'p2', stock: 9, version: 1 })); // older event arriving late
console.log('late socket event v1 : re-renders', JSON.stringify(diff(before, renders)), '|', text('[data-detail]'));
assert.deepEqual(diff(before, renders), {}); assert.equal(text('[data-detail]'), 'detail p2: 4 left');
await act(async () => { addToCart(api, 'p1'); }); // optimistic: visible before any response
console.log('add p1, no response :', text('b'), '| calls to server', api.calls);
assert.equal(text('b'), 'cart 1 / $12.00');
await act(async () => { addToCart(api, 'p2'); }); // second add while the first is still in flight
assert.equal(text('b'), 'cart 2 / $57.00');
await api.deliver(1); // responses arrive out of order: the newer one first
console.log('p2 reply first :', text('b'));
assert.equal(text('b'), 'cart 2 / $57.00');
await api.deliver(0); // the older reply is ignored (version <= confirmed)
console.log('p1 reply (older) :', text('b'));
assert.equal(text('b'), 'cart 2 / $57.00'); assert.deepEqual(store.get().cart.confirmed.qty, { p1: 1, p2: 1 });
await act(async () => { await addToCart(api, 'p3'); }); // server says out of stock: the optimistic op is removed
console.log('add p3 (out of stock) :', text('b'));
assert.equal(text('b'), 'cart 2 / $57.00 / out of stock');
await act(async () => { addToCart(api, 'p1'); }); // a second p1 add is pending while a different add fails
await act(async () => { await addToCart(api, 'p3'); });
console.log('p1 pending, p3 fails :', text('b'));
assert.equal(text('b'), 'cart 3 / $69.00 / out of stock'); // only the failed operation was removed
await api.deliver(0);
assert.equal(text('b'), 'cart 3 / $69.00 / out of stock'); assert.deepEqual(store.get().cart.confirmed.qty, { p1: 2, p2: 1 });
console.log('all assertions passed');
// ================= 5. the same socket event against denormalized state (each list and view holds its own copy)
const denorm = { list: [{ id: 'p2', stock: 5 }], detail: { id: 'p2', stock: 5 } };
const patched = { ...denorm, list: denorm.list.map((p) => (p.id === 'p2' ? { ...p, stock: 4 } : p)) }; // the author remembered the list only
console.log('denormalized : list says', patched.list[0].stock, 'but detail says', patched.detail.stock);
assert.notEqual(patched.list[0].stock, patched.detail.stock);
cleanup();
Reading the program in the order it runs:
- Section 1, the store.
reducerhandles five actions.listLoadedcopies each product intoproductsby id (merging with any copy already there) and stores only the ids inlists.inventoryEventreplacesstockandversionon one product, but only when the message's version is higher than the stored one.createStorekeepsstatein a variable, anddispatchnotifies subscribers only when the reducer returned a different object. - The cart actions.
cartAddStartedappends{ opId, id }toops, the pending operations: the record of an add the user made that the server has not yet confirmed.cartAddConfirmedreceives the server's whole cart,a.cart, which has aversion(how many changes the server has applied),qtyper product andapplied, the ids of the operations it already counts. It does two things: it removes fromopsevery operation listed inapplied, because the server now counts those, and it replacesconfirmedonly when the reply's version is newer than the one held. An older reply still prunesopsbut is not allowed to replaceconfirmed.cartAddFailedremoves just the failed operation and records the reason. - Derived values.
qtyOfis the confirmed quantity plus the number of pending operations for that product;cartCountandcartTotalsum it over all products. Nothing about the cart total is stored. - Section 2, the fake backend.
api.addToCartrejects at once when the product has no stock. Otherwise it updates the server's cart immediately (version plus one, quantity plus one, the operation id appended toapplied) and takes asnapshotof it. It returns a promise that stays unresolved: its resolver is pushed ontoapi.heldin call order.api.deliver(index)removes one resolver fromheldand calls it, sodeliver(1)releases the second call's reply before the first one's. - Section 3, the components.
useSel(selector)wrapsuseSyncExternalStore, React's hook for reading a store that lives outside React: it subscribes to the store and re-renders the component only when the selected value differs from last time.memo(React.memo) skips re-rendering a component whose props did not change.hit(name)counts how many times a component function runs, which is what the printed re-render numbers come from. - Section 4, the run.
act(...)from Testing Library runs the code inside it and applies the resulting React updates before returning, so the next line sees the updated screen.snapanddifftake the render counters before and after each step and keep only the differences.
Run in a node:22 container with the packages under "Running the code", it prints:
typing 3 chars : re-renders {"search":3}
socket p2 stock 5->4 : re-renders {"card p2":1,"detail":1} | Lamp (4 left) | detail p2: 4 left
late socket event v1 : re-renders {} | detail p2: 4 left
add p1, no response : cart 1 / $12.00 | calls to server 1
p2 reply first : cart 2 / $57.00
p1 reply (older) : cart 2 / $57.00
add p3 (out of stock) : cart 2 / $57.00 / out of stock
p1 pending, p3 fails : cart 3 / $69.00 / out of stock
all assertions passed
denormalized : list says 4 but detail says 5
The cart step by step
The cart section of the store after each step of the run (confirmed is the last server cart held; ops are the pending operations):
| Step | confirmed.version | confirmed.qty | confirmed.applied | ops | Badge |
|---|---|---|---|---|---|
| Start | 0 | {} | [] | none | cart 0 / $0.00 |
| Add p1, no reply yet | 0 | {} | [] | op1:p1 | cart 1 / $12.00 |
| Add p2, no reply yet | 0 | {} | [] | op1:p1, op2:p2 | cart 2 / $57.00 |
| Reply to the p2 call (server cart version 2) | 2 | {p1:1, p2:1} | [op1, op2] | none | cart 2 / $57.00 |
Older reply (version 1, applied [op1]) | 2 | {p1:1, p2:1} | [op1, op2] | none | cart 2 / $57.00 |
| Add p3, server rejects | 2 | {p1:1, p2:1} | [op1, op2] | none | cart 2 / $57.00 / out of stock |
The server handled the p2 call after the p1 call, so its cart already contained both adds when it replied. That is why the reply to the second call is enough to clear both pending operations, and why the late version-1 reply must not replace it: it describes the cart as it was before the p2 add. The badge is $57.00 because 1200 + 4500 = 5700 cents.
Reading the run
- Local state is isolated. Typing three characters re-rendered only
Search(3 renders). Nothing else subscribed to a changing value, so the cards, the badge and the detail view did not run. - Live inventory touches only what shows the changed entity. A socket message for product
p2re-rendered exactly one card and the detail view (one render each); the other cards stayed idle because their selectors returned the same primitive values. The detail view and the grid agree because they read one record. - Late message ignored. A message with version 1 arriving after version 2 caused no render and no change. With the version check removed the detail view flips to
9 leftand the assertion fails (the failing output is printed after this list). - Optimistic cart.
cart 1 / $12.00is on screen while the server has not yet replied (the server had received 1 call). The displayed quantity isconfirmed + pending operations, so there is no separate "optimistic copy" to keep in sync. - Out-of-order replies. Two adds were in flight; the reply to the second arrived first and carried both items (version 2). The older reply (version 1) was then ignored because its version is not newer than the confirmed cart. Without that check the badge drops to
cart 1 / $12.00(printed after this list). - Rejection and rollback. The out-of-stock add (
p3) was removed from the pending operations and an error shown; the cart stayed atcart 2 / $57.00(1200 + 4500 cents). Rolling back the operation list cannot clobber other pending adds, which a "restore the previous state" snapshot could. The last step of the run shows it: a second p1 add is still waiting for its reply when the p3 add fails, and the badge readscart 3 / $69.00 / out of stock(1200 + 4500 + 1200 = 6900 cents), so only the failed operation was removed. A failure handler that cleared every pending operation would pass the earlier steps, because nothing else was pending then, and fail this one. - Why normalization matters. The last line applies the same stock change to denormalized state, where the list and the detail view each hold a copy of the product. The author patched the list and forgot the detail copy: the list says 4 and the detail says 5. Every extra place a product is copied is one more place to forget.
What happens when each version check is removed
The two sed commands in the run instructions replace one condition with false. Run in the same container, the cart check removed (a.cart.version <= c.confirmed.version becomes false) prints, trimmed to the lines that matter:
p2 reply first : cart 2 / $57.00
p1 reply (older) : cart 1 / $12.00
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'cart 1 / $12.00'
- 'cart 2 / $57.00'
and the socket check removed (a.version <= cur.version becomes false) prints:
late socket event v1 : re-renders {"card p2":1,"detail":1} | detail p2: 9 left
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ {
+ 'card p2': 1,
+ detail: 1
+ }
- {}
In the first case the stale reply overwrote the version-2 cart with a cart that only knew about p1. In the second, the late version-1 message put stock: 9 back over the newer stock: 4.
Read and write paths
- Read (catalog): route params and URL filters decide the query, the response is written into the entity map plus a list of ids, components select what they need. Navigating from a list to a detail view shows the entity already in the store immediately and refetches the full record in the background.
- Read (inventory): the socket pushes
{ id, stock, version }. The reducer merges it into the entity if newer. A reconnect should refetch the visible products, because messages sent while disconnected are lost. - Write (cart): dispatch
cartAddStarted(optimistic), send the request with an operation id, then dispatch confirmed (the server's cart replaces the confirmed one) or failed (remove the operation, show the reason). - Checkout: never trust the optimistic cart or the displayed stock. The server re-validates stock and price at checkout and the UI renders its answer.
Trade-offs and pitfalls
- Normalization is not free. Writes must merge into the map, lists must be rebuilt from ids, and deleting an entity needs cleanup of every list that references it. If a record appears in only one place, keep it nested; normalize when the same record shows up in lists, detail views and the cart.
- Selectors must return stable values. Selecting a new array or object each call makes a component re-render on every store change; the run's counts come from selecting primitives (
title,stock,cartCount). - Do not put everything in the global store. The search draft lived in
useState, and the re-render count shows the benefit. Move state up only when a second component truly needs it. - Optimism has a limit. Add-to-cart is cheap to undo; payment is not and should show a pending state.
- This is one reducer, one fake backend and a handful of hand-ordered events. It demonstrates the data flow and its counts, not scale or latency.
Running the code
npm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16.0.1 @testing-library/dom@10.4.0 jsdom@25.0.1
node shop-state.mjs # prints the run above and "all assertions passed"
sed 's/a.cart.version <= c.confirmed.version/false/' shop-state.mjs > no-version-check.mjs && node no-version-check.mjs # fails: cart 1 / $12.00
sed 's/a.version <= cur.version/false/' shop-state.mjs > no-event-version.mjs && node no-event-version.mjs # fails: late event applied
sed 's/ops: s.cart.ops.filter((o) => o.opId !== a.opId)/ops: []/' shop-state.mjs > clear-all-ops.mjs && node clear-all-ops.mjs # fails: pending p1 add lost on a rejection
Save the listing as shop-state.mjs beside a package.json containing { "type": "module" }. Tested on node:22 (v22.23).
When you are handed a problem you have not seen before, how do you decide which family of technique it needs (for example, greedy versus dynamic programming, or memoization versus tabulation)? Walk through the signals you look for before you start coding, not just the eventual solution.
Sample Answer
Direct answer
Before writing any code, look for two structural signals: does the problem have overlapping subproblems and optimal substructure (an optimal solution is built from optimal solutions to smaller versions of itself)? If yes, it is a dynamic programming (DP) problem, not a greedy one. Within DP, whether you reach for memoization (caching recursive-call results, computed top-down) or tabulation (filling a table iteratively, bottom-up) is a secondary implementation choice, not a correctness question: both compute the same recurrence.
Structured elaboration
Signal 1: does a locally optimal choice guarantee a globally optimal one? Greedy algorithms make one irrevocable choice at each step and never reconsider it. That is only correct when the problem has the "greedy-choice property": committing to the best-looking option right now cannot make the final answer worse. You test this by trying to construct a counterexample where the locally-best choice forecloses a better global outcome (an exchange argument): if you can build one, greedy is wrong and you need DP; if every attempt to build a counterexample fails and you can sketch why (an exchange argument that any optimal solution can be rearranged to match the greedy choice without loss), greedy is likely correct.
Signal 2: overlapping subproblems and optimal substructure. If solving the problem for a larger input naturally requires solving the same smaller subproblem many times (for example, "the best way to reach state k" depends on "the best way to reach state k-1", but state k-1 also gets asked about from other paths), you have overlapping subproblems. If, in addition, an optimal solution to the whole problem is composed of optimal solutions to its subproblems (no locally-suboptimal subproblem answer can still lead to a globally optimal whole), you have optimal substructure. Both together mean DP applies: cache each subproblem's answer once, reuse it everywhere it recurs.
Signal 3: what does the recurrence look like? Write the recurrence in terms of "the answer for state X depends on the answer for smaller states Y, Z, ...", before touching code. If you can write this recurrence but it does not have an ordering where "smaller" always resolves before "larger" (a genuine dependency cycle), you likely need a different technique entirely (graph shortest-path with cycles, for instance).
Once you know it's DP: memoization vs tabulation. These are the same recurrence expressed two ways, not two different algorithms:
| Memoization (top-down) | Tabulation (bottom-up) | |
|---|---|---|
| Control flow | Recursive; caches results as encountered | Iterative; fills a table in dependency order |
| When it shines | Sparse state spaces where only some states are ever reached (a recursive call tree that naturally prunes) | Dense, regular state spaces (classic index-range DPs like coin change, edit distance) with a clear iteration order |
| Cost | Recursion/call overhead, hash-map lookups, risk of stack depth issues on deep recursion | No recursion overhead; better memory locality; can often drop to a rolling array to cut space |
| Downside | Deep or degenerate recursion can hit language recursion limits | Must work out a valid iteration order up front; may compute states you never needed |
Worked example
Take "minimum coins to make amount 6 from denominations {1, 3, 4}" (the coin change problem). The recurrence is: minCoins(a) = 1 + min(minCoins(a - c) for c in coins if c <= a), with minCoins(0) = 0. Overlapping subproblems are visible immediately: computing minCoins(6) needs minCoins(5), minCoins(3), minCoins(2); computing minCoins(5) also needs minCoins(2). minCoins(2) gets requested from two different callers, so caching it once and reusing it is exactly what turns an exponential naive recursion into a linear-in-target one. That overlap is the tell that this is DP, not greedy: a greedy "always take the largest coin" would take 4 then 1 then 1 (3 coins), while the true optimum is 3 + 3 (2 coins), because taking the largest coin first forecloses the better pairing, a real exchange-argument counterexample, confirming greedy is unsafe here and DP (with either memoization or tabulation) is required.
Trade-offs & pitfalls
Key points
- The most common mistake is reaching for greedy because a locally-best choice feels right; the discipline is to actively try to break it with a counterexample before trusting it, not to trust it by default.
- A DP recurrence existing does not by itself tell you whether to memoize or tabulate; that choice depends on whether the reachable state space is sparse (favors memoization) or dense with a clean iteration order (favors tabulation), and on language-specific recursion-depth limits.
- Some problems only look like DP: if there is no genuine overlap (each subproblem is only ever needed once), plain recursion or divide-and-conquer is simpler and DP's caching buys you nothing.
Complexity
- These are meta-level signals, not a specific algorithm, so there is no single complexity here; once you commit to DP, complexity is (number of distinct states) times (work per state), whether computed top-down with a cache or bottom-up with a table.
Edge cases
- A problem with optimal substructure but no overlapping subproblems (each subproblem solved once) does not need DP's memoization; plain recursion or divide-and-conquer suffices and adding a cache only adds overhead.
- A problem where you cannot write a clean dependency order for tabulation (irregular, data-dependent state transitions) may force memoization even in a dense-looking state space, since an explicit iteration order is hard to construct correctly.
What are over-fetching and under-fetching in client-server APIs, and how do REST and GraphQL each deal with them? Describe what a frontend or mobile client feels from each approach.
Sample Answer
Direct answer
Over-fetching means the response carries more data than the screen uses. Under-fetching means one response is not enough, so the client must make follow-up requests to assemble a screen. Both waste the client's time, data allowance and battery. REST fixes them by shaping resources and endpoints on the server: sparse fieldsets (a fields= parameter that lists the only fields the client wants, shown below), embedded related data, or screen-specific endpoints. GraphQL, a query language where the server publishes a schema (a typed list of every object and field a client may ask for), fixes them by letting the client name exactly the fields it wants in a single request, at the price of a heavier server and a harder caching story.
What each problem looks like
Take a feed screen. Each row shows a post title, the author's name and a thumbnail.
- Over-fetching.
GET /postsreturns the whole post: body text, tags, view counts, edit history. The row uses three fields. If each post is 2,000 bytes and a row needs about 100, a page of 20 rows downloads 20 x 2,000 = 40,000 bytes to render 20 x 100 = 2,000 bytes of content, a factor of 20. The phone also parses all of it as JSON (JavaScript Object Notation) and holds it in memory. - Under-fetching.
GET /postsreturnsauthorIdbut not the name. If the 20 posts have 3 distinct authors, the client makes 1 + 3 = 4 requests (the pattern is called N+1: one request for the list, then one more per distinct related item). The author lookups cannot start until the list has arrived, so the screen waits for at least two sequential network round trips (list, then authors), and each extra hop on a weak cellular link is a chance to stall.
How REST deals with it
REST (resources addressed by URL, standard HTTP verbs) has no built-in query language, so you shape responses with conventions:
- Sparse fieldsets:
GET /posts?fields=id,title,author.name,thumbnailUrl. - Embedding or inclusion:
GET /posts?embed=authororinclude=author, so related data rides along (JSON:API, a public REST convention, definesfields[TYPE]andincludeand requires400 Bad Requestwhen a server does not supportinclude). - Screen-shaped endpoints:
GET /screens/feed, which belongs to a Backend-for-Frontend (BFF, a server layer owned by the client team that returns exactly what one client needs).
How GraphQL deals with it
GraphQL exposes one typed schema. The client sends a query that names fields, and the response mirrors its shape:
{ posts(first: 20) { id title author { name } thumbnailUrl(width: 96) } }
Over-fetching disappears because only named fields come back. Under-fetching disappears because the nested author { name } is resolved on the server in the same request (a resolver is the server function that produces the value of one field, here the author's name). Per the GraphQL over HTTP documentation, servers must accept POST for queries and mutations (mutations are the GraphQL operations that write data) and may accept GET for queries only. A response can hold both data and errors, and a response with non-null data should still use a 2xx status, because HTTP has no status for partial success.
What the client feels
| Concern | REST with fieldsets / BFF | GraphQL |
|---|---|---|
| Bytes per screen | Small if the server implements shaping; fixed endpoints over-fetch for other screens | Small by construction, per query |
| Round trips | 1 with embeds or a screen endpoint, otherwise 1 + N (one list request plus one per related item) | 1 per screen query |
| Client CPU | Parses a small JSON; no query building | Parses a small JSON; a client library may normalize results into a cache (split each response into one record per object, keyed by id, so an author shared by many posts is stored once), and that splitting and merging costs CPU on low-end devices |
| CDN (content delivery network) caching | Easy: URL is the cache key, GET is cacheable | Hard with POST; possible with GET plus persisted query ids (short identifiers that replace long query text, which also avoids URL length limits) |
| Developer velocity | Frontend waits for a new field or endpoint if the shape is missing | Frontend adds a field to its own query, no backend ticket, if the schema already exposes it |
| Versioning | New fields are additive; breaking shapes need /v2 or negotiation | Add fields freely and mark old ones with the built-in @deprecated directive (an annotation on a schema field that tells tools and developers the field is going away); usage is visible per field |
| Error handling | HTTP status per request tells the story | Often HTTP 200 with an errors array and partial data, so clients must inspect the body |
Which screens feel it most
- Personalized feed: many small rows, several related entities per row (author, counts, reaction). Under-fetching dominates, so one composed request (GraphQL query or BFF endpoint) matters most.
- Settings screen: one small object, rarely changing. Plain REST is fine and caches well; GraphQL adds little.
- Analytics sync: the client uploads or downloads bulk data in the background. The cost is bytes and radio wake-ups (every time the phone's cellular radio leaves idle to send a request it draws extra battery, so many small requests cost more energy than one batched request), not flexible field choice. Batch it into one request and compress it; a query language is not the lever.
Pitfalls
- GraphQL does not remove over-fetching on the server: a resolver (the function that produces one field) may still load the whole database row. Field selection saves wire bytes, not necessarily database work.
- A permissive
fields=parameter can leak internal columns. Validate it against an allowlist. - Choosing GraphQL to fix under-fetching, then discovering that each nested field issues its own database query (the N+1 problem), swaps a client problem for a server one.
Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Frontend Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs