FAANG-Standard Backend Developer (Mid-Level) Interview Preparation Guide
This guide is based on general FAANG interview practices and may not reflect specific company procedures.
The interview process for a mid-level backend developer at FAANG companies typically consists of 7 rounds spanning 4-6 weeks. Initial rounds focus on coding proficiency and backend fundamentals, followed by system design to assess architectural thinking. Behavioral rounds evaluate leadership potential and cultural alignment. A final bar raiser round ensures hiring quality. Each round is designed to assess specific competencies: coding ability, system design thinking, API design, database optimization, cloud infrastructure knowledge, and leadership principles.
Interview Rounds
Recruiter Screening
What to Expect
Initial phone or video call with a recruiter to assess background, motivation, and cultural fit. The recruiter will review your resume, ask about your experience as a backend developer, discuss your interest in the role and company, and evaluate communication skills. This is NOT a technical round but rather a screening to ensure you meet baseline expectations and to learn about your career goals. The recruiter will also explain the interview process and answer logistical questions.
Tips & Advice
Be clear and concise about your backend development experience. Highlight specific projects where you designed APIs, optimized databases, or managed cloud infrastructure. Research the company and demonstrate genuine interest in their backend/infrastructure challenges. Prepare a 2-3 minute elevator pitch about yourself focusing on backend accomplishments. Ask thoughtful questions about the role, team structure, and technical stack. This round is conversational; avoid over-explaining and keep answers focused.
Focus Topics
Communication & Professionalism
Practice clear, concise communication without excessive jargon. Be ready to explain backend concepts to a non-technical recruiter. Show enthusiasm and genuine interest in the conversation.
Practice Interview
Study Questions
Motivation & Company Fit
Articulate why you're interested in this specific role and company. Connect your career goals to the company's backend challenges (scalability, reliability, infrastructure). Show you've researched their products and technical blog posts.
Practice Interview
Study Questions
Background & Experience Summary
Prepare a clear narrative of your backend development career, highlighting key projects, technologies used (Node.js, Python, Java), and impact (e.g., 'reduced API response time by 40%' or 'designed microservices for 10x user growth'). Be ready to discuss your most complex backend project.
Practice Interview
Study Questions
Technical Phone Screen
What to Expect
First technical assessment conducted via phone or video with a backend engineer (45-60 minutes). You'll solve 1-2 medium-difficulty coding problems on a shared coding platform. The focus is on data structures (arrays, strings, hash maps, linked lists, trees, graphs), algorithms (sorting, searching, dynamic programming), and your ability to write clean, working code under time pressure. The interviewer will observe your problem-solving approach, communication, and code quality. This round determines if you advance to on-site interviews.
Tips & Advice
Read the problem carefully and ask clarifying questions about input constraints, edge cases, and expected output. Start with a brute force approach and explain its limitations, then optimize. Write pseudocode first, then implement. Talk through your logic as you code. Test with examples including edge cases (empty input, single element, large datasets). Use proper variable names and write clean, readable code. If stuck, explain your thought process and ask for hints—interviewers appreciate transparency. Aim for solutions with good time and space complexity, but correctness is more important than perfection.
Focus Topics
Dynamic Programming
Learn DP fundamentals: overlapping subproblems, memoization, bottom-up tabulation. Practice classic problems: coin change, longest subsequence, knapsack, edit distance. Understand when DP applies.
Practice Interview
Study Questions
Sorting & Searching
Master merge sort, quicksort, binary search. Understand time complexity (O(n log n) for optimal sorts), space complexity, and stability. Practice custom comparators for sorting complex objects.
Practice Interview
Study Questions
Trees & Graphs
Understand tree traversal (DFS, BFS), binary search trees, graph representations, and pathfinding (DFS, BFS, Dijkstra). Practice problems on tree balancing, level-order traversal, and connected components.
Practice Interview
Study Questions
Array & String Manipulation
Master problems involving arrays and strings: finding missing/duplicate elements, rotating arrays, merging sorted arrays, string reversal, anagram detection, substring searches. Practice in-place operations and two-pointer techniques. Understand space-time trade-offs.
Practice Interview
Study Questions
Hash Maps & Hash Tables
Solve problems using hash maps for caching, counting, grouping, and deduplication. Understand collision handling, load factors, and hash function design. Practice LRU cache, frequency maps, two-sum variants.
Practice Interview
Study Questions
Technical Interview Round 1 - Coding with Backend Context
What to Expect
On-site or video interview (60 minutes) with a backend engineer where you solve a medium-hard coding problem, often with real-world backend context. The problem may involve designing data structures for an API, optimizing queries, or implementing backend logic (rate limiting, caching, authentication tokens). You'll be assessed on problem-solving approach, code quality, optimization, and ability to discuss trade-offs. The interviewer wants to see you think about real backend concerns: performance, scalability, and edge cases.
Tips & Advice
After understanding the problem, discuss your approach before coding. Identify performance bottlenecks and propose optimizations. Consider real-world backend concerns: concurrent access, memory limits, error handling, and maintainability. Write modular code with helper functions. Test thoroughly with various inputs. If a problem involves APIs or data structures, discuss how it would be deployed (database choice, caching strategy). Be prepared to discuss trade-offs (speed vs. memory, consistency vs. availability). Ask clarifying questions about expected scale and usage patterns—this shows backend maturity.
Focus Topics
Error Handling & Edge Cases
Write defensive code that handles errors gracefully (invalid input, overflow, concurrent access, missing data). Test edge cases: empty inputs, single elements, duplicates, boundary values, negative numbers, null references.
Practice Interview
Study Questions
Code Quality & Readability
Write clean code with descriptive variable names, comments explaining non-obvious logic, and proper formatting. Avoid clever tricks that reduce readability. Structure code logically with helper functions. Keep functions focused and maintainable.
Practice Interview
Study Questions
API & Data Structure Design
Design efficient data structures and APIs for backend problems: rate limiters, leaderboards, session managers, cache layers. Understand how to expose data via API endpoints and optimize for common queries. Practice designing custom classes and interfaces.
Practice Interview
Study Questions
Optimization & Scalability Thinking
Discuss optimization in terms of throughput, latency, and resource usage. Consider caching strategies, index design, and distributed approaches. Understand when to use different algorithms or data structures based on scale (e.g., 1000 vs. 1 billion operations).
Practice Interview
Study Questions
Technical Interview Round 2 - Coding
What to Expect
Second on-site or video technical interview (60 minutes) with a different backend engineer. You'll solve another medium-hard coding problem, typically from a different domain than Round 1. This might involve graph problems, string manipulation, dynamic programming, or system-level thinking. The purpose is to assess consistency of your coding ability, problem-solving approach, and communication across different problem types. Interviewers compare performances across rounds to get a holistic view of your technical depth.
Tips & Advice
Apply the same rigorous approach as Round 1: clarify requirements, propose approach, code cleanly, test thoroughly. Consistency is key—interviewers want to see you perform well across different problem types. If this round feels harder than Round 1, adjust your pacing: spend 5-10 minutes on approach planning rather than diving straight into code. If you get stuck, communicate your thought process and ask for clarification. Don't panic if Round 2 feels different; it's intentional to test adaptability. Remember that mid-level candidates should show strong fundamentals without needing to solve every problem perfectly.
Focus Topics
String Processing & Pattern Matching
Solve string problems: pattern matching, substring search, anagrams, palindromes. Practice with regex concepts if relevant to your language. Understand string encoding and character manipulation.
Practice Interview
Study Questions
Linked Lists & Complex Data Structures
Master linked list operations: reversal, cycle detection, merging sorted lists. Practice with doubly linked lists, circular lists. Understand when to use linked lists vs. arrays.
Practice Interview
Study Questions
Graph Algorithms & Traversal
Solve graph problems: shortest path, connected components, cycle detection, topological sorting. Implement DFS and BFS. Understand adjacency lists vs. matrices. Practice with directed and undirected graphs.
Practice Interview
Study Questions
Problem-Solving Communication
Articulate your thinking clearly: explain your approach before coding, discuss time/space complexity, identify optimizations, walk through examples. Handle ambiguous requirements by asking questions and stating assumptions.
Practice Interview
Study Questions
System Design Interview
What to Expect
On-site or video interview (75 minutes) with a senior backend engineer or architect assessing your ability to design scalable, distributed systems. You'll be asked to design a medium-scale backend system (e.g., 'Design a URL shortening service', 'Design a rate limiter', 'Design a notification system for millions of users'). You'll discuss system components (APIs, databases, caching, load balancers), architectural trade-offs, scalability strategies, and failure handling. This round is crucial for mid-level candidates—it shows you can think beyond individual coding problems to system-wide implications. You should scope the problem, identify key requirements, propose solutions with trade-offs, and defend your choices.
Tips & Advice
Start by clarifying requirements and constraints with the interviewer: expected users, data volume, latency requirements, consistency needs. Scope aggressively—mid-level candidates aren't expected to design enterprise systems in 75 minutes. Propose a solution with clear components: API layer, business logic, database, cache, messaging queue, etc. Use diagrams or ASCII art to illustrate architecture. Discuss trade-offs explicitly: SQL vs. NoSQL, consistency vs. availability, vertical vs. horizontal scaling. When proposing optimizations, explain the reasoning (e.g., 'caching this endpoint reduces database load by 60%'). Be ready to defend your choices and adapt when interviewer questions your approach. For mid-level, demonstrating pragmatic decision-making and understanding real constraints matters more than proposing perfect architectures. If you don't know a specific technology, discuss concepts and explain how you'd research it.
Focus Topics
Deployment & Infrastructure (Cloud Platforms)
Design deployment architecture using cloud platforms (AWS, Azure). Discuss containerization (Docker), orchestration (Kubernetes), CI/CD pipelines, monitoring, and logging. Understand auto-scaling policies.
Practice Interview
Study Questions
Security & Authentication
Design secure systems: authentication mechanisms (OAuth, JWT), authorization, encryption at rest and in transit, secrets management. Discuss HTTPS, SQL injection prevention, and secure API patterns.
Practice Interview
Study Questions
Database Design & Optimization
Design schemas, choose between relational (PostgreSQL) and NoSQL (MongoDB) databases. Discuss indexing, query optimization, denormalization, sharding strategies. Understand CAP theorem trade-offs and consistency models.
Practice Interview
Study Questions
RESTful API Design
Design scalable APIs with clear resource models, HTTP methods, status codes, and pagination. Discuss request/response formats, versioning strategies, and backward compatibility. Consider API rate limiting, authentication, and monitoring.
Practice Interview
Study Questions
Scalability & Load Balancing
Design for horizontal scaling: load balancers, stateless services, service replication. Discuss database sharding, read replicas, and distributed transactions. Understand when to scale horizontally vs. vertically.
Practice Interview
Study Questions
Caching & Performance Optimization
Implement multi-layer caching: in-memory caches (Redis), CDN for static content, query result caching. Understand cache invalidation strategies, TTLs, and cache stampede prevention.
Practice Interview
Study Questions
Behavioral Interview
What to Expect
On-site or video interview (45-60 minutes) with a hiring manager or senior engineer focused on behavioral competencies and leadership potential. You'll answer questions about past experiences using the STAR format (Situation, Task, Action, Result). The focus is on how you handle challenges, work in teams, make decisions, and align with company values. For mid-level candidates, interviewers assess: can you own projects end-to-end? Do you mentor junior developers? Do you handle ambiguity well? Can you disagree respectfully? This round determines cultural fit and leadership trajectory.
Tips & Advice
Prepare 5-7 concrete STAR stories from your actual experience: a time you solved a complex technical problem, mentored someone, handled conflict, shipped a major feature, dealt with failure, received critical feedback, or balanced multiple priorities. Make stories specific with metrics and outcomes (e.g., 'reduced latency by 40%', 'mentored 2 junior developers who both received promotions'). For mid-level, emphasize ownership: 'I owned this project from design through production deployment' shows progression. Discuss failures honestly and what you learned. Connect stories to FAANG leadership principles (Amazon: Ownership, Bias for Action, Earn Trust; Meta: Move Fast, Build Awesome Things; Google: Focus on Users, Deliver Excellence). Use the interviewer's questions as jumping-off points; don't recite answers robotically. Ask thoughtful questions about team dynamics, career growth, and technical challenges. Be authentic—interviewers value genuine responses over perfect stories.
Focus Topics
Learning from Failure & Resilience
Discuss a production incident, missed deadline, or technical mistake. Explain what went wrong, how you responded, what you learned, and how you prevented recurrence. Show accountability without blame-shifting.
Practice Interview
Study Questions
Collaboration & Cross-Functional Work
Share examples of working with frontend developers, product managers, DevOps teams, or other backend teams. Describe how you communicated technical constraints, resolved disagreements respectfully, and shipped together.
Practice Interview
Study Questions
Handling Ambiguity & Difficult Decisions
Describe situations where requirements were unclear, tech choices were complex, or you had to make trade-offs. Show how you gathered information, consulted stakeholders, made decisions, and communicated rationale.
Practice Interview
Study Questions
Mentorship & Team Growth
Share examples of mentoring junior developers: code reviews, pair programming, helping them debug issues, giving feedback. Describe how you helped grow someone's skills or helped them succeed in their role.
Practice Interview
Study Questions
Ownership & End-to-End Project Delivery
Prepare stories demonstrating how you've owned backend projects from conception through production: designing systems, implementing features, handling deployment, monitoring, and fixing production issues. Show how you balance technical excellence with business needs.
Practice Interview
Study Questions
Bar Raiser Round
What to Expect
Final on-site or video interview (60 minutes) conducted by a senior engineer or architect who is a 'bar raiser'—tasked with ensuring hiring quality and raising standards. This round combines technical depth and behavioral assessment. You might be asked deep technical questions about past projects (e.g., 'Tell me about the most complex API you designed—what trade-offs did you make?'), system design challenges, or behavioral questions rooted in company values. The bar raiser has significant input on the final hiring decision. This round assesses whether you're truly mid-level—showing strong technical fundamentals and beginning-level mentorship ability—without inflating yourself beyond realistic expectations.
Tips & Advice
Treat this as a conversation with a seasoned backend engineer, not an interrogation. Be honest about what you know and don't know. If asked about your most complex project, prepare to discuss it in detail: what problem did you solve, what was your approach, what would you do differently now, what did you learn? Bar raisers appreciate thoughtful self-reflection. If you encounter a question you can't answer, admit it and explain how you'd approach learning it. Don't pretend expertise you lack. Demonstrate growth mindset: 'I haven't worked with that technology, but I learn quickly and have successfully picked up similar technologies.' Ask insightful questions about technical direction, team challenges, or how the company approaches scalability—this shows you're thinking strategically. Remember bar raisers are looking for mid-level engineers who are progressing toward senior level, not senior engineers. Show strong fundamentals, leadership potential, and ownership without overcommitting to senior-level responsibilities.
Focus Topics
Production Engineering & Reliability
Discuss production experiences: incidents you've handled, monitoring you've implemented, debugging approaches, lessons learned. Show you understand operational aspects of backend systems beyond coding.
Practice Interview
Study Questions
Growth & Learning Orientation
Discuss how you've grown technically: new technologies you've learned, mistakes that led to breakthroughs, challenging problems that expanded your capabilities. Show curiosity and commitment to continuous improvement.
Practice Interview
Study Questions
Technical Depth & Project Mastery
Deep dive into your most complex backend project: problem statement, your architectural decisions, why you chose specific technologies, trade-offs you navigated, challenges you overcame, and outcomes. Be prepared for follow-up questions challenging your choices.
Practice Interview
Study Questions
System Thinking & Architectural Judgment
Demonstrate ability to think beyond immediate coding tasks to system implications: how your code scales, how it integrates with other services, what happens at 10x scale, how you'd debug production issues.
Practice Interview
Study Questions
Frequently Asked Backend Developer Interview Questions
Tell me about a time you sponsored someone, not just mentored them. Where you actively advocated for their promotion or a specific opportunity in a room they weren't in.
Sample Answer
Direct answer
Sponsorship means spending your own credibility to open a door someone couldn't open for themselves, which is different from mentoring, which is advice given directly to the person. The core act is advocating for them by name in a room they aren't in, backed by specific, evidence-based reasons they deserve the opportunity.
What sponsorship requires
Political capital and timing, not just advice. Mentoring can happen anywhere, anytime, one on one. Sponsorship requires actually being present, or having enough standing, in the room where a real decision gets made: a promotion committee, a staffing decision, an assignment to a high-visibility project.
An evidence-backed case, not a vague endorsement. "They're great" doesn't move a room. Specific, concrete contributions you can vouch for personally do. Building this case ahead of time, before the opportunity comes up, is part of the work.
Deciding when it's warranted. The right moment is when someone is already delivering at the target level but lacks the visibility or exposure to be considered for it, there's a real decision window open, and you have enough credibility in that specific room for your advocacy to actually carry weight.
Making the specific ask. Vouching in general terms is weaker than naming the specific opportunity and asking for the specific outcome: this person, for this role, on this team, now.
Aftercare. Sponsorship only compounds if the person knows it happened. Telling them what you did lets them lean into the opportunity and know someone is actively in their corner, not just quietly hoping things work out. Following up on the outcome, win or not, matters too.
Worked example
Someone you work closely with does excellent work but has almost no visibility outside their immediate team. A high-visibility opportunity, or a promotion cycle, comes up in a room they aren't part of. You go in with specific, concrete contributions you can personally back, not general praise, and explicitly vouch for their readiness for that specific opportunity. Afterward, they're included in the opportunity or the promotion conversation, and you tell them directly what you did and why, rather than letting them find out secondhand or not at all.
Trade-offs and pitfalls
Sponsoring someone whose work you can't concretely back with specifics spends your credibility on hope rather than evidence, and if it doesn't pan out, it costs you standing in that room for the next person you'd want to sponsor.
Sponsoring quietly and never telling the person defeats much of the point. They don't know to lean into the opportunity, and they don't know someone is actively advocating for them, which is often as valuable as the opportunity itself.
Sponsorship is finite. You have a limited amount of credibility to spend across your whole network, which means you genuinely cannot sponsor everyone equally, and who you choose to spend it on is a real, sometimes uncomfortable decision worth being honest with yourself about.
A common confusion is treating a glowing performance review comment as sponsorship. Real sponsorship requires actually being in the room, advocating for a specific decision, not just praising someone in the abstract where it doesn't reach the decision-maker.
What was your specific role versus the team's role on that project?
Sample Answer
Direct answer: Break the project into its major components or workstreams, and for each say plainly whether you owned it, contributed to it, or reviewed it, backed by something concrete you can point to rather than blanket language like "we" or "helped."
Why interviewers ask this
They're checking whether you can isolate your individual contribution inside a team effort, and whether your language ("I" versus "we") tracks something real rather than blending your work with everyone else's.
A simple ownership vocabulary
| Level | What it means | Example phrasing |
|---|---|---|
| Owned | You made the call and did the work | "I decided to... and built..." |
| Contributed | You built a defined piece, didn't set the overall direction | "I implemented the X piece within a design someone else set" |
| Reviewed / supported | You gave input, weren't hands-on | "I reviewed the approach and flagged..." |
How to structure the answer
- Break the project into 3-5 components (for example: scope and requirements, the core build, testing, rollout, monitoring).
- Label your involvement per component using the vocabulary above.
- Pick one component you owned and be ready to go deep on it, since that's what actually proves the claim rather than just asserting it.
Worked example (illustrative skeleton)
A cross-functional launch project broken into four components: requirements and scope (contributed: shaped 2 of 6 requirements after running user interviews), the core feature build (owned: built and shipped it end to end), rollout communication (supported: wrote the release notes, didn't own the go/no-go decision), and post-launch monitoring (owned: set up the alert that caught a regression). The rollout itself was staged from 10% of users to 100% over three weeks; the monitoring alert flagged the regression during the first week, while the remaining 90% of users hadn't yet been exposed to the change.
Trade-offs and pitfalls
- Overclaiming ("I built the whole thing") when you contributed one piece invites a follow-up you can't sustain once the interviewer asks for detail.
- Underclaiming ("we did everything together") reads as no real individual ownership at all.
- Not having one component ready to go deep on undermines the whole answer.
- Being honest about where you were a contributor rather than the owner builds credibility; it doesn't weaken the answer.
You're working with a partner function whose incentives are genuinely different from yours, for example they're measured on speed and you're measured on quality or risk. How does that difference change how you scope your asks to them and how you share status?
Sample Answer
Direct answer
Once you know a partner function is measured on something different from you (speed versus quality or risk, for example), you scope your asks to be small and cheap under their metric, and you change what "status" means when you talk to them: short, action-oriented signals instead of the detailed risk narrative you'd give your own stakeholders. You're not changing what you need, you're changing how you package it so it doesn't read as a tax on the thing they're rewarded for.
Structured elaboration
- Diagnose the incentive, don't assume it. Confirm what the partner function is actually measured on (deploy velocity, ticket close time, uptime, cost) rather than inferring it from how they push back. Different sub-teams within the "same" function can be measured differently.
- Scope the ask to the smallest unit that gets you what you need. If they're speed-measured, don't ask for a broad, standing review of everything; ask for a narrow, well-bounded check on the specific surface that carries the risk you actually care about, and let everything else pass without friction.
- Translate the ask into their currency. Instead of framing a request around your risk language, frame it around what it costs (or saves) them in their terms: incident response hours avoided, rework avoided, a compliance gate they'd otherwise hit later and more expensively.
- Change the shape of status, not just the ask. For a speed-measured partner, give a compact signal (blocked/not blocked, a count, a single risk flag) they can act on in seconds. Save the fuller narrative for your own stakeholders who need the detail. Sharing the same long-form update with both audiences under-serves the partner who needs to move fast.
- Keep a floor. Adapting your ask to their incentive has a limit: there's a minimum you can't compromise below without failing your own mandate. Know that floor before the conversation so "scoping down" doesn't quietly become "giving up the requirement."
- Revisit as trust builds. Early asks are necessarily narrow and low-trust. As the partner sees your asks are well-scoped and your status updates are reliable, you can often widen the ask (a slightly broader review surface, more lead time) because they've learned you're not going to slow them down for nothing.
Worked example
A platform team is measured on release velocity; a security-minded partner function is measured on defect and incident rates. Rather than asking the platform team to route every change through manual security review (a direct tax on their velocity metric), the ask is scoped to only changes that touch a named risk surface, such as authentication or payment code. Everything else ships without added friction. Status to the platform team is a single weekly line: "2 changes in the review queue, 0 blocking, both cleared by Thursday." The fuller write-up, with rationale and residual risk, goes to the security function's own leadership, not to the platform team, because that's not the audience that needs it to act.
Trade-offs & pitfalls
- Pitfall: scoping the ask down so far it stops actually managing the risk it exists to manage. Know your floor before you negotiate.
- Pitfall: assuming the incentive instead of confirming it. Guessing wrong (e.g., treating a team as purely speed-driven when they're also on the hook for a compliance metric) leads to asks that miss what would actually land.
- Pitfall: sending the same status update to every audience. It either over-informs the speed-measured partner (who tunes it out) or under-informs your own stakeholders (who need the detail to make decisions).
- Senior differentiator: treating the ask size and the status format as things you design deliberately around the incentive gap, and revisiting that design as trust changes, rather than a fixed communication style you use with everyone.
How do you decide how formal or casual to make a piece of written communication, and what do you actually look at to make that call?
Sample Answer
Direct answer
Calibrate tone based on your relationship with the recipient, the channel you're using, how much is at stake, and the recipient's seniority or role relative to you, rather than defaulting to one register for everything.
Structured elaboration
- Relationship: a close, established working relationship generally tolerates more casual language than a first interaction or an external party you don't know well.
- Channel: a quick chat message naturally reads more casually than an email, and an email more casually than a formal memo or a document with a wide, unknown future readership.
- Stakes: a message tied to a real decision, a commitment, or something that could be read back later (a policy, a formal request) warrants more careful, formal wording than a routine day-to-day update.
- Audience seniority or external status: writing to a senior executive or an external customer generally calls for more formality than writing to a close peer, independent of how you'd naturally phrase it to a friend.
- When in doubt, err slightly more formal than you think you need to, especially for a first interaction or a written record that might be read by people beyond the immediate recipient; it's easier to loosen up in a follow-up than to walk back an overly casual first message.
Worked example
The same piece of information, "the deploy is delayed a day," phrased three ways depending on context: to a close peer over chat, "heads up, deploy's slipping a day, nothing dramatic;" in a status email to your manager, "I wanted to flag that the deploy is delayed by one day due to a failed test in staging; we expect to resolve it by tomorrow morning;" in a formal note to an external customer expecting the release, "We want to let you know that the release originally planned for tomorrow will now go out one day later than scheduled, due to an issue we identified during final testing. We apologize for the short delay and will confirm once it's live."
Same underlying fact, three different registers, each appropriate to who's actually reading it.
Trade-offs and pitfalls
- Being too formal with a close, established peer can read as distant or even passive-aggressive; matching the existing norm of that relationship matters as much as any general rule.
- Being too casual with someone senior, external, or in a first interaction can undercut how seriously your message is taken, regardless of the quality of the content.
- Tone is also a moving target within a single relationship over time; the right register for a new working relationship is often more formal than the register that same relationship settles into after months of regular contact.
A text filter uses a leading wildcard, like a LIKE pattern that starts with '%', and it is forcing a full scan on a large text column. Why can't a standard B-tree index help here, and what are your realistic options for restoring fast lookups?
Sample Answer
Direct answer. A standard B-tree index stores values in sorted order, which lets it efficiently find a matching PREFIX of a string; a wildcard at the START of a LIKE pattern means there's no fixed prefix to search for, so the index can't narrow the search at all and the engine falls back to checking every row's text against the pattern directly.
Structured elaboration. LIKE 'foo%' (wildcard only at the end) can use a standard B-tree index efficiently, because every string matching that pattern shares the same prefix, 'foo', which the index's sorted order can jump straight to. LIKE '%foo%' or LIKE '%foo' (wildcard at the start) has no such fixed prefix: a match could be any string CONTAINING or ENDING WITH 'foo' anywhere, which the sorted order of a standard index gives no leverage on at all, so the engine has no better option than scanning and checking every row.
Realistic options: a specialized full-text search index (built for token or substring matching rather than prefix matching) is the most direct fix if your engine supports one and the matching semantics fit; a trigram or n-gram index (where supported) can accelerate substring matches specifically, including leading-wildcard patterns, by indexing small overlapping fragments of the text rather than the whole string; and, if the real requirement is closer to "search," moving that specific workload to a dedicated search engine designed for it is often the more durable long-term answer once a standard relational index genuinely can't help.
Worked example. A dashboard filter doing WHERE comments LIKE '%refund%' against a large text column is the exact shape that defeats a plain B-tree index; if the underlying database supports a trigram index, adding one on that column can make this specific kind of substring search dramatically faster without changing the query at all, since the trigram structure is built specifically to handle "the pattern could start anywhere" searches that a standard index can't.
Trade-offs and pitfalls. Specialized indexes for this kind of search (trigram or full-text) cost more storage and more write-time maintenance than a standard B-tree, and aren't a good fit for every use case (very short strings, or a genuinely rare query pattern that doesn't justify the ongoing cost); weigh how often this kind of search actually runs, and how latency-sensitive it is, against that ongoing cost before reaching for a specialized index.
A developer laptop was compromised and attackers exfiltrated long-lived OAuth client secrets and refresh tokens. Describe the incident response plan to contain and remediate identity exposures across cloud accounts, SaaS, and CI/CD. Include steps for discovery, revocation strategies, key rotations, credential search across systems, urgent mitigations, and communication to stakeholders.
Sample Answer
Direct answer
Treat a leaked long-lived OAuth (an authorization protocol that issues tokens instead of passing around passwords) client secret and refresh tokens as an ongoing breach, not a cleanup task. Revoke the specific compromised credentials immediately at every identity provider (IdP, the system that issues and manages identity credentials) that holds them, then run discovery and full rotation in parallel rather than waiting for scope to be perfectly known before you act. The reason long-lived secrets are dangerous is that a refresh token can keep minting fresh access tokens indefinitely, so revoking one access token accomplishes nothing if the refresh token behind it is still valid.
Structured elaboration
Work the incident as six overlapping phases, not a strict sequence: Contain, Discover, Rotate, Verify, Communicate, Harden.
- Immediate containment (minutes). Revoke or disable the exact OAuth client registration(s) at every authorization server that issued them. Force-expire the developer's active sessions and, if the laptop was enrolled in device management, revoke its device trust or client certificate so it cannot re-authenticate. Long-lived client secrets are frequently reused across many SaaS integrations (CI system, chat app, ticketing system), so containment is not done until you have checked every consumer that was ever handed that client_id, not just the one you first found it in.
- Discovery and scope, run in parallel with containment. Search everywhere secret sprawl actually hides: the secrets manager or vault, CI/CD pipeline variables (build system secret stores, environment variables baked into container images at build time), any
.envfiles (search the full git history, not just the current branch tip, since a rotated file still leaves the old value in an old commit), local shell history and config files on the laptop, and any password manager or ticket attachment the developer used. Cross-reference the identity provider's and authorization server's audit logs for every token issuance and refresh event tied to the compromised client_id to build a concrete blast-radius list of exactly which downstream systems exchanged it, across cloud accounts, SaaS integrations, and CI/CD pipelines specifically, since each of those three environments tends to cache the credential differently. - Rotation, detailed per leaked-artifact type in the worked example below, because "rotate the credential" means a materially different operation depending on what was actually leaked.
- Verification. Do not assume rotation succeeded; confirm it. Attempt to exchange a known old refresh token and confirm the authorization server now rejects it. Watch for a spike in authentication failures (401 responses) from services still configured with the old secret: that spike is telling you exactly what you missed, not something to suppress.
- Communication, on a timeline independent of when technical remediation finishes. Internally: security leadership, the owners of every affected service, and legal or compliance if any customer-reachable system was in the blast radius. Externally: only once scope is confirmed, and calibrated to what breach-notification law and customer contracts actually require, since committing to a specific claim ("no customer data was touched") before discovery is complete is a common and costly mistake.
- Hardening. This is where the specific artifact type matters most, because the right long-term fix differs by what leaked.
Worked example
The same six-phase framework applies to three distinct leaked-artifact scenarios that show up in this kind of incident. They differ enough in their revocation mechanics and their long-term fix that treating them identically would miss the point of each one.
| Leaked artifact | Typical hiding place | Revocation action | Rotation / emergency step | What is distinct about it |
|---|---|---|---|---|
| OAuth client secret + refresh tokens (this scenario) | Developer laptop config or .env file, CI/CD secret store | Revoke the client registration at the identity provider; invalidate every outstanding refresh token issued to that client_id, not just the one token you found | Issue a new client_id/secret pair and redeploy it to every consumer (CI pipelines, backend services, SaaS integrations) before disabling the old one | A refresh token renews itself; revocation must target the whole token family for that client, or the attacker keeps minting new access tokens from a refresh token nobody thought to kill |
| Refresh tokens leaked via a compromised mobile app build or app-store side channel | A decompiled or leaked mobile binary, or a misconfigured build artifact pushed to a store | Revoke the mobile app's OAuth client and invalidate the refresh-token cohort tied to the affected app version | Ship a forced app update registered under a new client; you cannot "rotate a secret" the same way a backend service does, because a mobile app is a public OAuth client (no confidential secret, authentication relies on PKCE, Proof Key for Code Exchange) | If the leaked binary embedded something that functioned like a static secret, that itself is the root-cause defect: public clients should never hold a value whose secrecy the security model depends on |
| A token-signing private key is exposed | The key an identity provider uses to sign the identity tokens it issues (for example JWTs, JSON Web Tokens) | Roll the signing key immediately: publish the new public key and mark the old key ID (kid) untrusted in the JWKS (JSON Web Key Set) endpoint every relying service already polls | Every token signed before rollover was signed with a now-untrusted key. This forces a global re-authentication moment once relying services start rejecting the old kid, which every downstream service needs to be coordinated on, not discover independently | Highest blast radius of the three: an attacker holding the signing key can mint a valid token for any identity, not just one client's, so this is the one scenario that justifies an all-hands emergency cutover rather than a quiet rotation |
Trade-offs and pitfalls
- Revoke-first versus fully-scope-first is a real tension, not a solved problem. Revoking immediately can break production for consumers you have not yet identified, or tip off an attacker mid-exfiltration. Waiting to fully scope first leaves a known-compromised credential live. The practical resolution is to contain the specific credential you already know is compromised immediately, and run discovery in parallel, not sequentially after containment finishes.
- Rotating the leaked secret without fixing why it was leakable treats the symptom. If a static, long-lived client secret was sitting in a developer's laptop config in the first place, the durable fix is moving that integration to short-lived, workload-scoped credentials (for example via workload identity federation) so a laptop compromise cannot expose something this valuable again. Shipping only the rotation and skipping this is the most common shortfall in this kind of response.
- Communicating before scope is confirmed is worse than communicating a little later. A confident early claim that later needs walking back (for example, "no customer data was affected") costs more credibility than a short delay while discovery genuinely finishes.
- Assuming the credential search stops at the primary secret store is a common miss. CI/CD systems frequently cache a decrypted secret in build logs or artifact storage even after the primary store is rotated; those stale copies need an affirmative purge or a documented decision to accept the residual exposure, not silence.
Tasks arrive over time, each with a processing time (and possibly a deadline), and must be assigned to one of several identical workers online, without knowing future arrivals. Propose a greedy assignment rule and argue, using an exchange argument, why greedy does not lose to the optimal offline schedule.
Sample Answer
Direct answer
Assign each arriving task to whichever machine currently has the smallest total load (the "least-loaded machine" greedy rule, also called list scheduling). This online rule is never worse than twice the optimal offline makespan, and a short exchange-style argument tightens that to a factor of (2−m1), where m is the number of identical machines. This is the classical Graham's bound (1966). If tasks additionally carry hard deadlines, a single machine's feasibility is best handled separately by Earliest Deadline First (EDF); no online multi-machine rule offers a comparable constant-factor guarantee once deadlines are layered on top of load balancing.
Structured elaboration
Setup: m identical machines, tasks arrive one at a time with processing time pi, no knowledge of future arrivals, goal is to minimize the makespan (the finish time of the last task to complete).
Greedy rule: on each arrival, place the task on the machine with the current minimum cumulative load.
The exchange/potential argument for the bound. Let job j be the one that finishes last in the greedy schedule, running on machine i, starting at time t. Because greedy always routes work to whichever machine has the least load at that instant, every OTHER machine's load at time t must already be at least t (otherwise greedy would have picked one of them instead). Summing that lower bound across all m machines: the total work already placed before job j arrived, P−pj (where P is the sum of all processing times), is at least m⋅t. That gives:
T=t+pj≤mP−pj+pj=mP+pj(1−m1)≤OPT+OPT⋅mm−1=(2−m1)OPTusing two separate lower bounds on any optimal schedule's makespan: the average load P/m≤OPT, and the single largest job pj≤OPT (any schedule must place job j somewhere, taking at least pj time there). The "exchange" insight is that at the exact moment job j was placed, no machine could have been idler than machine i, so every machine had already absorbed unavoidable work, not that two individual schedule decisions are swapped directly.
Deadline extension: on a single machine, preemptive EDF is optimal for feasibility (it schedules any instance that has a feasible schedule at all). Once you combine online arrival, multiple machines, AND hard deadlines, no algorithm achieves a constant competitive ratio in the worst case; production systems fall back to a fast per-machine EDF feasibility check (admission control) layered on top of the same least-loaded routing, rather than chasing a provably-optimal global schedule.
import itertools
def greedy_list_scheduling(processing_times, m):
"""Assign each task, in arrival order, to whichever of the m machines
currently has the smallest total load."""
loads = [0] * m
for p in processing_times:
i = min(range(m), key=lambda k: loads[k])
loads[i] += p
return max(loads), loads
def optimal_makespan_bruteforce(processing_times, m):
"""Brute-force optimal offline makespan (small n only)."""
n = len(processing_times)
best = float("inf")
for assignment in itertools.product(range(m), repeat=n):
loads = [0] * m
for idx, machine in enumerate(assignment):
loads[machine] += processing_times[idx]
best = min(best, max(loads))
return best
m = 3
processing_times = [1, 1, 1, 1, 1, 1, 3] # m*(m-1) unit tasks, then one size-m task
greedy_makespan, loads = greedy_list_scheduling(processing_times, m)
opt = optimal_makespan_bruteforce(processing_times, m)
print(f"greedy loads: {loads}, makespan: {greedy_makespan}")
print(f"optimal makespan: {opt}")
print(f"ratio: {greedy_makespan / opt:.4f}, bound (2 - 1/m): {2 - 1/m:.4f}")
Output:
greedy loads: [5, 2, 2], makespan: 5
optimal makespan: 3
ratio: 1.6667, bound (2 - 1/m): 1.6667
Worked example
With m = 3 machines, six unit-size tasks arrive first, then one size-3 task. Greedy spreads the six units evenly (2 per machine), then the size-3 task lands on whichever machine is currently tied for least-loaded, giving loads [5, 2, 2] and a makespan of 5. The optimal offline schedule instead puts the size-3 task alone on one machine (load 3) and splits the six unit tasks 3-and-3 across the other two (loads 3, 3), for an optimal makespan of 3. The ratio, 5/3 = 1.667, exactly matches 2−31: this is the standard tight instance showing the bound isn't just a proof artifact, an adversary really can force it.
Trade-offs & pitfalls
- The bound assumes identical machines with no migration; allowing tasks to migrate after the fact often does much better in practice, at the cost of moved-task overhead and more bookkeeping.
- The proof needs BOTH lower bounds (P/m and pj); relying on P/m alone fails the moment one job is very large, since a single huge job forces a bigger optimal makespan than "average load" alone would suggest.
- Tie-breaking among equally-loaded machines does not affect the worst-case ratio, but a naive deterministic tie-break (always lowest index) can create structural correlation with adversarial arrival patterns; some implementations break ties randomly to avoid that.
- If tasks carry deadlines, "least-loaded" optimizes makespan, not deadline feasibility; the least-loaded machine at arrival time is not necessarily the one where this specific task's deadline is still reachable, so admission control needs its own per-machine feasibility check rather than trusting the load-balancing rule alone.
- The (2 - 1/m) bound does NOT generalize to machines with different speeds (unrelated or uniform machines): "current load" stops being the right proxy for "expected finish time" once machines process work at different rates, and a different assignment rule is needed.
A robot starts at the top-left of an m by n grid and can only move right or down. Count the distinct paths to the bottom-right in O(mn) time, then reduce the extra space to O(n). Is there a closed-form answer, and why might you still prefer the DP?
Sample Answer
The idea
A robot that can only move right or down reaches any cell from the cell above it or the cell to its left, and from nowhere else. Every path to a cell therefore ends with one of those two moves, so the number of paths to a cell is the sum of the numbers of paths to those two neighbours. That sum, computed for all cells in order, is dynamic programming (DP): solving each small subproblem once and reusing it.
The five things to state
- What one cell means.
table[i][j]is the number of right/down paths from the top-left cell (0, 0) to cell (i, j). - The transition.
table[i][j] = table[i-1][j] + table[i][j-1]: paths arriving from above plus paths arriving from the left. The two groups cannot overlap because the last move differs. - Base cases. The entire top row and left column are 1: there is only one way to get to a cell on the edge (all rights, or all downs), and
table[0][0] = 1for the empty path. - Fill order. Row by row, left to right, so that both neighbours are filled before the cell that reads them.
- Where the answer is.
table[m-1][n-1], the bottom-right cell.
Brute force first
The recursion go(r, c) returns 1 on the last row or last column (from there only one path remains) and otherwise adds go(r+1, c) and go(r, c+1). Counting every call, the root included, gives 55 calls for a 3 x 7 grid, 1,847 for 7 x 7 and 97,239 for 10 x 10. Each equals 2 x paths - 1 (28, 924 and 48,620 paths), because the recursion bottoms out one call per path and every branch point adds one more. With a cache keyed on (r, c) the calls are 25, 73 and 163, which is 2 x (m-1)(n-1) + 1: each interior cell is computed once and the rest are hits.
The code
import itertools
import math
import random
def paths_brute(m, n):
calls = [0]
def go(r, c):
calls[0] += 1
if r == m - 1 or c == n - 1:
return 1
return go(r + 1, c) + go(r, c + 1)
return go(0, 0), calls[0]
def paths_memo(m, n):
memo, calls = {}, [0]
def go(r, c):
calls[0] += 1
if r == m - 1 or c == n - 1:
return 1
if (r, c) not in memo:
memo[(r, c)] = go(r + 1, c) + go(r, c + 1)
return memo[(r, c)]
return go(0, 0), calls[0]
def paths_table(m, n):
"""table[i][j] = number of right/down paths from (0, 0) to (i, j)."""
table = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
table[i][j] = table[i - 1][j] + table[i][j - 1]
return table
def paths_one_row(m, n):
row = [1] * n # row 0
for _ in range(1, m):
for j in range(1, n): # left to right: row[j-1] is already this row's value
row[j] += row[j - 1]
return row[-1]
def paths_one_row_reversed(m, n):
row = [1] * n
for _ in range(1, m):
for j in range(n - 1, 0, -1): # right to left: row[j-1] is still last row's value
row[j] += row[j - 1]
return row[-1]
def paths_with_blocks(m, n, blocked):
row = [0] * n
row[0] = 0 if (0, 0) in blocked else 1
for i in range(m):
for j in range(n):
if (i, j) in blocked:
row[j] = 0
elif j > 0:
row[j] += row[j - 1]
return row[-1]
def paths_with_blocks_brute(m, n, blocked):
def go(r, c):
if r >= m or c >= n or (r, c) in blocked:
return 0
if (r, c) == (m - 1, n - 1):
return 1
return go(r + 1, c) + go(r, c + 1)
return go(0, 0)
for row in paths_table(3, 4):
print(row)
print("answer:", paths_table(3, 4)[-1][-1], "| closed form C(5, 2):", math.comb(3 + 4 - 2, 3 - 1))
print(" m n paths recursion_calls memo_calls")
for m, n in ((1, 1), (1, 5), (2, 2), (3, 7), (7, 7), (10, 10)):
value, c1 = paths_brute(m, n)
_, c2 = paths_memo(m, n)
print(f"{m:2d} {n:2d} {value:6d} {c1:16d} {c2:11d}")
moves = 3 + 4 - 2
print("3 x 4 grid: down moves sit at these positions among", moves, "moves:", list(itertools.combinations(range(moves), 2)))
print("one row, left to right:", paths_one_row(3, 7), "| right to left:", paths_one_row_reversed(3, 7))
print("18 x 18 grid:", paths_one_row(18, 18), "= C(34, 17) =", math.comb(34, 17))
print("20! fits in signed 64 bits:", math.factorial(20) <= 2**63 - 1, "| 21! fits:", math.factorial(21) <= 2**63 - 1)
print("17 x 17:", paths_one_row(17, 17), "fits in signed 32 bits:", paths_one_row(17, 17) <= 2**31 - 1, "| 18 x 18 fits:", paths_one_row(18, 18) <= 2**31 - 1)
MOD = 10**9 + 7
fact = [1]
for k in range(1, 35):
fact.append(fact[-1] * k % MOD)
via_inverse = fact[34] * pow(fact[17] * fact[17] % MOD, -1, MOD) % MOD
print("C(34, 17) mod 1e9+7 from factorials and an inverse:", via_inverse, "| direct:", math.comb(34, 17) % MOD)
print("100 x 100 grid has", len(str(paths_one_row(100, 100))), "digits")
print("3 x 3 with the centre blocked:", paths_with_blocks(3, 3, {(1, 1)}), "| start blocked:", paths_with_blocks(3, 3, {(0, 0)}))
random.seed(6)
for _ in range(400):
m, n = random.randint(1, 8), random.randint(1, 8)
expected = math.comb(m + n - 2, m - 1)
assert paths_brute(m, n)[0] == paths_memo(m, n)[0] == paths_table(m, n)[-1][-1] == paths_one_row(m, n) == expected
blocked = {(random.randrange(m), random.randrange(n)) for _ in range(random.randint(0, 4))}
assert paths_with_blocks(m, n, blocked) == paths_with_blocks_brute(m, n, blocked)
print("400 random grids: DP, closed form and brute force agree; blocked-cell variant matches brute force")
Output:
[1, 1, 1, 1]
[1, 2, 3, 4]
[1, 3, 6, 10]
answer: 10 | closed form C(5, 2): 10
m n paths recursion_calls memo_calls
1 1 1 1 1
1 5 1 1 1
2 2 2 3 3
3 7 28 55 25
7 7 924 1847 73
10 10 48620 97239 163
3 x 4 grid: down moves sit at these positions among 5 moves: [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
one row, left to right: 28 | right to left: 4
18 x 18 grid: 2333606220 = C(34, 17) = 2333606220
20! fits in signed 64 bits: True | 21! fits: False
17 x 17: 601080390 fits in signed 32 bits: True | 18 x 18 fits: False
C(34, 17) mod 1e9+7 from factorials and an inverse: 333606206 | direct: 333606206
100 x 100 grid has 59 digits
3 x 3 with the centre blocked: 2 | start blocked: 0
400 random grids: DP, closed form and brute force agree; blocked-cell variant matches brute force
Reading the output
- The filled table for a 3 x 4 grid shows the first row and first column as 1s and the answer 10 in the bottom-right corner.
- One row. Row i depends only on row i-1 and on the cell to its left, so one row of n cells is enough:
row[j] += row[j-1]. The sweep must go left to right. At the momentrow[j]is updated,row[j]still holds the value from the row above (the "from above" count) androw[j-1]has already been updated to hold the current row's value (the "from the left" count). Sweeping right to left reads the stale value ofrow[j-1]from the row above instead, and the 3 x 7 grid prints 4 instead of 28. - The closed form agrees: the 3 x 4 grid gives C(5, 2) = 10, and 18 x 18 gives 2,333,606,220 = C(34, 17).
- The check compares the plain recursion, the memoized recursion, the table, the one-row version and the closed form on 400 seeded grids, and compares the blocked-cell variant with an independent brute force.
Closed form and why prefer the DP anyway
Any path from the top-left to the bottom-right makes m-1 moves down and n-1 moves right, in some order. Choosing which of the m+n-2 moves are the downward ones gives C(m+n-2, m-1) paths, computed by math.comb with no table. C(N, k), read "N choose k", is the number of ways to pick k items out of N when the order of picking does not matter. Here a path is a string of moves such as down, right, right, down, right, and it is fixed completely by the positions of its downs; so the number of paths is the number of ways to pick those positions. For the 3 x 4 grid there are 5 moves, 2 of them down, and the program prints the 10 possible position pairs, matching C(5, 2) = 10 and the table's corner. Still, the DP is usually the answer an interviewer wants, for these reasons:
- Obstacles. Blocked cells break the counting argument but not the DP: set the blocked cell to 0 and the same sum applies. The variant in the code gives 2 paths for a 3 x 3 grid with the centre blocked and 0 if the start is blocked, and matches brute force in the random check.
- Other constraints, such as costs, or a rule that forbids a move, extend the DP in one line and have no closed form.
- Overflow. In a fixed-width language (one where integers have a fixed size, such as 32 or 64 bits, and overflow when a result is too large) the factorial route breaks first: 20! fits in a signed 64-bit integer (a whole number with a sign, at most 2^63 - 1, about 9.2 x 10^18) and 21! does not (printed above), so
n!cannot be computed directly for the larger grids, whereas the DP only adds numbers no larger than the answer. The DP result itself exceeds a signed 32-bit integer (at most 2^31 - 1 = 2,147,483,647) at 18 x 18 (17 x 17 fits). A 100 x 100 grid has 59 digits, so a modulus (such as 10^9+7) must be applied at each addition in a fixed-width language. For a huge grid with a modulus, the closed form with precomputed factorials and modular inverses is the faster tool, which is a good thing to say out loud. The idea: C(N, k) = N! / (k! (N-k)!), and under a prime modulus you cannot divide, but you can multiply by the modular inverse of the denominator (the number x with x times the denominator leaving remainder 1; Python'spow(d, -1, MOD)finds it). The factorials up to N are computed once, so each query costs a few multiplications; the program prints C(34, 17) this way next to the direct value. Interviews typically stop at the DP and themath.combformula, and this large-grid route is deeper material.
Complexity
| Version | States x work per state | Time | Space |
|---|---|---|---|
| Plain recursion | 2 x paths - 1 calls x O(1) | O(C(m+n-2, m-1)) | O(m + n) call depth |
| Memoized | (m-1)(n-1) interior states x O(1) | O(mn) | O(mn) plus O(m + n) depth |
| Table | mn cells x O(1) | O(mn) | O(mn) |
| One row | mn updates x O(1) | O(mn) | O(n) |
Closed form with math.comb | one binomial coefficient | depends on the size of the big integers involved | O(1) extra |
To get O(min(m, n)) space, make the row the shorter dimension.
Common mistakes
- Sweeping the single row right to left.
- Treating a one-row or one-column grid as a special case that needs work; the answer is 1, as the 1 x 5 row of the table shows.
Running the code
python3.12 grid_paths.py
Standard library only. Save the listing as grid_paths.py and run the command above; it prints exactly the output shown.
You need to fetch 1000 keys from Redis in a Python service, and doing it with 1000 individual GET calls is killing your latency budget. Write code for a more efficient approach, explain why it's faster, and call out what could still go wrong at that batch size.
Sample Answer
Why 1000 individual GETs is slow
Each GET is a full network round trip: send the command, wait for Redis to process it, wait for the response, before the next one can start (unless you're pipelining, batching multiple commands onto the wire together and reading all the responses back afterward, without waiting on each one individually, which is what the r.pipeline(transaction=False) call below does when loading the test data). At even a modest 0.5ms round trip, 1000 sequential calls is 500ms of pure network waiting, independent of how fast Redis itself is at looking the key up.
A faster approach: batch the request
Send all 1000 keys as a single command instead of 1000 separate ones, using MGET, which returns a list of values in the same order as the keys you asked for (with None/nil for any key that doesn't exist).
import time
import redis
r = redis.Redis(host="127.0.0.1", port=6399, decode_responses=True)
keys = [f"product:{i}" for i in range(1000)]
pipe = r.pipeline(transaction=False)
for i, k in enumerate(keys):
pipe.set(k, f"value-{i}")
pipe.execute()
# Slow way: one GET per key = 1000 network round trips.
start = time.perf_counter()
slow_results = [r.get(k) for k in keys]
slow_elapsed = time.perf_counter() - start
# Fast way: MGET sends all 1000 keys in a single request/response round trip.
start = time.perf_counter()
fast_results = r.mget(keys)
fast_elapsed = time.perf_counter() - start
print("results match:", slow_results == fast_results)
print(f"1000x GET: {slow_elapsed * 1000:.1f} ms")
print(f"1x MGET: {fast_elapsed * 1000:.1f} ms")
print(f"speedup: {slow_elapsed / fast_elapsed:.1f}x")
Output (measured on a local Redis instance; exact numbers vary by machine and network, but the shape holds):
results match: True
1000x GET: 638.5 ms
1x MGET: 1.6 ms
speedup: 390.2x
Why it's faster
MGET collapses 1000 round trips into one: the client sends every key in a single request, and Redis returns every value in a single response. The per-call network latency, which dominated the slow version, is paid exactly once instead of a thousand times.
What could still go wrong at that batch size
- In Redis Cluster mode, keys can be spread across different nodes by hash slot. A single
MGETacross keys that don't share a hash slot will fail (aCROSSSLOTerror); you'd need to group keys by slot first, or use a hash tag (like{user123}.name,{user123}.email) to force related keys onto the same slot. - Redis processes most commands on a single thread; a very large
MGET(or a much bigger batch than 1000) can briefly block other clients while it's being served, so there's a point past which batching further hurts overall latency for everyone else rather than helping. - If any of the 1000 keys are missing,
MGETreturnsNonein that position rather than raising an error, the caller must check for that positionally instead of assuming every key resolved. - A very large response (1000 large values) can be a meaningful chunk of memory and bandwidth in one shot; if values are large, batching in smaller chunks (say 100 at a time) trades off round trips against peak response size.
Implement a rolling-hash based substring search (Rabin-Karp) in Java that finds all occurrences of a fixed-length pattern in a text. Use base=256 and mod=1000000007. Show how to update the rolling hash in O(1) when sliding the window and describe how to handle and detect hash collisions.
Sample Answer
The idea
Rabin-Karp compares numbers instead of strings. Read each length-m window of the text as a number in base 256 (one "digit" per character), reduce it modulo a prime (take the remainder after dividing by a prime number MOD, so the value stays small) so it fits in a long, and compare it with the pattern's number. A window whose number differs cannot be a match. When the numbers agree the code compares the actual characters, because two different strings can produce the same number (a hash collision). The rolling update turns the hash of window i into the hash of window i+1 in O(1): remove the leading character's contribution, shift everything one place (multiply by the base), and add the new character.
The update formula
With high = BASE^(m-1) mod MOD (the weight of the leading character):
window = ((window - text[i] * high) mod MOD * BASE + text[i+m]) mod MOD
Two Java details matter. The product text[i] * high is at most 65,535 * (10^9 + 6), about 6.6 * 10^13, and window * BASE is under 10^9 * 256; both fit in a 64-bit long (max about 9.2 * 10^18), so no overflow occurs. And Java's % takes the sign of its left operand, so window - drop can be negative; the code adds mod before the remainder (+ mod) to keep the hash in [0, MOD).
The slide with real numbers
Here m = 3, so high = 256^2 = 65,536. Start from window zab, whose hash is 8,020,322 (printed below).
- Drop
z(code 122):122 * 65,536 = 7,995,392, and8,020,322 - 7,995,392 = 24,930. What is left is the hash ofabas a two-digit number. - Shift left by one place:
24,930 * 256 = 6,382,080. - Add the new character
c(code 99):6,382,080 + 99 = 6,382,179, which is the hash ofabc.
The next slide drops a (97) and adds p (112): 97 * 65,536 = 6,356,992, then 6,382,179 - 6,356,992 = 25,187, then 25,187 * 256 + 112 = 6,447,984, the printed hash of bcp. Every value here is below the modulus, so no remainder changes anything; the remainder only matters once a window is long enough to exceed 1,000,000,007.
Code
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RabinKarp {
static final long BASE = 256;
static final long MOD = 1_000_000_007L;
// Returns every start index of pattern in text. falsePositives[0] counts hash hits that failed verification.
static List<Integer> search(String text, String pattern, long mod, int[] falsePositives, boolean verbose) {
int n = text.length(), m = pattern.length();
List<Integer> hits = new ArrayList<>();
if (m == 0) {
for (int i = 0; i <= n; i++) hits.add(i);
return hits;
}
if (m > n) return hits;
long high = 1; // BASE^(m-1) mod mod, the weight of the leading char
for (int i = 1; i < m; i++) high = high * BASE % mod;
long target = 0, window = 0;
for (int i = 0; i < m; i++) {
target = (target * BASE + pattern.charAt(i)) % mod;
window = (window * BASE + text.charAt(i)) % mod;
}
for (int i = 0; i + m <= n; i++) {
if (verbose) System.out.println(" window " + i + " " + text.substring(i, i + m) + " hash=" + window + " target=" + target);
if (window == target) {
if (text.startsWith(pattern, i)) hits.add(i); // verify: equal hashes do not imply equal strings
else falsePositives[0]++;
}
if (i + m < n) {
long drop = text.charAt(i) * high % mod;
window = ((window - drop + mod) % mod * BASE + text.charAt(i + m)) % mod; // + mod keeps it non-negative
}
}
return hits;
}
// Same loop without the "+ mod" fix: Java's % keeps the sign of the dividend.
static List<Integer> searchNegativeBug(String text, String pattern, long mod) {
int n = text.length(), m = pattern.length();
List<Integer> hits = new ArrayList<>();
long high = 1;
for (int i = 1; i < m; i++) high = high * BASE % mod;
long target = 0, window = 0;
for (int i = 0; i < m; i++) {
target = (target * BASE + pattern.charAt(i)) % mod;
window = (window * BASE + text.charAt(i)) % mod;
}
for (int i = 0; i + m <= n; i++) {
if (window == target && text.startsWith(pattern, i)) hits.add(i);
if (i + m < n) window = ((window - text.charAt(i) * high % mod) * BASE + text.charAt(i + m)) % mod;
}
return hits;
}
static List<Integer> naive(String text, String pattern) {
List<Integer> hits = new ArrayList<>();
for (int i = 0; i + pattern.length() <= text.length(); i++)
if (text.startsWith(pattern, i)) hits.add(i);
return hits;
}
public static void main(String[] args) {
int[] fp = new int[1];
System.out.println("zabcp / abc, mod 1e9+7:");
System.out.println(search("zabcp", "abc", MOD, fp, true));
System.out.println("ababa / aba: " + search("ababa", "aba", MOD, fp, false));
System.out.println("empty pattern in 'abc': " + search("abc", "", MOD, fp, false));
System.out.println("pattern longer than text: " + search("ab", "abc", MOD, fp, false));
System.out.println("negative-modulo bug, mod 101: " + searchNegativeBug("zabcpqrabc", "abc", 101)
+ " vs correct " + search("zabcpqrabc", "abc", 101, fp, false));
Random rnd = new Random(42);
String alphabet = "abé日本";
int falseAlarms = 0;
for (int t = 0; t < 3000; t++) {
StringBuilder s = new StringBuilder(), p = new StringBuilder();
int n = rnd.nextInt(40), m = rnd.nextInt(5);
for (int i = 0; i < n; i++) s.append(alphabet.charAt(rnd.nextInt(alphabet.length())));
for (int i = 0; i < m; i++) p.append(alphabet.charAt(rnd.nextInt(alphabet.length())));
long mod = (t % 2 == 0) ? MOD : 101;
int[] f = new int[1];
List<Integer> got = search(s.toString(), p.toString(), mod, f, false);
if (!got.equals(naive(s.toString(), p.toString()))) throw new AssertionError(s + " / " + p);
if (mod == 101) falseAlarms += f[0];
}
System.out.println("3000 random cases (half with mod 101, wide chars) match the naive scan; hash hits rejected by verification (mod 101 runs): " + falseAlarms);
}
}
Output (Java 21, Temurin, in a container):
zabcp / abc, mod 1e9+7:
window 0 zab hash=8020322 target=6382179
window 1 abc hash=6382179 target=6382179
window 2 bcp hash=6447984 target=6382179
[1]
ababa / aba: [0, 2]
empty pattern in 'abc': [0, 1, 2, 3]
pattern longer than text: []
negative-modulo bug, mod 101: [] vs correct [1, 7]
3000 random cases (half with mod 101, wide chars) match the naive scan; hash hits rejected by verification (mod 101 runs): 150
Reading the output
- For
abcinzabcpthe pattern hash is 6,382,179. Becauseabcas a base-256 number (97*256^2 + 98*256 + 99) is below the modulus 1,000,000,007, the hash equals the exact number. Window 0 (zab) gives 8,020,322, window 1 (abc) matches, window 2 (bcp) gives 6,447,984, so only window 1 is verified, giving[1]. - Overlapping matches:
abainababagives[0, 2]. - Negative-modulo pitfall: with modulus 101, searching
abcinzabcpqrabcgives[]without the+ modfix, because the negative window hash can never equal the non-negative pattern hash (a silent wrong answer, no exception), and[1, 7]with it. - The random test compares the result with a plain
startsWithscan on 3,000 seeded random inputs over the alphabeta,b,é,日,本; half run with modulus 101 so collisions actually happen (150 hash hits were rejected by the verification step), and every result still matches.
Choosing base and modulus
- The modulus should be a prime well above the number of windows: a text with W windows and a modulus near W makes collisions between unrelated windows likely, since each window has about a 1 in MOD chance of matching the pattern's hash by accident, so the expected number of wasted verifications is about W / MOD. With 10^9 + 7 and a text of a million windows that is about one in a thousand. 10^9 + 7 also keeps all intermediate products inside a
long; a much larger modulus needs wider multiplication (for example 128-bit arithmetic, a multiply whose result is twice as many bits wide as along). - The base is normally at least the alphabet size. Java
charvalues go up to 65,535, larger than 256. Correctness is unaffected because every hash hit is verified; the hash is still a polynomial modulo a prime, and only the collision rate is a concern. - A fixed, known pair (256, 10^9 + 7) can be attacked with crafted strings that all collide, which turns every window into a verification and the search into O(n*m). In a service that searches untrusted text, choose the base at random at startup (any value from 2 to MOD - 2); for a random base the collision chance for two distinct strings of length m is at most (m - 1) / (MOD - 3), which is about (m - 1) / MOD. The reason: two strings collide when the polynomial formed by their character differences, which is not zero and has degree below m, evaluates to 0 mod MOD at the base. A nonzero polynomial of degree d has at most d roots modulo a prime (for example
x^2 - 5x + 6is 0 only at x = 2 and x = 3), so at most m - 1 of the MOD - 3 allowed bases cause a collision. An attacker who cannot see the random base cannot craft such strings. This kind of crafted-collision attack on a hash table or search is often called hash flooding. - Wide alphabets: Java strings are UTF-16, so
charAtreturns code units, and a character outside the Basic Multilingual Plane (the first 65,536 Unicode code points, the ones that fit one UTF-16 code unit, a 16-bit value) such as an emoji is two units. This code therefore matches by code unit; hashcodePoints()instead if you need code point semantics.
Handling and detecting collisions
Detection is the startsWith check on every hash hit; falsePositives counts the rejected ones. A hash hit that fails verification is a collision, never a result. Without verification a collision gives a wrong match.
Complexity
- Expected time O(n + m): O(m) to hash the pattern and the first window, O(1) per slide, and O(m) verification only on a hash hit (true matches, plus rare collisions).
- Worst case O(n*m) when many windows hit (all windows equal the pattern, as in
aaaa.../aaa, or an adversarial text). - Space O(1) beyond the result list;
startsWithdoes not allocate. (Thesubstringcall in the verbose trace is the only allocation and exists just for printing.)
Edge cases
Empty pattern returns all indices 0..n; a pattern longer than the text returns an empty list; a pattern equal to the text works (one window); text and pattern that contain characters above 255 work because hashes are verified.
Running the code
javac RabinKarp.java && java RabinKarp
Used with JDK 21; no other config.
Recommended Additional Resources
- LeetCode (focus on medium-hard problems, company-tagged questions for FAANG)
- System Design Primer (GitHub repo - free comprehensive system design resource)
- Cracking the Coding Interview (book - classic preparation guide for FAANG interviews)
- Designing Data-Intensive Applications (book - deep dive into backend architecture)
- The Art of Computer Systems Performance Analysis (book - scalability fundamentals)
- AWS & Azure documentation and white papers (cloud infrastructure knowledge)
- Backend engineering blogs from FAANG companies (Google Cloud Blog, AWS Architecture Blog, Meta Engineering)
- InterviewBit & InterviewKickstart (curated coding and system design problems)
- Exponent & Interviewpen (structured system design mock interviews)
- FAANG-specific resources: Blind, TeamBlind community for real interview experiences
Search Results
Top 70 Coding Interview Questions and Answers for 2026
This article will discuss the top 70 coding interview questions you should know to crack those interviews and get your dream job.
Amazon Software Engineer Interview Guide: Process + Questions
Get ready for the Amazon software engineer interview with this in-depth guide. Learn the 2025 hiring process, coding questions, system design tips, ...
Top 50+ Software Engineering Interview Questions and Answers
Software Engineering is the discipline of applying engineering principles to the design, development, testing, and maintenance of software systems.
Meta Software Engineer Interview (questions, process, prep)
The questions are tough, highly specific to Meta, and cover a broad range of technical and conceptual topics. To stand out, you'll need to show a strong coding ...
Top FAANG+ Coding Interview Questions for Software Engineers
Below are some sample Java coding interview questions: Write a program to check if two 2-dimensional arrays contain identical elements.
50 Most Popular Salesforce Interview Questions & Answers ...
41. At a high level, can you describe the Software Development Lifecycle? · 42. Can you name a few ways to help improve Salesforce user adoption? · 43. What can ...
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 Backend Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs