Junior Fullstack Developer Interview Preparation Guide - FAANG Standard
This guide is based on general FAANG interview practices and may not reflect specific company procedures.
FAANG companies typically conduct 5-7 interview rounds for Junior Fullstack Developer roles, progressing from initial recruiter screening through multiple technical evaluations (coding, system design fundamentals, and platform-specific skills) to behavioral assessments. The process evaluates coding proficiency, fullstack understanding, problem-solving approach, cultural fit, and learning potential. At the junior level, interviewers assess foundational competency, collaboration skills, and ability to write clean, maintainable code under guidance.
Interview Rounds
Recruiter Screening Call
What to Expect
Initial 30-minute conversation with a technical recruiter to assess background, motivation, and baseline technical understanding. The recruiter verifies your resume accuracy, discusses your fullstack experience, clarifies your career goals, and checks cultural fit. This round is primarily conversational and used to confirm you meet basic qualifications before proceeding to technical rounds.
Tips & Advice
Have your resume memorized with specific project details and dates. Be honest about your experience level and learning gaps. Prepare 2-3 elevator pitches about why you're interested in fullstack development and this company. Ask thoughtful questions about the team and project scope. Mention any relevant projects, internships, or coursework that demonstrates fullstack capabilities. Show enthusiasm for learning and growth opportunities. Avoid overselling junior-level skills.
Focus Topics
Technical Depth Self-Assessment
Honestly communicate your strongest and weakest areas. For example, 'I'm very comfortable with React and REST APIs, but less experienced with database optimization.' Being truthful prevents overcommitment and helps interviewers calibrate expectations.
Practice Interview
Study Questions
Motivation and Career Goals
Articulate why you want to work as a fullstack developer at this company specifically. Discuss what attracts you to the role, company culture, and how this opportunity fits your career trajectory as a junior developer seeking to grow.
Practice Interview
Study Questions
Learning Ability and Problem-Solving Mindset
Demonstrate curiosity, ability to learn new technologies independently, and how you approach problems you encounter. Share an example of learning something new for a project or overcoming a technical challenge.
Practice Interview
Study Questions
Core Fullstack Technologies
Brief overview of your proficiency with frontend technologies (HTML, CSS, JavaScript frameworks), backend technologies (server-side languages, APIs), and databases. Be honest about depth vs breadth at junior level.
Practice Interview
Study Questions
Background and Experience Summary
Clear articulation of your fullstack development journey, relevant projects, internships, and educational background. For junior level, focus on projects that demonstrate both frontend and backend work, including what technologies you used and what you learned.
Practice Interview
Study Questions
Technical Phone Screen - Coding Fundamentals
What to Expect
45-60 minute technical interview conducted over phone or video with a junior engineer or mid-level engineer. You'll solve 1-2 medium-difficulty coding problems related to data structures and algorithms in a shared coding environment (CoderPad, HackerRank, etc.). Focus is on problem-solving approach, code quality, and communication rather than flawless execution. Interviewers assess your ability to think through problems, write clean code, and ask clarifying questions.
Tips & Advice
Start by clarifying the problem statement, asking about edge cases and constraints before coding. Think out loud and explain your approach before implementing. Write clean, readable code with meaningful variable names. Test your solution with provided examples and edge cases. If stuck, explain your thought process and ask for hints rather than sitting silently. Time management is crucial—aim to spend 5 min understanding, 15-20 min coding, 5-10 min testing. Use a language you're most comfortable with. Don't overthink optimization at first; a working solution is better than an incomplete optimal one. Be humble if you make mistakes and show ability to debug.
Focus Topics
Stacks and Queues
Understanding LIFO and FIFO data structures and their applications. Junior-level problems include valid parentheses, next greater element, and simple backtracking patterns. Understanding when to use stacks vs queues and implementing them.
Practice Interview
Study Questions
Trees and Basic Graph Traversal
Understanding tree traversals (in-order, pre-order, post-order, level-order), basic tree problems, and simple graph concepts like BFS/DFS. Junior-level problems include tree height, finding paths, and basic connectivity problems.
Practice Interview
Study Questions
Linked Lists
Understanding linked list data structure, traversal, insertion, deletion, and manipulation. Junior-level problems include reversing linked lists, detecting cycles, merging lists, and finding elements. Requires understanding pointers/references and basic graph traversal concepts.
Practice Interview
Study Questions
Hash Maps and Sets
Using hash-based data structures to solve problems efficiently. Junior-level topics include counting frequencies, detecting duplicates, finding pairs that sum to target, and cache-like implementations. Understanding time/space trade-offs of hash-based solutions.
Practice Interview
Study Questions
Problem-Solving Communication and Code Quality
Ability to articulate your thought process, ask clarifying questions, and write clean code with meaningful variable names, proper indentation, and comments. Demonstrating debugging skills when issues arise and explaining your solution complexity.
Practice Interview
Study Questions
Array and String Manipulation
Problems involving searching, sorting, traversing, and manipulating arrays and strings. Common patterns include two-pointer technique, sliding window, and basic sorting. Junior-level problems in this area test fundamental understanding of indexing, iteration, and basic algorithms.
Practice Interview
Study Questions
Technical Interview 1 - Data Structures & Algorithms Deep Dive
What to Expect
60-90 minute in-person or virtual technical interview focused on advanced data structures and algorithmic problem-solving. You'll typically solve 1-2 medium to medium-hard problems with emphasis on optimization, complexity analysis, and handling edge cases. This round tests your ability to think through complex problems, optimize solutions, and explain trade-offs. Unlike the phone screen, here you're expected to demonstrate strong algorithmic thinking and the ability to handle follow-up questions and optimizations.
Tips & Advice
Thoroughly review LeetCode medium and some hard problems before this round. Focus on understanding patterns rather than memorizing solutions. When given a problem, spend 10-15 minutes discussing approach with interviewer before coding. Start with brute force, explain its complexity, then optimize. Write the most optimized solution possible. Test thoroughly including edge cases, empty inputs, and large inputs. Be prepared to discuss time and space complexity in Big O notation. If you get stuck, communicate clearly about where you're stuck and ask for hints. Show enthusiasm about problem-solving. Code should be production-quality: clean, well-organized, with error handling.
Focus Topics
Coding Interview Patterns and Meta-Strategies
Recognizing common patterns in interview problems (two-pointer, sliding window, backtracking, divide-and-conquer). Understanding how to approach unfamiliar problems systematically. Meta-strategies include clarifying requirements, starting simple, incrementally optimizing, and thorough testing.
Practice Interview
Study Questions
Sorting and Searching Algorithms
Understanding various sorting algorithms (merge sort, quick sort, heap sort), their complexities, and when to use each. Binary search variants and searching in modified arrays. Junior-level mastery of these algorithms and understanding tradeoffs.
Practice Interview
Study Questions
Dynamic Programming Fundamentals
Recognizing overlapping subproblems and optimal substructure. Junior-level DP problems include fibonacci variants, coin change, longest increasing subsequence, and basic knapsack problems. Understanding memoization and bottom-up approaches.
Practice Interview
Study Questions
Complexity Analysis and Optimization
Analyzing time and space complexity in Big O notation. Understanding when to optimize and trade-offs between time and space. Identifying bottlenecks and common optimizations like caching, early termination, and better data structures.
Practice Interview
Study Questions
Graph Algorithms and DFS/BFS
Graph representation (adjacency list, matrix), depth-first and breadth-first search, connected components, cycle detection, and topological sorting. Junior-level problems focus on traversal correctness and basic pathfinding rather than complex shortest-path algorithms.
Practice Interview
Study Questions
Binary Trees and Binary Search Trees
Deep understanding of tree structures, balanced vs unbalanced trees, BST properties, and various tree problems. Junior-level focus includes traversals, searching, insertion, deletion, lowest common ancestor, and validating BST. Understanding tree balancing concepts at high level.
Practice Interview
Study Questions
Technical Interview 2 - Frontend Development
What to Expect
60-90 minute technical interview focusing on frontend technologies and skills. You'll typically work on a frontend coding problem or build a small component from scratch using HTML, CSS, and JavaScript (usually with a framework like React). Problems may include building an interactive UI component, debugging existing code, or implementing specific functionality. This round assesses your ability to work with frontend technologies, understand UI/UX principles, implement responsive design, and write clean, maintainable frontend code.
Tips & Advice
Ensure you're very comfortable with your chosen frontend framework (React, Vue, Angular). Practice building components from scratch quickly. Review HTML semantic elements, CSS flexbox, and grid. Understand event handling, state management, and component lifecycle/hooks. Be prepared to discuss accessibility (a11y) and responsive design principles. Write clean, commented code that's easy to follow. Show understanding of component composition and reusability. If asked about performance, discuss optimization techniques. Practice in actual development environment you'd use in interview. Be prepared to debug existing code and explain what's wrong and how to fix it. Discuss user experience and edge cases in UI.
Focus Topics
Frontend State Management and Data Flow
Managing application state, prop drilling, lifting state up, and alternatives like Context API or state management libraries. Understanding data flow from parent to child components. Handling complex state updates.
Practice Interview
Study Questions
CSS Styling and Responsive Design
CSS fundamentals, flexbox, CSS grid, media queries, and responsive design principles. Understanding CSS specificity, cascading, and inheritance. Mobile-first approach and designing for various screen sizes. CSS preprocessing basics.
Practice Interview
Study Questions
HTML and Semantic Web Standards
HTML5 semantic elements, form controls, accessibility attributes (alt text, ARIA roles, labels), proper document structure. Understanding semantic HTML beyond just `<div>` tags. Basic validation and form handling.
Practice Interview
Study Questions
React Fundamentals (or chosen framework)
Components (functional and class-based), props and state management, hooks (useState, useEffect, useContext), component lifecycle, conditional rendering, lists and keys, and forms. Understanding when to use different hooks and component patterns. Basic understanding of performance optimization.
Practice Interview
Study Questions
JavaScript Fundamentals for Frontend
Core JavaScript concepts including ES6+ features (arrow functions, destructuring, spread operator, template literals), async/await, promises, closures, scope, and prototypes. Understanding event handling, DOM manipulation, and browser APIs. Junior-level mastery of modern JavaScript syntax and patterns used in frontend development.
Practice Interview
Study Questions
API Integration and Asynchronous Operations
Fetching data from APIs, handling loading and error states, implementing debouncing and throttling for API calls, understanding REST principles, handling authentication tokens, and managing side effects with useEffect or equivalent patterns.
Practice Interview
Study Questions
Technical Interview 3 - Backend Development & Databases
What to Expect
60-90 minute technical interview focusing on backend technologies, server-side logic, and database design. You'll typically work on designing a simple API endpoint, writing backend logic to solve a problem, optimizing a database query, or designing a basic schema for a given scenario. This round assesses your ability to work with server-side languages, understand REST API principles, design databases, and solve backend-specific challenges.
Tips & Advice
Be proficient in your backend language of choice (Node.js/JavaScript, Python, Java, etc.). Understand REST API principles and HTTP methods. Practice designing database schemas and writing queries. Review indexing concepts and basic query optimization. Be prepared to discuss trade-offs between SQL and NoSQL databases. Understand basic authentication and security concepts. Write clean, well-structured backend code. Be comfortable explaining API design decisions. Discuss error handling and validation. For Node.js specifically, understand async operations, middleware, and event-driven architecture. Practice using databases (SQL and NoSQL) in your projects before the interview.
Focus Topics
SQL and Database Query Optimization
Writing efficient SQL queries, understanding indexes, query execution plans, and basic optimization techniques. Understanding joins, subqueries, and aggregations. Recognizing N+1 query problems. Basic understanding of normalization and database design principles.
Practice Interview
Study Questions
Error Handling and Logging
Implementing try-catch blocks, returning appropriate error responses with meaningful messages, logging for debugging, and graceful error recovery. Understanding different error types and how to handle them appropriately. Debugging backend issues systematically.
Practice Interview
Study Questions
Authentication, Authorization, and Security
Basic authentication concepts (username/password), token-based authentication (JWT), session management, and authorization (who can do what). Understanding common security vulnerabilities like SQL injection and CSRF. Storing sensitive data securely.
Practice Interview
Study Questions
Database Schema Design and Relationships
Designing database schemas for given business requirements. Understanding primary keys, foreign keys, and relationships (one-to-one, one-to-many, many-to-many). Normalization concepts. Choosing between SQL and NoSQL for different use cases.
Practice Interview
Study Questions
Backend Language Proficiency
Strong working knowledge of chosen backend language (Node.js/JavaScript, Python, Java, etc.). Understanding language fundamentals, standard library usage, package management, and frameworks. Writing clean, maintainable backend code. Understanding language-specific patterns and best practices.
Practice Interview
Study Questions
REST API Design and HTTP
Designing RESTful APIs with proper resource modeling, HTTP methods (GET, POST, PUT, DELETE, PATCH), status codes, and request/response patterns. Understanding idempotency, stateless design, and API versioning. Handling pagination and filtering. JSON as data format.
Practice Interview
Study Questions
System Design Round - Basic Fullstack Architecture
What to Expect
45-60 minute technical interview focused on basic system design and architectural thinking. You'll be given a real-world problem or feature requirement and asked to design how you'd build it. This might be building a URL shortener, a simple social media feed, a real-time chat system, or similar. At junior level, focus is on understanding components (frontend, backend, database, caching), trade-offs between choices, and basic scalability thinking rather than complex distributed systems. Interviewers assess your ability to think architecturally about fullstack applications, make reasonable technology choices, and communicate your design clearly.
Tips & Advice
Start by clarifying requirements and constraints with the interviewer. Draw diagrams showing frontend, backend, database, and data flow. Discuss technology choices and trade-offs (SQL vs NoSQL, caching strategies, API design). At junior level, don't go too deep into distributed systems; focus on practical architecture. Discuss potential bottlenecks and how to address them. Think about scalability from the start but keep it realistic. Mention monitoring, logging, and error handling. Be prepared to evolve your design based on feedback. Practice drawing architectural diagrams. Use familiar technologies from your experience. Reference real systems you know to explain concepts.
Focus Topics
Deployment and Operations Basics
Understanding deployment process for fullstack applications, containerization basics (Docker), CI/CD concepts, and monitoring/logging requirements. Thinking about error tracking and performance monitoring.
Practice Interview
Study Questions
Caching Strategies
Understanding when to use caching, different cache types (in-memory, Redis, CDN), cache invalidation strategies, and potential cache coherency issues. Basic knowledge of cache hit ratios and performance impact.
Practice Interview
Study Questions
Scalability and Load Considerations
Understanding horizontal vs vertical scaling, load balancing, and database scalability (replication, sharding). At junior level, conceptual understanding rather than implementation details. Recognizing bottlenecks and basic mitigation strategies.
Practice Interview
Study Questions
Database Selection and Schema Design
Choosing between SQL and NoSQL based on requirements. Designing efficient schemas for queries your system needs. Understanding indexing strategy. Considering read/write patterns when designing schema.
Practice Interview
Study Questions
API Contract Definition and Data Models
Defining clear API contracts between frontend and backend. Designing request/response schemas. Normalizing data for JSON API responses. Understanding versioning and backward compatibility. Designing efficient data transfer.
Practice Interview
Study Questions
System Architecture Fundamentals
Understanding basic system components: frontend application, backend servers, databases, caching layers, and their interactions. Understanding client-server architecture, request/response flow, and component responsibilities. Designing fullstack systems with appropriate separation of concerns.
Practice Interview
Study Questions
Behavioral & Hiring Manager Round
What to Expect
45-60 minute interview combining behavioral assessment and role-specific discussion with the hiring manager or senior team member. This round evaluates cultural fit, teamwork, communication skills, growth mindset, and your ability to work in a collaborative engineering environment. You'll discuss past experiences using STAR method, ask insightful questions about the role and team, and demonstrate your interest in the fullstack developer position. This is also your opportunity to learn more about the team, projects, and company culture.
Tips & Advice
Prepare 5-7 specific stories about past experiences (projects, challenges, collaborations, failures, learning moments) using STAR method. Focus on stories demonstrating: learning from failures, collaborating with teammates, handling ambiguity, taking initiative, and adaptability. At junior level, emphasize willingness to learn, ability to work in teams, and growth mindset. Have thoughtful questions prepared about the team, projects, company engineering culture, and what success looks like in the role. Research the company thoroughly and reference specific projects or values in conversation. Show genuine enthusiasm about the opportunity. Be authentic and personable. Listen carefully to interviewer's responses and adapt. Avoid generic answers. At end, thank interviewer and express genuine interest if you have it.
Focus Topics
Communication and Technical Explanation
Ability to explain technical concepts clearly to different audiences, document work, communicate status and blockers, and listen actively to others. Demonstrated through how you answer questions and explain your background throughout interview.
Practice Interview
Study Questions
Initiative and Ownership
Demonstrate ability to take ownership of tasks, identify issues proactively, suggest improvements, and drive features to completion. Stories about going beyond assigned work, solving problems independently (with guidance as needed), or improving team processes.
Practice Interview
Study Questions
Interest in Fullstack Development and the Role
Demonstrate genuine interest in fullstack development specifically, understanding why it's valuable to work across both frontend and backend, interest in the specific company and team, and thoughtful questions about projects and growth opportunities.
Practice Interview
Study Questions
Handling Failure and Challenges
Discuss a significant professional challenge or failure, what you learned, and how you recovered. Show resilience, problem-solving approach, and ability to extract learning from difficult situations. Stories about bugs you couldn't initially fix, projects that went wrong, or difficult team situations.
Practice Interview
Study Questions
Growth Mindset and Learning Ability
Demonstrate intellectual curiosity, ability to learn new technologies quickly, comfort with challenges and mistakes as learning opportunities, and proactive self-improvement. Stories about picking up new frameworks, debugging complex problems, or overcoming skill gaps.
Practice Interview
Study Questions
Collaboration and Teamwork
Demonstrate ability to work effectively with team members, communicate clearly, accept feedback, and contribute to shared goals. Stories about pair programming, code reviews, helping teammates, or navigating team disagreements. Understanding that junior developers learn from and with their teams.
Practice Interview
Study Questions
Frequently Asked Full-Stack Developer Interview Questions
In Node.js using Express, outline middleware that verifies a Bearer JWT access token signed with RS256 by using a JWKS endpoint. Provide the high-level pseudocode, list error cases to handle (expired, malformed, unknown kid), and explain how to cache JWKS keys safely to avoid performance problems.
Sample Answer
Direct answer
An Express middleware that verifies a Bearer RS256 JWT (JSON Web Token) needs to: extract the token from the Authorization header, resolve the signing key by the token's kid from a JWKS (JSON Web Key Set) endpoint through a caching client rather than fetching on every request, verify the signature with the algorithm pinned to RS256, and map each distinct failure (missing header, malformed token, expired token, unknown kid) to a 401 response with its own machine-readable error code, so logs and clients can tell the failure modes apart instead of seeing one undifferentiated "unauthorized."
Structured elaboration (approach)
- Extraction: read
Authorization: Bearer <token>; a missing or malformed header is rejected before any verification work happens at all. - Key resolution with caching: use a JWKS client (
jwks-rsabelow) configured withcache: true, acacheMaxAge, andrateLimit: truewith a requests-per-minute ceiling. This matters specifically because a burst of requests can present several differentkidvalues in quick succession right after the identity provider rotates keys; without a cache, that burst becomes a burst of outbound calls to the JWKS endpoint, turning someone else's infrastructure into a dependency of your hot path. - Verification:
algorithms: ['RS256']is passed explicitly, the same defense used against algorithm-confusion attacks as in a Python implementation of the same idea, plusaudienceandissuerchecks and aclockTolerancefor clock-skew. - Error mapping:
TokenExpiredErrorbecomestoken_expired;JsonWebTokenError(which covers a malformed token and a bad signature) becomesinvalid_token; anything else, in practice the JWKS client's own "no signing key found for this kid" error, becomesunauthorized.
Worked example (executed)
"use strict";
const http = require("http");
const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const jwksClient = require("jwks-rsa");
// npm install jsonwebtoken jwks-rsa
const EXPECTED_ISSUER = "https://idp.example.com";
const EXPECTED_AUDIENCE = "orders-api";
function requireBearerJwt(client) {
function getKey(header, callback) {
client.getSigningKey(header.kid, (err, key) => {
if (err) return callback(err);
callback(null, key.getPublicKey());
});
}
return function (req, res, next) {
const authHeader = req.headers["authorization"] || "";
const match = /^Bearer (.+)$/.exec(authHeader);
if (!match) {
return res.status(401).json({ error: "missing_bearer_token" });
}
const token = match[1];
jwt.verify(
token,
getKey,
{
algorithms: ["RS256"],
audience: EXPECTED_AUDIENCE,
issuer: EXPECTED_ISSUER,
clockTolerance: 30,
},
(err, decoded) => {
if (err) {
if (err.name === "TokenExpiredError") {
return res.status(401).json({ error: "token_expired" });
}
if (err.name === "JsonWebTokenError") {
return res.status(401).json({ error: "invalid_token", detail: err.message });
}
return res.status(401).json({ error: "unauthorized", detail: err.message });
}
req.user = decoded;
next();
}
);
};
}
// --- test harness: real RSA keypair, real local JWKS HTTP server, 5 cases ---
function buildKeypairAndJwks() {
const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
const jwk = publicKey.export({ format: "jwk" });
jwk.kid = "test-key-1";
jwk.alg = "RS256";
jwk.use = "sig";
return { privatePem: privateKey.export({ format: "pem", type: "pkcs8" }), jwksDoc: { keys: [jwk] } };
}
function startJwksServer(jwksDoc) {
const body = JSON.stringify(jwksDoc);
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(body);
});
return new Promise((resolve) => {
server.listen(0, "127.0.0.1", () => {
const { port } = server.address();
resolve({ server, jwksUrl: `http://127.0.0.1:${port}/jwks.json` });
});
});
}
async function runCase(middleware, authHeaderValue) {
const req = { headers: { authorization: authHeaderValue } };
let nextCalled = false;
const settled = new Promise((resolve) => {
const res = {
_status: 200, _body: null,
status(code) { this._status = code; return this; },
json(body) { this._body = body; resolve(); return this; },
};
req._res = res;
middleware(req, res, () => { nextCalled = true; resolve(); });
});
await settled;
const res = req._res;
return { nextCalled, status: res._status, body: res._body, user: req.user };
}
async function main() {
const { privatePem, jwksDoc } = buildKeypairAndJwks();
const { server, jwksUrl } = await startJwksServer(jwksDoc);
const client = jwksClient({
jwksUri: jwksUrl, cache: true, cacheMaxEntries: 5,
cacheMaxAge: 10 * 60 * 1000, rateLimit: true, jwksRequestsPerMinute: 10,
});
const middleware = requireBearerJwt(client);
const now = Math.floor(Date.now() / 1000);
const basePayload = { sub: "user-42", iss: EXPECTED_ISSUER, aud: EXPECTED_AUDIENCE };
const validToken = jwt.sign(basePayload, privatePem, { algorithm: "RS256", keyid: "test-key-1", expiresIn: 300 });
const expiredToken = jwt.sign({ ...basePayload, iat: now - 1000, exp: now - 700 }, privatePem,
{ algorithm: "RS256", keyid: "test-key-1" });
const unknownKidToken = jwt.sign(basePayload, privatePem, { algorithm: "RS256", keyid: "does-not-exist", expiresIn: 300 });
const malformedToken = "not-a-jwt-at-all";
const results = [];
const r1 = await runCase(middleware, `Bearer ${validToken}`);
results.push(["valid token calls next() with req.user", r1.nextCalled && r1.user && r1.user.sub === "user-42"]);
const r2 = await runCase(middleware, `Bearer ${expiredToken}`);
results.push(["expired token -> 401 token_expired", !r2.nextCalled && r2.status === 401 && r2.body.error === "token_expired"]);
const r3 = await runCase(middleware, `Bearer ${malformedToken}`);
results.push(["malformed token -> 401", !r3.nextCalled && r3.status === 401]);
const r4 = await runCase(middleware, `Bearer ${unknownKidToken}`);
results.push(["unknown kid -> 401", !r4.nextCalled && r4.status === 401]);
const r5 = await runCase(middleware, "");
results.push(["missing bearer header -> 401 missing_bearer_token", !r5.nextCalled && r5.status === 401 && r5.body.error === "missing_bearer_token"]);
let allPass = true;
for (const [name, passed] of results) {
console.log(`[${passed ? "PASS" : "FAIL"}] ${name}`);
if (!passed) allPass = false;
}
console.log(`\nALL_PASS=${allPass}`);
server.close();
}
main();
Output, from an actual run (node verify_jwt_middleware.js):
[PASS] valid token calls next() with req.user
[PASS] expired token -> 401 token_expired
[PASS] malformed token -> 401
[PASS] unknown kid -> 401
[PASS] missing bearer header -> 401 missing_bearer_token
ALL_PASS=true
Complexity and edge cases
Excluding a JWKS cache miss (one HTTP round trip), each request costs one RSA signature verification and a handful of claim comparisons, O(1) in the number of requests. The three named error cases plus a missing-header case are exercised directly above: expired token, malformed token, and unknown kid all resolve to a 401 with a distinct error code rather than an unhandled exception or a generic 500, and each is tested against a real signature so the failure is genuine, not simulated by mocking the verification step itself.
Trade-offs and pitfalls
- Don't collapse "the credential is missing" and "the credential is invalid" into identical log output; both end up as a
401, but a client integration bug (forgetting the header) looks nothing like a compromised or expired token in an incident review, and conflating them in logs erases that distinction. - The JWKS client's cache has a maximum entry count; under a fleet-wide key rotation with many keys active simultaneously, a low limit can evict entries that are still legitimately in use, causing avoidable cache misses. Size it against how many keys the identity provider actually keeps active concurrently, not against a copied default.
getKeybeing asynchronous means a slow, uncached key lookup adds real latency to that one request, not to the whole server, but "not blocking everyone else" is a much lower bar than "fast." The cache configuration is what actually keeps the common case fast, not the mere fact that the lookup is async.
What would make you excited to take this specific role, even on a difficult day?
Sample Answer
Direct answer
Name two or three sources of engagement that are durable, ownership of a real problem, autonomy to fix something broken, seeing your work actually used, because those are what survive a bad day, unlike novelty or initial excitement, which don't.
The framework
- Separate fragile excitement from durable motivation: prestige, initial novelty, and a strong first impression wear off; ownership of an outcome, autonomy, and a teammate depending on you tend not to.
- Contrast durable motivators with compensation explicitly: this question is implicitly testing whether your engagement is pay-dependent, if the work is only worth doing because of the paycheck, a bad day has nothing to pull you back, so naming non-comp durable motivators directly answers what's being tested.
- Acknowledge that bad days are real rather than claiming immunity to them; naming what specifically pulls you through one is more credible than implying you never have them.
- Tie the durable motivator to something concrete about this specific role's day-to-day, not a generic value that would apply anywhere.
Worked example
On a genuinely hard day earlier in my career, a project I owned hit a frustrating, unglamorous problem that took much longer than planned to actually fix. What got me back in the next morning wasn't excitement about the company, it was that the problem was mine to solve and a teammate was blocked on it; finishing it meant something specific and immediate, not abstract. That's the kind of motivator I'm looking for in this role too: a defined area of ownership where the work is visibly mine and visibly used, not just a mission statement I agree with in the abstract.
Trade-offs and pitfalls
| Weak pattern | Strong pattern |
|---|---|
| Naming only external motivators (perks, pay, prestige) | Naming ownership, autonomy, and visible use of your work |
| Claiming you never have bad days | Acknowledging bad days and naming what specifically pulls you through |
| A motivator generic enough to apply to any employer | A motivator tied to something concrete in this role's actual day-to-day |
| Implying money doesn't matter at all | Contrasting durable motivators with pay explicitly, without dismissing pay |
An answer built entirely on external motivators invites the obvious follow-up about leaving for more money, while an answer that claims total immunity to bad days reads as unconvincing; the credible middle ground names something specific that held up under a real bad day.
You're designing a user-profile service requiring flexible attributes, low-latency reads for 100M users, and occasional complex analytics queries. Compare using a relational DB versus a document NoSQL store for serving the profile API. Discuss data modeling, consistency, read and write patterns, caching needs, operational cost, and a migration path that supports both fast reads and analytics workloads.
Sample Answer
Direct answer
Serve the profile API from a document-oriented NoSQL store (DynamoDB or MongoDB, either fits this shape) rather than a relational database, because flexible per-user attributes and low-latency reads at 100 million users are exactly what a document store's native partitioning and schemaless record shape were built for. Never make that same store answer the "occasional complex analytics" requirement directly: feed a change-data-capture (CDC, a stream of every insert/update/delete as it happens) pipeline into a columnar analytical warehouse instead, so analytical scans never compete with the serving path for resources.
Structured elaboration
Why document over relational for the serving path. A relational schema for "flexible attributes" forces a choice between a wide, mostly-empty table (most columns null for most users, wasting storage and confusing every query planner statistic) or a key-value attribute table (user_id, attribute_name, attribute_value), which turns every profile read into a self-join and reintroduces exactly the problem a document store solves natively. A document model stores each user's profile, whatever shape it happens to have, as one self-describing record. Reading one profile is one partition read, not a join.
Data modeling. One document per user, keyed by user_id. Embed attributes that are almost always read together with the base profile (display name, avatar, preference flags); keep unbounded, ever-growing collections (activity history, full audit log) out of the profile document entirely, in a separate store keyed by user_id plus a time or sequence component, so the profile document itself stays small and cheap to read.
Consistency. The UX moment that matters is "I just edited my profile, does the app show my edit." That needs read-your-writes on the write path: use a strongly consistent read (DynamoDB's ConsistentRead=true, or MongoDB's read preference set to the primary) immediately after a write, and fall back to eventually consistent reads everywhere else, including any read replicas, since a moment of staleness on someone else's profile view is not user-visible or harmful.
Read and write pattern. The stated shape is read-heavy: 100 million users implies far more profile views than profile edits. That is the textbook case for a cache-aside layer.
Caching. Put Redis in front as a cache-aside layer: a read checks Redis first, falls through to the document store on a miss and populates the cache, and a write invalidates (or updates) the cached copy. A time-to-live (TTL, an automatic expiration the cache enforces) bounds how stale an uninvalidated entry can get as a safety net.
Operational cost. A managed document store's cost scales with actual request volume and storage, which is usually cheaper at this DAU-driven traffic shape than provisioning a relational read-replica fleet sized for the same peak, because the document store's partitioning is native and automatic rather than a fleet you provision and rebalance by hand.
Migration path that keeps both fast reads and analytics workable. Do not synchronously dual-write to both the serving store and the warehouse; that couples the two systems' availability and adds write latency to the serving path for no serving-path benefit. Instead, stream every change out of the serving store (DynamoDB Streams, or MongoDB Change Streams) asynchronously into the warehouse. The serving path stays fast and simple; the warehouse eventually reflects every change (typically within seconds), which is exactly what "occasional complex analytics" can tolerate.
Worked example
The instinct at "100 million users" is to assume enormous QPS (queries per second). Working the number through from a realistic daily-active fraction shows the opposite, and shows why the cache-aside layer does most of the real work.
# profile-read QPS and cost at 100M registered users.
users = 100_000_000
daily_active_fraction = 0.06 # 6% DAU/registered ratio, a reasonable consumer-app assumption
dau = users * daily_active_fraction
views_per_session = 4 # own profile + a few others viewed per session
daily_reads = dau * views_per_session
avg_qps = daily_reads / 86400
peak_concentration = 9 # traffic is not uniform across 24h; a peak-hour multiplier
peak_qps = avg_qps * peak_concentration
cache_hit_rate = 0.85
peak_origin_qps = peak_qps * (1 - cache_hit_rate)
print(f"DAU = {dau:,.0f}")
print(f"avg qps (all reads) = {avg_qps:,.0f}")
print(f"peak-hour qps (all reads) = {peak_qps:,.0f}")
print(f"peak qps actually reaching the document store after {cache_hit_rate:.0%} cache hit rate = {peak_origin_qps:,.0f}")
# DAU = 6,000,000
# avg qps (all reads) = 278
# peak-hour qps (all reads) = 2,500
# peak qps actually reaching the document store after 85% cache hit rate = 375
Two hundred and seventy-eight average, 2,500 peak, 375 peak at the origin store after caching: at 100 million registered users, that is a modest number for a document store built to handle tens of thousands of QPS per table. The real engineering problem this design has to solve is not raw throughput, it is p99 (99th-percentile) latency per request and cache-invalidation correctness on writes, and both of those are solved by the read-your-writes rule above, not by adding capacity.
Trade-offs & pitfalls
- Assuming "100 million users" implies enormous sustained load. It usually does not; work the DAU and session-shape assumptions through explicitly before sizing anything, and be ready to defend the assumptions, not the headline user count.
- Letting the analytics requirement pull the serving-path schema toward a relational, join-friendly shape "just in case." That is optimizing the 99% of traffic (serving) for the 1% of traffic (analytics), and it is exactly backwards; let the CDC pipeline and the warehouse absorb the analytical shape instead.
- Synchronous dual-writing to the warehouse. It seems simpler than a CDC pipeline but couples serving-path write latency and availability to the warehouse's, which defeats the entire point of separating the two workloads.
- Skipping the read-your-writes rule to save cost. It is tempting to serve every read eventually consistent for the lower price, but "I just saved my profile and it looks unsaved" is a support ticket generator; pay the strong-read cost only on the specific post-write read, not globally.
- Unbounded arrays embedded in the profile document (an ever-growing activity log, for example) quietly turn a cheap single-partition read into an expensive, growing one over a user's lifetime. Keep growth-shaped data in its own store from day one.
Implement run_length_encode(s) and run_length_decode(encoded) in Java or Python for a backend that compresses repeated character sequences in logs. Your encode should compress runs (e.g., 'aaabb' -> 'a3b2') and decode should invert it. Discuss how to handle counts exceeding single digits and when run-length encoding is inappropriate.
Sample Answer
Direct answer
Use a character-then-count convention instead ('aaabb' becomes 'a3b2'): scan once, emitting each run's character followed by its length as an ordinary decimal number, so a run of 12 becomes 'a12' automatically, no extra logic needed for multi-digit counts beyond ordinary integer-to-string conversion. Decoding reads one character, then greedily consumes every digit that follows as its count. Run-length encoding stops being a good idea once the data has little run structure, or, more sharply, once the alphabet itself can contain digit characters, the second case does not just compress poorly, it can silently corrupt the decode.
Structured elaboration
Encoding and decoding. run_length_encode walks the string tracking the current run's length; on each boundary it emits char + str(run_length). run_length_decode reads one character, then reads forward while the next characters are digits, converts that digit run to an integer, and repeats the character that many times. Because Python's str(count) and int(digit_string) both handle any number of digits, a run of 100 encodes and decodes exactly as cleanly as a run of 3, no special-casing needed for the count's width.
When run-length encoding is inappropriate, as the question asks directly:
- Low-redundancy data. Diverse text with few or no repeated runs can nearly double in size under this encoding, the same argument as the sibling count-then-character convention, just confirmed again below for this format.
- An alphabet containing digit characters. This is not merely slower, it is a genuine decode-time ambiguity: a digit that is data becomes indistinguishable from a digit that is part of a count, demonstrated concretely below.
- Data needing random access. Finding the character at an arbitrary offset requires decoding sequentially from the very start; there is no way to jump directly to position 10,000 in the encoded form.
- Already-compressed or encrypted data. Neither retains any run structure, so applying run-length encoding on top typically expands the data further rather than shrinking it.
Worked example
def run_length_encode(s: str) -> str:
if not s:
return ""
result = []
i, n = 0, len(s)
while i < n:
j = i
while j < n and s[j] == s[i]:
j += 1
result.append(s[i] + str(j - i))
i = j
return ''.join(result)
def run_length_decode(encoded: str) -> str:
result = []
i, n = 0, len(encoded)
while i < n:
char = encoded[i]
i += 1
j = i
while j < n and encoded[j].isdigit():
j += 1
count = int(encoded[i:j])
result.append(char * count)
i = j
return ''.join(result)
print(f"run_length_encode('aaabb') = {run_length_encode('aaabb')!r}")
print()
t12 = "a" * 12 + "b"
enc12 = run_length_encode(t12)
dec12 = run_length_decode(enc12)
print(f"run of 12: {t12!r} -> {enc12!r} -> {dec12!r} roundtrip_ok={dec12 == t12}")
t100 = "z" * 100
enc100 = run_length_encode(t100)
dec100 = run_length_decode(enc100)
print(f"run of 100: 'z'*100 -> {enc100!r} -> roundtrip_ok={dec100 == t100}")
print()
t_digits = "aaa111"
enc_digits = run_length_encode(t_digits)
dec_digits = run_length_decode(enc_digits)
print(f"alphabet-with-digits case: {t_digits!r} -> encoded {enc_digits!r}")
print(f"decoded length = {len(dec_digits)} (expected {len(t_digits)})")
print(f"roundtrip preserved original: {dec_digits == t_digits}")
print()
worst = "abcdefgh"
enc_worst = run_length_encode(worst)
print(f"worst case, no repeats: {worst!r} (len {len(worst)}) -> {enc_worst!r} (len {len(enc_worst)})")
Output:
run_length_encode('aaabb') = 'a3b2'
run of 12: 'aaaaaaaaaaaab' -> 'a12b1' -> 'aaaaaaaaaaaab' roundtrip_ok=True
run of 100: 'z'*100 -> 'z100' -> roundtrip_ok=True
alphabet-with-digits case: 'aaa111' -> encoded 'a313'
decoded length = 313 (expected 6)
roundtrip preserved original: False
worst case, no repeats: 'abcdefgh' (len 8) -> 'a1b1c1d1e1f1g1h1' (len 16)
'aaabb' encodes to 'a3b2' exactly as given. A run of 12 correctly encodes as 'a12', and a run of 100 as 'z100', confirming multi-digit counts need no special handling. The digit-alphabet case is the sharpest, fully reproduced result here: 'aaa111' (three a's, then three 1's) encodes to 'a313' ('aaa' -> 'a3', '111' -> '13', concatenated). Decoding 'a313' reads the character 'a', then greedily consumes every following digit, '3', '1', '3', as one combined count, and returns 'a' repeated 313 times, a 313-character string, not the original 6-character input. This is an actual, executed failure, not a hypothetical one: the run boundary between the 'a' run and the '1' run was silently destroyed by the encoding itself.
Trade-offs and pitfalls
The digit-alphabet bug above is the sharpest interview signal in this sub-area: naming the fix matters more than the exposure itself. Options include reserving a delimiter character between the character and its count that cannot appear in the source alphabet, escaping digit characters specially before encoding, or simply documenting the scheme as invalid for any alphabet containing digits and validating that precondition before calling it.
Random access remains the wrong-tool problem regardless of compression ratio: even on genuinely repetitive data, if the access pattern needs "the character at position 10,000" without decoding everything before it, run-length encoding is the wrong structure on its own, a different indexed structure, or a hybrid with periodic decode checkpoints, is needed instead.
This character-then-count convention and the count-then-character convention are both valid design choices on their own; the trade-off is between them, not a correctness question of one over the other. What is a genuine bug is mixing the two conventions within one system, or assuming an encoder and decoder from different sources agree on which one is in use.
Draft a concise API contract (endpoints, request/response examples, and audit behavior) for an internal feature-flagging service used by multiple teams. Include endpoints for creating a flag, evaluating a flag on a low-latency path, toggling a flag, and retrieving audit logs. Note the performance and safety considerations your schema choices need to account for.
Sample Answer
A feature-flag service's contract centers on one asymmetry: the evaluate path is read constantly, on a hot path, by every service that checks a flag, while create/toggle/audit are low-volume management operations. The contract should reflect that asymmetry directly in its shape, not just in the implementation behind it.
The four endpoints
Create a flag (POST /flags): accepts a flag key, a human-readable description, and a default value, and returns the created flag's identifier and current state. This is a low-frequency, administrative operation, so its response can afford to be verbose (full flag metadata) without any latency concern.
Evaluate a flag (GET /flags/{key}/evaluate?context=...): the hot path. The request carries an evaluation context (user ID, environment, or other targeting attributes); the response should be as small as possible, essentially just the resolved boolean or variant value, because this call happens on every request path that checks the flag and any extra payload weight is paid millions of times over.
Toggle a flag (PATCH /flags/{key}): flips a flag on or off (or changes its targeting rules), and should return the new state plus a version or timestamp so a caller can confirm the toggle actually took effect and see what it changed from.
Retrieve audit logs (GET /flags/{key}/audit): returns a paginated history of who changed the flag, when, and what the before/after state was, which is the accountability trail for a service that can change application behavior without a code deploy.
Worked example: the evaluate response shape
{
"flag_key": "new_checkout_flow",
"value": true,
"reason": "targeting_rule_match"
}
Compare that to a create response, which can be much richer:
{
"flag_key": "new_checkout_flow",
"description": "Enables the redesigned checkout flow for eligible users",
"default_value": false,
"created_at": "2026-07-28T12:00:00Z",
"version": 1
}
The evaluate response is deliberately minimal (three small fields); the create response can afford ten times the payload because it runs orders of magnitude less often.
Performance and safety considerations the schema has to account for
- Evaluate must be cacheable and fast to parse, so its schema stays flat and small; nesting a full targeting-rule explanation into every evaluate call would add latency to the busiest path in the system for the sake of a debugging convenience almost nobody needs on every call.
- Toggle must be auditable by construction, not as an afterthought: every toggle response including a version number means a caller (and the audit log) can always answer "what did this flag look like immediately before this specific change."
- The evaluation context in the evaluate request needs a stable, documented shape (which attributes are supported for targeting) so that adding a new targeting dimension later is an additive, backward-compatible schema change, not a breaking one for every existing caller.
Trade-offs and pitfalls
The most common mistake is putting all four operations behind one uniform, verbose response schema for consistency's sake, which quietly taxes the highest-traffic endpoint (evaluate) to make the lowest-traffic ones (create, audit) marginally easier to read. A feature-flag contract earns its keep specifically by treating "how often is this called" as a first-class input into how big its response is allowed to be.
Describe a time you had to explain the same technical concept to a stakeholder more than once because they did not grasp it the first time. How did you adjust your approach the second time, and how did you keep the conversation from feeling condescending?
Sample Answer
Direct answer
The second explanation almost never wins by being louder or more detailed than the first. It wins by changing the format, meaning I switch from telling to showing, and by rooting the explanation in a decision the person actually needs to make rather than in the mechanics of the tool itself. To avoid condescension, I treat the first miss as information about my explanation, not about their ability.
Structured elaboration
When a first explanation does not land, I go through a specific adjustment process rather than just repeating myself more slowly:
- Diagnose what actually did not land, by asking a targeted question rather than re-explaining immediately. Usually the gap is one of three things: the vocabulary I used, the lack of a concrete example, or the fact that I explained the mechanism instead of the decision it enables.
- Change the format, not just the pace. If the first pass was verbal, the second pass gets a visual or a live walkthrough. If the first pass was abstract, the second pass starts from a specific, real example the person already cares about.
- Anchor the explanation in a decision they need to make, not in how the underlying system works. People retain "here is what you do when you see X" far better than "here is how X is calculated."
- Check understanding by having them use it themselves, not by asking if it makes sense. Watching someone operate the thing and narrate their reasoning out loud surfaces exactly where the model in their head diverges from reality.
To avoid condescension, I frame the second attempt as "let me show you a different way to look at this" rather than "let me try explaining this more simply," and I never reference the fact that this is a repeat explanation in front of other people.
Worked example
I owned a dashboard that tracked monthly customer churn, acquisition channel, and cohort value for Product and Customer Success managers, most of whom were not technical. After my first walkthrough, several of them still could not use it to decide which customers to prioritize for retention outreach; they nodded along in the room but did not use it afterward.
For the second attempt, I changed three things. First, storytelling: instead of walking through the chart types, I opened with a real scenario, "we're seeing a spike in churn from one acquisition channel this quarter, here is what that costs us and how we'd catch it," and used the dashboard to answer that story as it unfolded. Second, guided filters: rather than describing the filters, I handed them the dashboard and had each person isolate a cohort and change the date range themselves while I coached, so the tool's behavior stopped being something I described and became something they had just done. Third, annotated visuals: I added in-dashboard annotations next to each chart naming the business question it answers, so the connection between a chart and a decision was visible without me being in the room. Afterward, I gave each person a short realistic scenario and had them talk through, using the dashboard, what they would do, which told me directly whether the explanation had landed rather than relying on their saying it made sense.
Trade-offs and pitfalls
- Switching format on the second attempt costs more preparation time than repeating yourself; it is worth it specifically because a second identical explanation rarely succeeds where the first one failed for the same underlying reason.
- Anchoring purely in decisions can under-explain the tool for a stakeholder who later needs to use it in a situation you did not walk through. If the audience needs durable independence, not just one correct decision, the mechanism has to come back in briefly, just after the decision framing rather than before it.
- The biggest condescension risk is not tone, it is implying the person should have understood the first time. Framing the second pass as offering a different angle, rather than a simpler one, avoids that without softening the actual content.
- Hands-on practice only works if you can tolerate the person making a visible mistake in front of you or others; rushing to correct every misstep undercuts the exact learning-by-doing effect you are relying on.
List common off-by-one mistakes and mid-calculation errors that cause binary search implementations to loop infinitely or return incorrect indices. For each mistake give a short example input that breaks the incorrect implementation and explain the root cause.
Sample Answer
The idea in plain words
A binary search is a loop that keeps a window [lo, hi] of positions where the target could still be, and shrinks it using the middle element. Almost every bug is a mismatch between three choices that must agree: what the window means (does hi point at a real candidate, or one past the end?), when the loop stops (lo <= hi or lo < hi), and how the window shrinks (mid + 1, mid - 1, or mid). A mismatch skips a candidate, or leaves the window the same size so the loop never ends.
The correct closed-window version has this invariant, in words: if the target is in the list, it is somewhere in a[lo..hi], both ends included. The loop runs while the window is non-empty (lo <= hi), and each step removes mid from the window, so it must shrink.
The programs
Buggy functions 1 to 5 below each change one thing from correct; 6 and 7 are first-occurrence and last-occurrence searches with one thing wrong. To make an endless loop visible instead of hanging the program, the runner passes a list subclass that raises an error after 100 reads (Looping); a correct search on these tiny lists never gets near that. In Guarded, the method __getitem__ is what Python calls for every a[i], so each read adds one to reads, and super().__getitem__(i) then does the ordinary list read. The block that prints the int32 line runs the midpoint formula over a virtual sorted array of two billion items (nothing is stored: the value at index i is just i), with a function that wraps the sum the way a signed 32-bit integer does.
import itertools
class Looping(Exception):
pass
class Guarded(list):
"""A list that raises Looping after too many reads, so an infinite loop shows up as an error."""
reads = 0
def __getitem__(self, i):
self.reads += 1
if self.reads > 100:
raise Looping("more than 100 reads")
return super().__getitem__(i)
def correct(a, t): # closed window [lo, hi]; invariant: t, if present, is in a[lo..hi]
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_strict_loop(a, t): # 1. 'lo < hi' with a closed window
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_lo_equals_mid(a, t): # 2. 'lo = mid' never shrinks the window
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid
else:
hi = mid - 1
return -1
def bug_hi_equals_mid(a, t): # 3. 'hi = mid' with a closed window
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid
return -1
def bug_hi_is_len(a, t): # 4. hi = len(a) but the loop treats hi as inclusive
lo, hi = 0, len(a)
while lo <= hi:
mid = lo + (hi - lo) // 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def bug_float_mid(a, t): # 5. '/' instead of '//' in Python 3
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) / 2
if a[mid] == t:
return mid
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
return -1
def first_ge(a, t): # reference: first index with a[i] >= t
return next((i for i, x in enumerate(a) if x >= t), len(a))
def bug_first_occurrence(a, t): # 6. half-open window but 'hi = mid - 1'
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] >= t:
hi = mid - 1
else:
lo = mid + 1
return lo
def last_le(a, t): # reference: last index with a[i] <= t, or -1
return max((i for i, x in enumerate(a) if x <= t), default=-1)
def bug_last_occurrence(a, t): # 7. 'lo = mid' needs the upper middle, but mid rounds down
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] <= t:
lo = mid
else:
hi = mid - 1
return lo if a and a[lo] <= t else -1
def first_ge_fixed(a, t): # half-open window: hi = mid keeps a possible answer
lo, hi = 0, len(a)
while lo < hi:
mid = lo + (hi - lo) // 2
if a[mid] >= t:
hi = mid
else:
lo = mid + 1
return lo
def last_le_fixed(a, t): # closed window, 'lo = mid' paired with the upper middle
lo, hi = 0, len(a) - 1
while lo < hi:
mid = lo + (hi - lo + 1) // 2
if a[mid] <= t:
lo = mid
else:
hi = mid - 1
return lo if a and a[lo] <= t else -1
def run(fn, a, t):
try:
return fn(Guarded(a), t)
except Looping:
return "infinite loop"
except Exception as e:
return type(e).__name__
def to_int32(x):
x &= 0xFFFFFFFF
return x - (1 << 32) if x >= (1 << 31) else x
def search_virtual(n, target, midpoint):
"""Binary search over the virtual sorted array [0, 1, ..., n-1]."""
lo, hi = 0, n - 1
steps = []
while lo <= hi:
mid = midpoint(lo, hi)
steps.append((lo, hi, mid))
if mid < 0:
return "negative index " + str(mid), steps
if mid == target:
return mid, steps
if mid < target:
lo = mid + 1
else:
hi = mid - 1
return -1, steps
cases = [
("1 strict loop ", bug_strict_loop, [1, 3, 5], 5),
("1 strict loop ", bug_strict_loop, [4], 4),
("2 lo = mid ", bug_lo_equals_mid, [1, 3], 3),
("3 hi = mid ", bug_hi_equals_mid, [1, 3], 0),
("4 hi = len(a) ", bug_hi_is_len, [1, 3, 5], 9),
("5 mid = (lo+hi)/2 ", bug_float_mid, [1, 3, 5], 3),
]
for name, fn, a, t in cases:
print(f"{name} a={a} target={t}: buggy={run(fn, a, t)} correct={correct(a, t)}")
for name, fn, ref, a, t in [
("6 first, hi=mid-1 ", bug_first_occurrence, first_ge, [1, 2, 3, 3], 3),
("7 last, lo=mid ", bug_last_occurrence, last_le, [1, 2], 2),
]:
print(f"{name} a={a} target={t}: buggy={run(fn, a, t)} correct={ref(a, t)}")
# Every non-decreasing list of length 0..5 over the values 0..3, with targets -1..4.
inputs = [(list(c), t) for n in range(6)
for c in itertools.combinations_with_replacement(range(4), n) for t in range(-1, 5)]
print("\ninputs per check:", len(inputs))
def fails(fn, expect):
bad = 0
for a, t in inputs:
got = run(fn, a, t)
bad += got != expect(a, t)
return bad
for name, fn in [("correct", correct), ("bug 1", bug_strict_loop), ("bug 2", bug_lo_equals_mid),
("bug 3", bug_hi_equals_mid), ("bug 4", bug_hi_is_len), ("bug 5", bug_float_mid)]:
bad = 0
for a, t in inputs:
got = run(fn, a, t)
ok = isinstance(got, int) and ((got == -1 and t not in a) or (got != -1 and a[got] == t))
bad += not ok
print(f"{name:8} wrong or crashing on {bad} inputs")
print("bug 6 wrong on", fails(bug_first_occurrence, first_ge), "inputs")
print("bug 7 wrong on", fails(bug_last_occurrence, last_le), "inputs")
print("fixed 6 wrong on", fails(first_ge_fixed, first_ge), "inputs")
print("fixed 7 wrong on", fails(last_le_fixed, last_le), "inputs")
print()
n = 2_000_000_000
total = 1_000_000_000 + 1_999_999_999
print(f"int32 maximum 2,147,483,647; sum {total:,} wraps to {to_int32(total):,} "
f"(= {total:,} - 2**32), halved with // gives {to_int32(total) // 2:,}")
for label, mid in [("(lo+hi)//2 in int32", lambda lo, hi: to_int32(lo + hi) // 2),
("lo+(hi-lo)//2 ", lambda lo, hi: lo + (hi - lo) // 2)]:
result, steps = search_virtual(n, n - 1, mid)
print(f"{label}: result={result} after {len(steps)} steps; last (lo, hi, mid) = {steps[-1]}")
print()
a, t = [1, 3, 5, 7], 4
lo, hi = 0, len(a) - 1
print(f"correct search for {t} in {a}:")
while lo <= hi:
mid = lo + (hi - lo) // 2
print(f" lo={lo} hi={hi} mid={mid} a[mid]={a[mid]}")
if a[mid] == t:
break
if a[mid] < t:
lo = mid + 1
else:
hi = mid - 1
print(f" ends with lo={lo} hi={hi}: empty window, return -1")
The output below is the complete output of that program.
1 strict loop a=[1, 3, 5] target=5: buggy=-1 correct=2
1 strict loop a=[4] target=4: buggy=-1 correct=0
2 lo = mid a=[1, 3] target=3: buggy=infinite loop correct=1
3 hi = mid a=[1, 3] target=0: buggy=infinite loop correct=-1
4 hi = len(a) a=[1, 3, 5] target=9: buggy=IndexError correct=-1
5 mid = (lo+hi)/2 a=[1, 3, 5] target=3: buggy=TypeError correct=1
6 first, hi=mid-1 a=[1, 2, 3, 3] target=3: buggy=1 correct=2
7 last, lo=mid a=[1, 2] target=2: buggy=infinite loop correct=1
inputs per check: 756
correct wrong or crashing on 0 inputs
bug 1 wrong or crashing on 87 inputs
bug 2 wrong or crashing on 323 inputs
bug 3 wrong or crashing on 265 inputs
bug 4 wrong or crashing on 211 inputs
bug 5 wrong or crashing on 750 inputs
bug 6 wrong on 102 inputs
bug 7 wrong on 446 inputs
fixed 6 wrong on 0 inputs
fixed 7 wrong on 0 inputs
int32 maximum 2,147,483,647; sum 2,999,999,999 wraps to -1,294,967,297 (= 2,999,999,999 - 2**32), halved with // gives -647,483,649
(lo+hi)//2 in int32: result=negative index -647483649 after 2 steps; last (lo, hi, mid) = (1000000000, 1999999999, -647483649)
lo+(hi-lo)//2 : result=1999999999 after 31 steps; last (lo, hi, mid) = (1999999999, 1999999999, 1999999999)
correct search for 4 in [1, 3, 5, 7]:
lo=0 hi=3 mid=1 a[mid]=3
lo=2 hi=3 mid=2 a[mid]=5
ends with lo=2 hi=1: empty window, return -1
The eight mistakes, each with its failing input and cause
- Loop condition
lo < hiwith a closed window. On[1, 3, 5], target 5, the window shrinks tolo=hi=2and the loop exits without ever looking at index 2, so the result is -1 instead of 2.[4]with target 4 fails the same way: the loop never starts. Root cause: withhia real candidate, a window of size one is still unsearched. Fix:lo <= hi. lo = midinstead ofmid + 1. On[1, 3], target 3:mid=0,a[0]=1 < 3, andlois set back to 0, so the window never changes. The guard reports an infinite loop. Root cause:midwas already inspected and rejected, so it must leave the window. Fix:lo = mid + 1.hi = midinstead ofmid - 1. On[1, 3], target 0:mid=0,a[0]=1 > 0,hi=0, and the next round repeats exactly. Same root cause as mistake 2, on the other side.hi = len(a)with an inclusive loop. On[1, 3, 5], target 9 the window reacheshi=3,mid=3, anda[3]raisesIndexError. Root cause: the code mixes the half-open convention (hiis one past the end) with the closed-window loop (lo <= hireadsa[hi]). Pick one convention and keep every line consistent with it./instead of//for the midpoint. In Python 3,(lo + hi) / 2is a float:a[1.0]raisesTypeErroron[1, 3, 5](every input with a non-empty list that reaches a probe, which is why 750 of 756 inputs fail). Habits from C and Java, where/on two integers gives an integer, cause this; use//.- First-occurrence search over a half-open window (
hi = len(a), looplo < hi) that setshi = mid - 1. On[1, 2, 3, 3], target 3 the buggy search returns 1, but the first index with a value >= 3 is 2. Root cause: for "first index that satisfies a condition",miditself may be the answer when the condition holds, so it must stay:hi = mid. Throwing it away silently skips the answer. The working form isfirst_ge_fixedin the listing:if a[mid] >= t: hi = mid, elselo = mid + 1, which fails on 0 of the 756 inputs. lo = midwhile searching for the last occurrence, withmidrounding down. On[1, 2], target 2:lo=0, hi=1, mid=0, the condition holds,lo = mid = 0again, and the window never shrinks. Root cause: when the update keepsmid(lo = mid), the midpoint must round up (the upper middle: for a window of two items, the right one) so it differs fromlo:mid = lo + (hi - lo + 1) // 2. The mirror rule: updates that keepmidon thehiside use the rounded-down midpoint. The working form islast_le_fixedin the listing, which also fails on 0 of the 756 inputs.- Midpoint overflow,
(lo + hi) // 2in a 32-bit signed integer. The last block searches the virtual array0..1,999,999,999for the value 1,999,999,999. A signed 32-bit integer holds values only up to 2,147,483,647. In Java a sum past that is defined to wrap around by 2^32 = 4,294,967,296 (in C and C++ signed overflow is itself undefined behaviour, and on common hardware it typically wraps the same way); the program emulates the wrapping. The first probe is safe (0 + 1,999,999,999 fits), and the search moves tolo=1,000,000,000andhi=1,999,999,999. Then the sum 2,999,999,999 is above the limit, so it wraps to 2,999,999,999 - 4,294,967,296 = -1,294,967,297, and the program's floor division gives -647,483,649 (both numbers are on the int32 line of the output, and the line after it prints the failing search): a negative index. Integer division in Java, C and C++ truncates toward zero instead of flooring, so(lo + hi) / 2there gives -647,483,648 for this sum (run in an eclipse-temurin:21-jdk container); either way the index is negative. In C and C++ an out-of-range read is undefined behaviour, meaning the language puts no requirement on what happens, so the program may crash or read garbage; other languages raise an exception or return the wrong element. Withlo + (hi - lo) // 2the same search ends at the right index after 31 steps. Python's integers never overflow, so this only appears in fixed-width languages or when you emulate them as above.
The counts after "inputs per check" come from running each version on all 756 non-decreasing lists of length 0 to 5 over the values 0 to 3, with every target from -1 to 4: the correct version fails on 0, and every buggy version fails on a different number of inputs. Mistake 6 and 7 are judged against a first-index-at-or-above and last-index-at-or-below reference, the others against "an index holding the target, or -1".
The correct version, step by step
The final block traces the correct search for the absent value 4 in [1, 3, 5, 7]: probe index 1 (value 3, too small) so lo=2; probe index 2 (value 5, too big) so hi=1. Now lo=2 > hi=1, the window is empty, and the function returns -1. The loop ends exactly when the window empties, which is why lo <= hi is the matching condition for a closed window.
A rule to keep
Choose a convention before writing any line, and check three things against it: the initial hi, the loop condition, and each update. Then run three inputs on a one-element list [4]: target 4 (a hit), target 0 (below everything) and target 9 (above everything). Those catch mistakes 1 to 4 immediately.
Running the code
docker run --rm -v "$PWD":/w -w /w python:3.12 python binary_search_bugs.py
Save the program as binary_search_bugs.py. It uses only the standard library, and the output above is from Python 3.12.
Your service stores user-uploaded images. Thumbnails get requested constantly, but the original full-resolution files are almost never read again after the first day. Design a strategy that meaningfully cuts the object storage bill, and walk through the trade-offs of whatever approach you land on.
Sample Answer
Approach
Two very different access patterns share one storage bill: thumbnails are read constantly but are tiny, originals are large but almost never read again after day one. Design around that asymmetry instead of applying one policy to both.
Strategy
- Thumbnails: keep in standard (hot) storage, and put a CDN (content delivery network, a caching layer close to users) in front of them with a long cache TTL (time-to-live). Since they're small and requested constantly, the CDN absorbs most of the read traffic, keeping origin storage cost and request cost low even though the tier itself is the expensive one.
- Originals: transition to a cheaper, infrequent-access class after a short buffer (a couple of days, not day one, since users often edit or delete a fresh upload and an early transition can trigger a minimum-storage-duration charge), then to an archive-class tier after a longer window, since the question states they're "almost never read again" past the first day.
Worked example
At 10 million images/month, average 4 MB originals and 50 KB thumbnails: originals total about 39,060 GB/month, thumbnails about 477 GB/month, so originals are roughly 80x the stored bytes even though thumbnails get nearly all the traffic. At an illustrative $0.023/GB-month, leaving originals in standard storage costs about $898/month per monthly cohort; moving them to an archive class at an illustrative $0.004/GB-month cuts that to about $156/month, a saving near $742/month (about 83%) per cohort, compounding every month new uploads land. Thumbnails, by contrast, cost only about $11/month even fully hot, because they're small; there's no real saving available there, which is exactly why they're not worth tiering down.
Trade-offs
- Archiving originals adds retrieval latency and a retrieval fee for the rare user who wants their full-resolution download; that's an acceptable trade given how rarely it happens, but the product needs a "this may take a moment" state for that path.
- An alternative or complementary lever is re-encoding originals to a smaller lossy format once they're old enough that print-quality is unlikely to matter, trading some quality for less-than-linear byte reduction; worth evaluating if archive-tier savings alone aren't enough, but it's a one-way, quality-losing move, so treat it separately and more cautiously than a reversible storage-class transition.
Implement a responsive card grid using a mobile-first approach. Requirements:
- Mobile: single column
- Tablet: two columns
- Desktop: four columns
Provide the CSS (you may use CSS Grid or Flexbox). Explain your chosen breakpoints and why mobile-first helps maintain performance and progressive enhancement.
Sample Answer
Direct answer
Write the one-column layout as the base CSS, then add columns with min-width media queries: two columns from 600px and four from 1024px. Grid is the shortest tool for this (repeat(n, 1fr) per breakpoint); Flexbox gets the same result with percentage-based flex-basis values that must account for the gaps. A third version needs no media queries at all: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)) lets the container width decide the column count.
Terms used below: a breakpoint is the viewport width at which a media query switches on; mobile-first means the unqualified CSS is the phone layout and min-width queries add to it; progressive enhancement means the baseline works everywhere and richer layout is layered on top; fr is a fraction of the free space after gaps.
The HTML and CSS
Four containers hold eight identical cards so the approaches can be compared side by side: grid with media queries (#grid), the same pattern with 2, 3 and 4 columns (#grid-234), Flexbox (#flex), and auto-fit (#auto). Two more containers hold two cards each to show auto-fit against auto-fill. The last element is a button. The CSS has three labelled rule sets, A (grid with media queries), B (Flexbox) and C (auto-fit), plus the button rule; the HTML is the same eight cards repeated once per container, so each container can be measured separately.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Responsive card grid</title>
<link rel="stylesheet" href="cards.css">
</head>
<body>
<section id="grid" class="grid" aria-label="Grid with media queries">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
<article class="card"><h3>Card 3</h3></article>
<article class="card"><h3>Card 4</h3></article>
<article class="card"><h3>Card 5</h3></article>
<article class="card"><h3>Card 6</h3></article>
<article class="card"><h3>Card 7</h3></article>
<article class="card"><h3>Card 8</h3></article>
</section>
<section id="grid-234" class="grid grid--234" aria-label="Grid, 2 then 3 then 4 columns">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
<article class="card"><h3>Card 3</h3></article>
<article class="card"><h3>Card 4</h3></article>
<article class="card"><h3>Card 5</h3></article>
<article class="card"><h3>Card 6</h3></article>
<article class="card"><h3>Card 7</h3></article>
<article class="card"><h3>Card 8</h3></article>
</section>
<section id="flex" class="flex" aria-label="Flexbox with media queries">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
<article class="card"><h3>Card 3</h3></article>
<article class="card"><h3>Card 4</h3></article>
<article class="card"><h3>Card 5</h3></article>
<article class="card"><h3>Card 6</h3></article>
<article class="card"><h3>Card 7</h3></article>
<article class="card"><h3>Card 8</h3></article>
</section>
<section id="auto" class="auto" aria-label="auto-fit, no media queries">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
<article class="card"><h3>Card 3</h3></article>
<article class="card"><h3>Card 4</h3></article>
<article class="card"><h3>Card 5</h3></article>
<article class="card"><h3>Card 6</h3></article>
<article class="card"><h3>Card 7</h3></article>
<article class="card"><h3>Card 8</h3></article>
</section>
<section id="few-fit" class="auto" aria-label="auto-fit, two cards">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
</section>
<section id="few-fill" class="auto auto--fill" aria-label="auto-fill, two cards">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
</section>
<button id="cta" class="btn" type="button">Get started</button>
</body>
</html>
* { box-sizing: border-box; }
:root { --gap: 16px; }
body { margin: 0; padding: 16px; font: 16px/1.5 system-ui, sans-serif; }
section { margin-bottom: 24px; }
.card { padding: 16px; background: #eef; border-radius: 8px; }
.card h3 { margin: 0; }
/* A. Grid, mobile-first: 1, then 2, then 4 columns. */
.grid { display: grid; grid-template-columns: 1fr; gap: var(--gap); }
@media (min-width: 600px) { .grid { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 1024px) { .grid { grid-template-columns: repeat(4, 1fr); } }
/* Same pattern with other numbers: 2, then 3, then 4 columns. */
.grid--234 { grid-template-columns: repeat(2, 1fr); }
@media (min-width: 768px) { .grid--234 { grid-template-columns: repeat(3, 1fr); } }
@media (min-width: 1024px) { .grid--234 { grid-template-columns: repeat(4, 1fr); } }
/* B. Flexbox: wrapping row; each item gets a width that leaves room for the gaps. */
.flex { display: flex; flex-wrap: wrap; gap: var(--gap); }
.flex > .card { flex: 0 0 100%; }
@media (min-width: 600px) { .flex > .card { flex-basis: calc((100% - var(--gap)) / 2); } }
@media (min-width: 1024px) { .flex > .card { flex-basis: calc((100% - 3 * var(--gap)) / 4); } }
/* C. No media queries: as many 15rem-minimum columns as fit. */
.auto { display: grid; gap: var(--gap);
grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)); }
.auto--fill { grid-template-columns: repeat(auto-fill, minmax(min(100%, 15rem), 1fr)); }
/* Button: full width on small screens, natural width from 600px. */
.btn { display: block; width: 100%; padding: 12px 16px; font: inherit; }
@media (min-width: 600px) { .btn { display: inline-block; width: auto; } }
Choosing breakpoints
Breakpoints should sit where the content stops looking right, not at device names. Here the content rule is that each card should stay at 230px or wider (an illustrative minimum: enough for a card title and a short line of text without cramped wrapping; the arithmetic below works the same with any other minimum). With 16px of body padding on each side and 16px gaps, four columns hit exactly 230px when the viewport is 1000px: the container is 968px, so (968 - 3 x 16) / 4 = 230px. At 1024px the container is 992px and the cards are (992 - 3 x 16) / 4 = 236px. Two columns reach 230px from a 508px viewport ((476 - 16) / 2 = 230 with a 476px container), so 600px is a round number above that: (568 - 16) / 2 = 276px. The 1024px breakpoint is chosen the same way: it is a round number just above the 1000px at which four columns reach 230px. A 2, 3, 4 progression (#grid-234) is the same pattern with another middle step at 768px, where three columns give (736 - 2 x 16) / 3 = 234.7px.
Grid or Flexbox
| Question | Grid | Flexbox |
|---|---|---|
| Column count per breakpoint | repeat(2, 1fr): the intent is the code | flex-basis: calc((100% - 3 * var(--gap)) / 4): the gaps are your arithmetic |
| A partly filled last row | the last items sit in the same columns as the rows above | the last row's items sit on the same basis, left-aligned; use flex-grow and they stretch instead |
| Rows lined up in tracks | yes, columns are shared by every row | each row is laid out on its own |
| Unknown number of items per row | auto-fill / auto-fit | only through flex-wrap with a fixed basis |
Grid is the better default for a card grid because the container, not the cards, owns the column structure. Flexbox is still right when the items are a single row of mixed sizes (a toolbar, a tag list), which is a different shape of layout.
No media queries: auto-fit with minmax
repeat(auto-fit, minmax(min(100%, 15rem), 1fr)) means: make as many columns as fit, each at least 15rem (240px at the default font size) and sharing leftover space equally. The min(100%, 15rem) stops a narrow container from forcing a 15rem column wider than itself. With a 16px gap the number of columns is the largest n with n x 240 + (n - 1) x 16 not above the container width, which gives 1, 2, 3 and 4 at containers of 343, 736, 992 and 1248px (viewports 375, 768, 1024 and 1280). Traced at the 768px viewport, whose container is 736px: one column needs 240px, two need 2 x 240 + 16 = 496px, three need 3 x 240 + 2 x 16 = 752px, which is more than 736px, so the largest n that fits is 2; the two columns then share the leftover space equally, (736 - 16) / 2 = 360px each, the 360.0px in the output. The run below confirms that, including the case the media-query version cannot express: at 1024px auto-fit gives 3 columns, not 4.
auto-fit and auto-fill differ when there are fewer items than columns. MDN: auto-fit "behaves the same as auto-fill, except that after placing the grid items any empty repeated tracks are collapsed." With two cards at 1280px the auto-fit cards stretch to fill the row (616px each) while auto-fill keeps the empty tracks and the cards stay 300px.
The button
.btn is display: block; width: 100% by default and display: inline-block; width: auto from 600px. The default is what a narrow screen wants (a full-width tap target) and the query restores the natural size.
Verifying in three engines
The script counts distinct left edges among each container's cards to get the real column count, and reads card and button widths. Every expectation is also derived by hand above: 768px gives (736 - 16) / 2 = 360px for two columns, and 1280px gives (1248 - 3 x 16) / 4 = 300px for four.
import { chromium, firefox, webkit } from 'playwright';
import { pathToFileURL } from 'node:url';
import path from 'node:path';
const url = pathToFileURL(path.resolve('index.html')).href;
const near = (a, b) => Math.abs(a - b) <= 0.5;
let failures = 0;
const expect = (ok, msg) => { if (!ok) { failures++; console.log(' FAIL', msg); } };
// Columns = number of distinct left edges among a container's cards.
const columns = (sel) => {
const cards = [...document.querySelectorAll(sel + ' .card')];
const lefts = new Set(cards.map((c) => Math.round(c.getBoundingClientRect().left)));
return { cols: lefts.size, width: cards[0].getBoundingClientRect().width };
};
const buttonWidth = () => document.querySelector('#cta').getBoundingClientRect().width;
const want = { // width -> expected columns for each container
375: { '#grid': 1, '#grid-234': 2, '#flex': 1, '#auto': 1 },
768: { '#grid': 2, '#grid-234': 3, '#flex': 2, '#auto': 2 },
1024: { '#grid': 4, '#grid-234': 4, '#flex': 4, '#auto': 3 },
1280: { '#grid': 4, '#grid-234': 4, '#flex': 4, '#auto': 4 },
};
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
for (const width of Object.keys(want).map(Number)) {
const page = await browser.newPage({ viewport: { width, height: 800 } });
await page.goto(url);
const row = [];
for (const [sel, n] of Object.entries(want[width])) {
const got = await page.evaluate(columns, sel);
expect(got.cols === n, `${name} ${width} ${sel}: expected ${n} columns, got ${got.cols}`);
row.push(`${sel}=${got.cols} cols @ ${got.width.toFixed(1)}px`);
}
const bw = await page.evaluate(buttonWidth);
expect(width < 600 ? near(bw, width - 32) : bw < 200, `${name} ${width}: button width ${bw}`);
if (name === 'chromium') console.log(width, row.join(' | '), '| button', bw.toFixed(1) + 'px');
if (width === 1280) {
const fit = await page.evaluate(columns, '#few-fit');
const fill = await page.evaluate(columns, '#few-fill');
expect(fit.width > 2 * fill.width, `${name}: auto-fit stretches 2 cards, auto-fill keeps empty tracks`);
if (name === 'chromium') console.log('2 cards at 1280: auto-fit', fit.width, 'px each, auto-fill', fill.width, 'px each');
}
await page.close();
}
await browser.close();
}
console.log(failures === 0 ? 'ALL CHECKS PASSED' : `${failures} CHECK(S) FAILED`);
process.exit(failures ? 1 : 0);
Output (Chromium lines printed; Firefox and WebKit are asserted against the same expectations):
375 #grid=1 cols @ 343.0px | #grid-234=2 cols @ 163.5px | #flex=1 cols @ 343.0px | #auto=1 cols @ 343.0px | button 343.0px
768 #grid=2 cols @ 360.0px | #grid-234=3 cols @ 234.7px | #flex=2 cols @ 360.0px | #auto=2 cols @ 360.0px | button 114.6px
1024 #grid=4 cols @ 236.0px | #grid-234=4 cols @ 236.0px | #flex=4 cols @ 236.0px | #auto=3 cols @ 320.0px | button 114.6px
1280 #grid=4 cols @ 300.0px | #grid-234=4 cols @ 300.0px | #flex=4 cols @ 300.0px | #auto=4 cols @ 300.0px | button 114.6px
2 cards at 1280: auto-fit 616 px each, auto-fill 300 px each
ALL CHECKS PASSED
Removing the min-width: 1024px grid rule from the stylesheet and re-running makes the script fail at 1024 and 1280 in all three engines, so the check exercises the rule it describes. Chromium's lines:
FAIL chromium 1024 #grid: expected 4 columns, got 2
FAIL chromium 1280 #grid: expected 4 columns, got 2
The last line of that run reads 6 CHECK(S) FAILED. WebKit here is Playwright's build, not Safari on iOS.
Why mobile-first helps
- Progressive enhancement. The unqualified rules are the whole layout for any browser that does not apply the queries, and the narrow layout is the simplest one, so nothing needs undoing.
- Less overriding. Each breakpoint only adds columns, so rules do not have to cancel each other. Media queries add no specificity of their own, so a later rule at the same specificity wins by source order, and
min-widthqueries ordered from small to large read as a single escalating sequence. - Performance, stated precisely. A mobile-first file is not smaller by itself, and web.dev notes that "The browser downloads all CSS resources, regardless of blocking or non-blocking behavior." The measurable lever is splitting wide-screen CSS into a
<link rel="stylesheet" href="wide.css" media="(min-width: 1024px)">. A stylesheet is render-blocking when the browser will not paint anything until it has downloaded and parsed it (first paint is the moment the first pixels of the page appear). web.dev says a stylesheet whose media query does not match the current device is non-render-blocking, and the browser fetches it at lower priority, so a phone does not wait for the wide-screen rules.
Trade-offs and pitfalls
- Flexbox percentage maths: forgetting the gap in
flex-basismakes the fourth card wrap onto a new row. Prefercalc((100% - 3 * var(--gap)) / 4). 1frhas an automatic minimum.1frbehaves likeminmax(auto, 1fr), and theautominimum is the item's smallest possible width, itsmin-contentsize (the width of its longest unbreakable word or string). A card containing an unbreakable string therefore widens its track instead of shrinking; useminmax(0, 1fr)if cards hold long unbroken content.auto-fitcannot guarantee exactly four columns. If design demands exactly 1, 2, 4, use explicit queries.- Edge cases: eight cards fill 4 columns twice, but seven would leave a partly filled last row in every version above; an empty container renders nothing; zoomed text (larger rem) reduces the column count in the
auto-fitversion because the 15rem minimum grows.
Running the code
mkdir demo && cd demo # put index.html, cards.css, check.mjs here
npm init -y && npm pkg set type=module
npm i playwright@1.48.2 && npx playwright install chromium firefox webkit
node check.mjs
Explain how hash tables handle collisions via separate chaining versus open addressing, including the average-case and worst-case complexity of get/put/delete under each. Then explain how an attacker who can choose the keys can degrade every lookup to O(n) (a hash-flooding attack), and what mitigations (randomized hash seeding, safer hash functions) restore the average-case guarantee.
Sample Answer
Direct answer: Separate chaining stores colliding keys in a linked list (or small array/tree) per bucket; open addressing (linear/quadratic probing, double hashing) stores every key directly in the table itself, probing to the next slot on collision. Both give average-case O(1) get/put/delete under a good hash function and bounded load factor, but an attacker who can choose (or predict) keys that all hash to the same bucket can force every operation to O(n) - a real denial-of-service vector, not just a theoretical curiosity, mitigated by randomized hash seeding at process startup and hash functions resistant to seed-independent collision construction.
Structured elaboration
- Separate chaining: each bucket holds a small collection (commonly a linked list, or - in some modern implementations like Java 8+'s HashMap - a balanced tree once a bucket grows large) of all keys hashing there. Lookup cost is O(1 + chain length); with load factor kept bounded, expected chain length is O(1).
- Open addressing: on collision, probe subsequent slots (linear: next slot; quadratic: quadratically-increasing offsets; double hashing: a second hash function determines the probe sequence) until an empty slot is found. Avoids the pointer-chasing overhead of chaining (better cache locality, since probing stays within the contiguous backing array), but degrades faster as load factor approaches 1 (must keep load factor well below 1, commonly under 0.7, whereas chaining degrades more gracefully).
- The attack: if the hash function is known (or its output is predictable, e.g. a naive non-cryptographic hash with a fixed seed) and an attacker controls input keys (e.g. HTTP form-field names, JSON keys), they can construct a large set of keys that all collide into the same bucket(s), degrading every operation from O(1) to O(n) and creating an algorithmic denial-of-service - a single request with thousands of colliding keys can pin a server's CPU.
Worked example
This is not hypothetical: this exact vulnerability class ("hash flooding") was responsibly disclosed and patched across essentially every major web-application language runtime around 2011-2012, after researchers demonstrated that a small POST request with carefully-crafted colliding form-field names could consume many CPU-seconds parsing what should have been a millisecond-scale request. The fix adopted across languages was randomizing the hash seed per-process at startup (so the attacker can't predict the collision-inducing keys ahead of time without knowing the runtime's random seed) and, in some cases, switching to collision-resistant hash functions (like SipHash) specifically designed to make seed-independent collision construction computationally infeasible even if an attacker can observe hash outputs.
Trade-offs & pitfalls
- "Average-case O(1)" is a claim about TYPICAL inputs, not a security guarantee - any system that hashes attacker-controlled keys needs the worst-case-resistant mitigations (randomized seeding, or a cryptographically-motivated hash), not just a "good enough in practice" hash function.
- Randomized per-process seeding means hash order becomes non-deterministic across process restarts - code that accidentally depends on hash-iteration order (a common latent bug) will surface intermittently once seeding is randomized.
- Open addressing's degradation is sharper (clustering effects can compound near a full table) than chaining's, so open-addressing implementations typically resize more aggressively (lower load-factor threshold) to stay safely away from the cliff.
Recommended Additional Resources
- LeetCode Premium - Practice 150-200 medium problems focusing on arrays, strings, linked lists, trees, graphs, and dynamic programming
- Cracking the Coding Interview (6th Edition) - Essential book covering interview preparation strategies and common questions
- System Design Primer (GitHub) - Comprehensive free resource for learning system design concepts and patterns
- Educative System Design for Interviews - Structured course on system design patterns and real-world case studies
- JavaScript: The Definitive Guide - Comprehensive reference for JavaScript fundamentals and advanced concepts
- React Official Documentation and Tutorial - Essential for understanding React fundamentals, hooks, and best practices
- You Don't Know JS (Book Series) - Deep dive into JavaScript concepts and how they work under the hood
- CS50's Web Programming with Python and JavaScript - Excellent free course covering fullstack development concepts
- Node.js Official Documentation - Reference material for Node.js APIs, modules, and best practices
- SQL Tutorial by W3Schools - Quick reference for SQL syntax and common database operations
- Stanford Lecture Series on Databases - Video lectures covering database fundamentals and design principles
- FAANG Interview Stories on YouTube - Real interview experiences and tips from engineers at top companies
- Design Data-Intensive Applications (Book) - Advanced but valuable for understanding distributed systems concepts
- Front-end Developer Handbook - Comprehensive guide to frontend development tools, practices, and concepts
- Backend Development Best Practices - Articles and resources on writing production-quality backend code
- HackerRank and CodeSignal - Alternative platforms for practicing coding problems with interview-style assessments
- GitHub Repositories - Study real-world open-source fullstack projects to understand best practices
- STAR Method Guide - Resources for structuring behavioral interview responses effectively
- Company Engineering Blog Posts - Read technical blog posts from FAANG companies to understand their engineering culture and decisions
- Tech Interview Handbook (GitHub) - Community-created resource with interview tips, study guides, and salary negotiation advice
Search Results
Top 24 Full Stack Developer Interview Questions & Answers
Intermediate Full Stack Developer Interview Questions · 1. Explain the concept of RESTful API and its usage. · 2. What do you mean by the term MEAN Stack? · 3.
Top 70 Coding Interview Questions and Answers for 2026
Here are various coding interview questions related to arrays, linked lists, stacks, queues, trees, and graphs, helping you understand how to approach problems ...
Top FAANG+ Coding Interview Questions for Software Engineers
To help you prepare for your next coding interview, we've compiled this list of the most common coding interview questions asked at FAANG+ interviews.
Top 126 Node.js Interview Questions And Answers - FullStack.Cafe
Top 126 Node.js Interview Questions And Answers To Kill Your Next Tech Interview.
Top JavaScript Interview Questions You MUST Know ... - YouTube
Comments · React Junior Developer Interview (Questions & Challenge) · Top 30 JavaScript Interview Questions 2025 | JavaScript Interview Questions & Answers | ...
This interview preparation guide was generated using AI-powered research from the sources listed above. While we strive for accuracy, we recommend verifying critical information from official company sources.
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 Full-Stack Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs