Meta Mobile Developer (Entry Level) - Comprehensive Interview Preparation Guide
Meta's interview process for entry-level mobile developers consists of an initial recruiter screening followed by 1-2 technical phone screens with coding assessments. Successful candidates advance to the onsite stage (typically 4 rounds) featuring Meta's AI-enabled multi-part coding interview, system design fundamentals, mobile development technical assessment, and behavioral evaluation. The entire process spans 4-8 weeks and emphasizes problem-solving ability, code quality, mobile platform knowledge, technical communication, and cultural fit.
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with Meta recruiter lasting 20-30 minutes. This is a non-technical round focused on understanding your background, career motivation, and cultural fit. The recruiter will walk you through the interview process, confirm your interest in mobile development, and address logistical questions. They'll also gather information about your experience with iOS and/or Android development, your familiarity with cross-platform frameworks, and your reasons for applying to Meta. This round determines whether you advance to technical phone screens.
Tips & Advice
Be genuine and enthusiastic about mobile development and Meta's products. Prepare a 2-minute summary of your background, focusing on mobile development experience if you have it. Research Meta's mobile products (Instagram, WhatsApp, Messenger, Threads) and mention genuine interest in one or two. Ask thoughtful questions about the team, role expectations, and mobile technology stack at Meta. Have a Metacareers account created before this call. Clarify whether the role emphasizes iOS, Android, or cross-platform development.
Focus Topics
Clarifying Role Focus
Ask and understand whether the role focuses on iOS, Android, React Native, or a mix of platforms
Practice Interview
Study Questions
Mobile Development Experience
Overview of any iOS, Android, or cross-platform projects you've built or contributed to
Practice Interview
Study Questions
Career Motivation and Background Story
Concise explanation of your professional journey and why you're interested in mobile development
Practice Interview
Study Questions
Why Meta Specifically
Articulate reasons for applying to Meta over other companies; reference Meta's mobile products and mission
Practice Interview
Study Questions
Technical Phone Screen 1 - Coding Fundamentals
What to Expect
First technical interview lasting approximately 45 minutes conducted over phone/video with a Meta engineer. Expect 5-10 minutes of introductions and behavioral questions, followed by 35-40 minutes of coding. You'll solve one to two LeetCode-style problems of easy to medium difficulty, often related to arrays, strings, linked lists, or basic algorithms. The interviewer will assess your ability to clarify requirements, write clean code, think through edge cases, and communicate your approach. You're expected to write and execute working code. The session may touch on mobile-specific context (e.g., sorting a list of app names, handling API response data structures) but fundamentals are the primary focus.
Tips & Advice
Practice LeetCode problems at easy-to-medium difficulty; aim to solve 30-50 problems covering arrays, strings, hash maps, and basic graph traversal. Write code that is clean, readable, and well-structured—variable names matter. Always clarify the problem statement before coding: ask about input constraints, edge cases, and expected output format. Speak through your thought process but avoid over-narration. Test your code mentally or by walking through examples before submitting. If stuck, communicate your block to the interviewer—they appreciate transparency. You don't need to be perfectly fast; accuracy and communication matter more. Have a whiteboard or paper nearby to sketch out ideas if it helps your thinking.
Focus Topics
Problem Clarification and Communication
Asking clarifying questions about constraints, edge cases, and output format before coding
Practice Interview
Study Questions
Edge Case Identification
Recognizing and handling boundary conditions like empty inputs, single elements, negative numbers, and duplicates
Practice Interview
Study Questions
Basic Algorithm Patterns
Common patterns like two pointers, sliding window, binary search, and BFS/DFS
Practice Interview
Study Questions
Array and String Manipulation
Operations like searching, sorting, filtering, and transforming arrays and strings
Practice Interview
Study Questions
Hash Maps and Dictionaries
Using key-value pairs for fast lookups, grouping, and deduplication
Practice Interview
Study Questions
Technical Phone Screen 2 - Coding Problem-Solving
What to Expect
Second technical interview lasting approximately 45 minutes, conducted over phone/video with a different Meta engineer. Similar format to Phone Screen 1: 5-10 minutes introductions, followed by 35-40 minutes of coding. This screen typically features a medium-difficulty problem that may involve slightly more complex data structures or algorithms (e.g., linked lists, basic trees, or problems requiring nested loops). The interviewer assesses your ability to optimize solutions, handle complex scenarios, and articulate trade-offs. You may be asked to improve a brute-force solution or extend a problem with new requirements. Focus on code quality, clarity, and the reasoning behind your approach.
Tips & Advice
After Phone Screen 1, continue practicing medium-difficulty LeetCode problems. Focus on problems involving linked lists, trees, and problems that require optimization (e.g., improving time complexity from O(n²) to O(n log n)). Understand trade-offs between time and space complexity; be ready to discuss why you chose a particular approach. If asked to optimize, always explain what you're optimizing for and why. Practice writing code that's easy to extend—if the interviewer adds a constraint mid-problem, your code structure should adapt cleanly. Use meaningful variable names and add brief comments for complex logic. Stay calm if you don't immediately know the optimal solution; demonstrating your thought process is valuable.
Focus Topics
Code Extensibility
Writing code that handles requirement changes without major refactoring
Practice Interview
Study Questions
Linked List Operations
Traversal, reversal, cycle detection, and merging of linked lists
Practice Interview
Study Questions
Solution Optimization
Improving brute-force solutions and making trade-off decisions between time and space
Practice Interview
Study Questions
Tree Traversal and Basic Tree Problems
In-order, pre-order, post-order traversal; finding height, LCA, and path sums
Practice Interview
Study Questions
Time and Space Complexity Analysis
Understanding Big-O notation and analyzing your solution's efficiency
Practice Interview
Study Questions
Onsite Round 1 - AI-Enabled Multi-Part Coding Interview
What to Expect
In-person or virtual coding interview lasting 60 minutes, conducted with a Meta engineer. This is Meta's signature AI-enabled coding round where you work through one multi-part problem structured into 2-3 stages. The problem often involves building or extending functionality from scratch or working with a partial implementation. For mobile developers, problems might involve app logic like building a feature within an existing codebase (e.g., adding filtering to a list, implementing a cache, or handling state). You have access to AI assistance (like Copilot in CoderPad) but using it is optional—Meta evaluates your ability to think critically and make informed decisions, not how much you use AI. You're expected to run code, read test failures, debug in real time, and iterate. The interviewer observes how you understand existing code, extend systems, and ensure solutions meet requirements.
Tips & Advice
This round rewards running and iterating over perfection. Start by understanding the problem deeply: restate it in your own words, clarify inputs/outputs/constraints, and identify edge cases. Create a visible requirements checklist before coding. Use the AI as a scaffolding tool—ask it to generate boilerplate or test templates, but always review and understand the generated code. Run your code early and often; don't wait until the end. When tests fail, read the failure messages carefully and debug methodically. Communicate your next steps while the AI generates code. After runs, summarize what passed/failed and what you'll fix. Mention complexity and acknowledge trade-offs. Practice this round format extensively before your interview; the ability to iterate and debug in real-time is critical.
Focus Topics
Technical Communication and Reasoning
Explaining your approach, discussing trade-offs, asking clarifying questions, and incorporating feedback
Practice Interview
Study Questions
Code Quality and Maintainability
Writing clean, readable, well-structured code with meaningful names; evaluating and improving code quality
Practice Interview
Study Questions
Debugging and Iterating
Reading error messages, identifying bugs, fixing code in real-time, and re-running tests
Practice Interview
Study Questions
Code Navigation and Understanding Existing Codebases
Reading and building on partial implementations, understanding code structure, and extending working code
Practice Interview
Study Questions
Writing and Running Tests
Creating test cases covering golden path and edge cases, running tests, and reading test output
Practice Interview
Study Questions
Problem Clarification and Requirements Definition
Restating problems, identifying inputs/outputs, constraints, edge cases, and defining clear requirements checklist
Practice Interview
Study Questions
Onsite Round 2 - System Design Fundamentals
What to Expect
In-person or virtual interview lasting 45-60 minutes with a Meta engineer or architect. This round assesses your understanding of how systems and applications are designed at scale. For entry-level mobile developers, expect questions focused on foundational system design concepts as they apply to mobile apps—for example, designing a feature like a newsfeed, caching strategy for an image-heavy app, or how a mobile app communicates with backends. You'll discuss trade-offs, scalability considerations, and mobile-specific challenges (network latency, battery efficiency, offline-first design). The interviewer is not expecting you to design Netflix infrastructure; rather, they want to see that you understand how mobile clients fit into larger systems and can reason about basic architectural decisions. You should be able to sketch diagrams (on whiteboard or virtual drawing tool) and articulate why certain choices matter for mobile platforms.
Tips & Advice
Study basic system design principles: client-server architecture, APIs, caching, databases, and load balancing. For mobile-specific design, focus on: how mobile apps fetch and cache data, offline-first strategies, network optimization, battery efficiency, and security. Draw and explain diagrams clearly—the visual communication is important. Practice discussing trade-offs: consistency vs availability, latency vs bandwidth, battery life vs feature richness. Familiarize yourself with common mobile architecture patterns (MVC, MVP, MVVM) and why they matter. When given a problem, start by asking clarifying questions about scale (number of users, devices, data volume), requirements (latency, consistency, security), and constraints. At entry-level, don't overcomplicate your design; focus on clarity and explaining fundamental concepts. Research Meta products (Instagram Stories, Messenger) and understand at a high level how they likely work—this shows genuine interest.
Focus Topics
Basic Architecture Patterns (MVC/MVP/MVVM)
Structural patterns for organizing mobile app code, separation of concerns, and testability
Practice Interview
Study Questions
Mobile Network Optimization
Minimizing network requests, batching requests, handling network latency, and offline-first design
Practice Interview
Study Questions
Battery Efficiency and Performance
Impact of background tasks, location services, push notifications, and how design affects battery drain
Practice Interview
Study Questions
Caching Strategies for Mobile
In-memory caching, disk caching, cache invalidation, and trade-offs for resource-constrained devices
Practice Interview
Study Questions
Client-Server Architecture and APIs
How mobile apps communicate with backends, REST vs GraphQL basics, request/response patterns
Practice Interview
Study Questions
Onsite Round 3 - Mobile Development Technical Assessment
What to Expect
In-person or virtual interview lasting 45-60 minutes with a mobile platform specialist (iOS or Android engineer, or React Native/Flutter expert depending on the role focus). This round dives deep into mobile platform-specific knowledge and problem-solving. You may be asked to write platform-specific code (Swift for iOS, Kotlin for Android, or JavaScript/TypeScript for React Native), discuss lifecycle management, handle asynchronous operations, manage state, implement UI components, or debug common mobile issues. You might work on a small project like building a simple screen with a network request, handling user input, or integrating a third-party SDK. The focus is on your practical mobile development skills, understanding of the platform you're specializing in, and ability to build features end-to-end within the mobile environment. For entry-level, the expectations are foundational: you should know your platform's fundamentals, common patterns, and be able to write working code.
Tips & Advice
Deepen your expertise in your primary platform (iOS, Android, or cross-platform framework). If iOS: master Swift syntax, UIKit or SwiftUI basics, view controllers, delegation, and common design patterns. If Android: master Kotlin syntax, Activity and Fragment lifecycle, RecyclerView, coroutines, and modern Android architecture. If React Native: master JavaScript/TypeScript, React hooks, navigation, and platform-specific APIs. Practice writing small projects end-to-end: build a screen that fetches data from a mock API, displays it in a list, handles errors, and responds to user interactions. Understand and be able to explain: your platform's threading model, how to handle asynchronous operations, state management approaches, and common performance pitfalls. Know how to use debugging tools on your platform. Be familiar with the app store deployment process (basics like versioning and signing). For entry-level, you're not expected to be expert-level, but you should be fluent in fundamentals and eager to learn.
Focus Topics
Performance and Battery Optimization
Writing efficient code, avoiding memory leaks, and minimizing battery drain
Practice Interview
Study Questions
State Management
Managing application state, handling data flow, and persisting user data locally
Practice Interview
Study Questions
Mobile-Specific Features (Push Notifications, Camera, Location, Storage)
Implementing platform capabilities and integrating third-party SDKs
Practice Interview
Study Questions
Networking and API Integration
Making HTTP requests, parsing JSON responses, handling errors, and working with RESTful or GraphQL APIs
Practice Interview
Study Questions
Asynchronous Programming and Threading
Handling network requests, background tasks, and managing main thread vs background threads
Practice Interview
Study Questions
Platform Fundamentals (iOS: Swift, UIKit/SwiftUI; Android: Kotlin, Activity/Fragment; Cross-platform: React Native/Flutter)
Language syntax, core framework concepts, view/component lifecycle, and basic UI development
Practice Interview
Study Questions
Onsite Round 4 - Behavioral and Cultural Fit Interview
What to Expect
In-person or virtual interview lasting 30-45 minutes with a Meta manager, team lead, or senior engineer. This round assesses your cultural alignment, teamwork, communication, and past experience. Expect behavioral questions about challenges you've faced, how you handle feedback, collaboration with teammates, conflict resolution, and motivation. The interviewer will ask about your career goals, why Meta, and what you're looking for in a team. This is your opportunity to demonstrate Meta values: Focus on Impact, Move Fast, Be Direct, Build What the World Needs, and Live the Mission. Prepare concrete examples from your education, internships, or projects that show these values in action. For entry-level, interviewers understand you're early in your career; they're evaluating your ability to learn, collaborate, and grow. They're also assessing whether you'll thrive in Meta's fast-paced environment.
Tips & Advice
Prepare 5-7 concrete stories using the STAR method (Situation, Task, Action, Result) that demonstrate Meta's core values. Examples: a time you delivered something fast despite constraints (Move Fast), a time you gave or received critical feedback (Be Direct), a project where you focused on user impact (Focus on Impact), or a time you collaborated cross-functionally to solve a problem. Research Meta's mobile products and understand how they impact billions of users (Build What the World Needs). Practice telling your stories out loud to make them sound natural, not rehearsed. Be authentic and honest—interviewers can detect insincerity. For entry-level, it's okay to draw examples from school projects, internships, or personal projects if you don't have extensive professional experience. Show genuine curiosity about the team, product, and culture. Ask thoughtful questions about the team's goals, how they measure impact, and what success looks like. Avoid generic questions. Listen carefully to the interviewer and adapt your answers to what they're looking for.
Focus Topics
Learning and Growth Mindset
Examples of learning new skills, adapting to feedback, and taking on stretch challenges
Practice Interview
Study Questions
Teamwork and Collaboration
Examples of working effectively with designers, backend engineers, product managers, or teammates; handling disagreements constructively
Practice Interview
Study Questions
Meta Core Value: Be Direct
Stories about giving or receiving honest feedback, having difficult conversations, and valuing transparency
Practice Interview
Study Questions
Meta Core Value: Focus on Impact
Projects where you prioritized user outcomes over technical perfection; examples of shipping features that mattered
Practice Interview
Study Questions
Meta Core Value: Move Fast
Examples of shipping quickly, making decisions under uncertainty, and iterating based on feedback
Practice Interview
Study Questions
Tell Me About Yourself
Concise personal narrative covering background, key accomplishments, and career focus on mobile development
Practice Interview
Study Questions
Frequently Asked Mobile Developer Interview Questions
In sparse vector manipulation you may want to move zeros to the end while keeping relative order of nonzero elements. Given an integer array, implement a Python in-place algorithm that moves all zeros to the end. Example: input = [0,1,0,3,12] -> [1,3,12,0,0]. Explain how this helps when compressing sparse representations.
Sample Answer
Direct answer
Use a single read/write pointer pass: keep a write index starting at 0, and for every element you read that is nonzero, swap it into position write and advance write. By the time the scan finishes, every nonzero element has been moved (in its original relative order) into the front of the array, and every zero has been pushed toward the back, all without any extra array. This is O(n) time and O(1) extra space, a single linear pass with two pointers moving at different speeds.
Structured elaboration
Why a two-speed pointer pair works. The read pointer visits every element exactly once. The write pointer only ever advances when a nonzero element is found, so it always points at the next open slot for a nonzero value. Because write <= read at all times, swapping nums[read] into nums[write] never overwrites an element read hasn't looked at yet; the elements between write and read (if any gap has opened up) are exactly the zeros collected so far, and the swap places one of them further back, which is what keeps zeros trailing.
Why relative order among nonzero elements is preserved. Nonzero elements are written into the front of the array in the exact order the read pointer encounters them, since each one gets a swap into the next available write slot in sequence. No nonzero element ever gets moved past another nonzero element, which is the "keeping relative order" requirement in the question.
Connection to sparse-vector compression. A sparse vector's useful information is its nonzero entries and their positions; long runs of zeros carry no information beyond "there are this many." Once all nonzero values have been compacted to a contiguous prefix of the array (which is exactly what this routine produces), a sparse representation becomes cheap to derive: store just the compacted prefix (the nonzero values and, for a true sparse encoding, their original indices) plus a single count of how many trailing zeros were dropped, rather than storing every zero explicitly. In other words, this in-place partition is the mechanical first step that turns a dense array into something ready to be run-length-encoded or converted into a (value, index) sparse pair list, since it groups all the "real" data together and reduces the zero tail to a single number.
Worked example
Full runnable code with pinned test cases, including the question's own example:
def move_zeroes(nums):
"""In-place: move all zeros to the end, keep relative order of nonzero
elements. O(n) time, O(1) extra space. Single read/write pointer pass."""
write = 0
for read in range(len(nums)):
if nums[read] != 0:
nums[write], nums[read] = nums[read], nums[write]
write += 1
return nums
if __name__ == "__main__":
tests = [
([0, 1, 0, 3, 12], [1, 3, 12, 0, 0]),
([0, 0, 0], [0, 0, 0]),
([1, 2, 3], [1, 2, 3]),
([0], [0]),
([], []),
([4, 0, 5, 0, 0, 6], [4, 5, 6, 0, 0, 0]),
]
for arr, expected in tests:
arr_copy = list(arr)
result = move_zeroes(arr_copy)
print(f"input={arr!r:20} -> {result!r:22} (expected {expected!r})")
Output (actual run):
input=[0, 1, 0, 3, 12] -> [1, 3, 12, 0, 0] (expected [1, 3, 12, 0, 0])
input=[0, 0, 0] -> [0, 0, 0] (expected [0, 0, 0])
input=[1, 2, 3] -> [1, 2, 3] (expected [1, 2, 3])
input=[0] -> [0] (expected [0])
input=[] -> [] (expected [])
input=[4, 0, 5, 0, 0, 6] -> [4, 5, 6, 0, 0, 0] (expected [4, 5, 6, 0, 0, 0])
Given [0, 1, 0, 3, 12] -> [1, 3, 12, 0, 0] from the last test above: the nonzero values 1, 3, 12 land at indices 0, 1, 2 in exactly the order they appeared, and the two zeros are pushed to indices 3 and 4. A sparse representation could then be stored as nonzeros=[1, 3, 12] (with original positions [1, 3, 4] recorded separately if needed) plus trailing_zero_count=2, instead of keeping five explicit slots.
Trade-offs and pitfalls
- Building a new array (copy nonzero elements into a fresh list, then append zeros) is simpler to write correctly on the first try, but costs O(n) extra space; naming it as a valid baseline before presenting the in-place two-pointer version shows you understand what the O(1)-space constraint is actually buying.
- A common bug: swapping unconditionally instead of only when
nums[read] != 0, which would just be an identity/no-op most of the time but risks a wasted swap whenread == write; the code above avoids extra work here since a self-swap is harmless, but it's worth being explicit that the swap is a genuine no-op in that case, not a source of a bug. - This partition preserves order at the cost of doing real swaps (not just overwrites), which is necessary specifically because order matters; if order among the nonzero elements didn't matter, a simpler two-pointer partition (like Dutch National Flag style) could do fewer writes.
- The "sparse compression" framing is a motivation for why this operation is useful, not an added algorithmic requirement: the core routine here is doing the compaction only, and a full sparse-vector encoder would be a separate downstream step (recording positions, applying run-length encoding to the zero tail) built on top of this compacted array.
- If the array holds
-0.0(a floating-point negative zero) rather than integers, remember that-0.0 == 0.0isTruein most languages, so it should still be treated as a zero for this purpose; the code above already handles this correctly since it uses!=for comparison rather than checking sign or type.
Rewrite a dense, jargon-heavy sentence or short paragraph into a direct, plain-language version that keeps the meaning but removes filler words and unnecessary qualifiers.
Sample Answer
Direct answer
Read the sentence for what it is actually trying to say, restate that meaning in the fewest plain words, and remove verbal padding (filler words, unnecessary qualifiers, and jargon that doesn't add precision) rather than just shortening it mechanically.
Structured elaboration
- Separate meaning from wording first. Read the sentence and paraphrase its actual point out loud in your own words before touching the original text; this stops you from just deleting words from the existing structure and instead lets you rebuild a clean sentence.
- Remove filler and hedges: "um," "like," "you know," "sort of," "basically," "at the end of the day," and throat-clearing openers ("so, I mean").
- Remove unnecessary qualifiers that soften a claim without adding real uncertainty: "kind of important," "a little bit concerning," "somewhat unclear," when the writer actually means "important," "concerning," "unclear."
- Replace jargon with the plain-language equivalent only where the jargon isn't doing real precision work; keep a technical term if a more common word would actually lose meaning.
- Prefer active voice and a direct subject-verb-object order, which is usually both shorter and clearer than passive constructions. Active voice means the subject of the sentence does the action, for example "the team shipped the fix." Passive voice flips this around so the subject receives the action instead of doing it, and often hides or drops who actually did it, for example "the fix was shipped by the team" (actor still named, but buried at the end) or "the fix was shipped" (actor dropped entirely, so the reader can't tell who's responsible).
Worked example
Original: "So, um, basically what we're trying to do here is, like, sort of make the checkout flow a little bit faster, if that makes sense, because right now it's kind of slow for some users."
Rewrite: "We're speeding up checkout. It's currently slow for some users."
Word count drops from 35 words to 10, a 71% reduction, while the two facts (goal: faster checkout; problem: currently slow for some users) both survive intact. Everything removed was filler, hedging, or a qualifier that added no information.
Trade-offs and pitfalls
- Removing every qualifier can accidentally remove real uncertainty the speaker meant to convey; "somewhat unclear" sometimes genuinely means partially unclear, not fully unclear, so check whether the hedge was doing real work before deleting it.
- Jargon isn't always the enemy: "p95 latency" (the 95th-percentile response time) is more precise than "how fast it usually is," and rewriting it away for a technical audience would lose information, not just words.
- This is a skill best practiced by rewriting your own recent messages after the fact; it is much harder to self-edit in the moment than it is with a few minutes of distance.
Design an online algorithm that processes a stream of characters and at any time can return the first non-repeating character seen so far. Describe the data structures you'd use and implement an online method next(char) that returns the current first non-repeating character or None. Discuss time and space complexity.
Sample Answer
Direct answer
Maintain a hash map from character to its running count, plus a queue that holds candidates for
"first non-repeating" in the order they first appeared. On each next(char), update the count
and push the character onto the queue if it is new; then pop from the front of the queue while
its count is greater than 1, since a repeated character can never again be the answer. Whatever
remains at the front (or None if the queue is empty) is the current answer.
Structured elaboration
Why a hash map alone is not enough. A hash map of counts tells you WHETHER a character
repeats, but not which non-repeating character came FIRST. You need an ordering structure
alongside it.
Why a plain list of "seen order" is not enough either. If you kept every character ever
seen in a list and re-scanned it on every query, you would pay O(k) per query, where k grows
with the stream. The insight that makes this online and efficient: once a character's count
exceeds 1, it can never become the answer again, so it should be permanently removed from
consideration, not re-scanned every time.
The deque of candidates. A deque (double-ended queue) holds characters that MIGHT still be
the first non-repeating one, in first-seen order. On each new character: increment its count in
the hash map, append it to the deque. Then, while the deque's front character has a count
greater than 1, pop it (it is now permanently disqualified). The deque's new front, if any, is
the answer.
Complexity. Each character is appended to the deque exactly once and popped at most once
over the life of the stream, so total deque work across n calls is O(n), making each
next() call amortized O(1), even though a single call can trigger several pops if multiple
front characters were just disqualified. Space is O(distinct characters seen so far), bounded
by the alphabet size for a fixed character set (for example 256 for byte-level input), not by
stream length.
Worked example
from collections import deque, defaultdict
class FirstNonRepeating:
def __init__(self):
self.counts = defaultdict(int)
self.candidates = deque()
def next(self, char):
self.counts[char] += 1
self.candidates.append(char)
while self.candidates and self.counts[self.candidates[0]] > 1:
self.candidates.popleft()
return self.candidates[0] if self.candidates else None
class BruteForceFirstNonRepeating:
"""O(k) per call: re-scans everything seen so far, no deque pruning."""
def __init__(self):
self.seen_order = []
self.counts = defaultdict(int)
def next(self, char):
self.counts[char] += 1
self.seen_order.append(char)
for c in self.seen_order:
if self.counts[c] == 1:
return c
return None
stream = "aabcbcd"
fnr = FirstNonRepeating()
fast_answers = [fnr.next(ch) for ch in stream]
for ch, ans in zip(stream, fast_answers):
print(ch, "->", ans)
brute = BruteForceFirstNonRepeating()
brute_answers = [brute.next(ch) for ch in stream]
print("brute-force cross-check:", brute_answers, "| matches:", brute_answers == fast_answers)
Running this against the stream "aabcbcd" prints:
a -> a
a -> None
b -> b
c -> b
b -> c
c -> None
d -> d
brute-force cross-check: ['a', None, 'b', 'b', 'c', None, 'd'] | matches: True
Tracing it by hand confirms each step: after "a" the only character is a (answer a);
after "aa", a now repeats (answer None); after "aab", b is the only non-repeat (answer
b); after "aabc", both b and c are non-repeating but b came first (answer b); after
"aabcb", b now repeats and c is the earliest remaining non-repeat (answer c); after
"aabcbc", c now repeats too and nothing is left (answer None); after "aabcbcd", d is
the only non-repeat (answer d). The independent brute-force cross-check above (re-scanning the
full seen-order list and counts on every call, an O(k) per-call approach) produces the exact
same seven answers on this stream, confirming the deque-pruning optimization changes performance
without changing the result.
Trade-offs and pitfalls
- Do not use a plain hash map without an ordering structure. A map alone can tell you a
character's count but has no notion of "which non-repeating character came first," since hash
maps do not guarantee iteration order matches insertion order in every language and even where
they do (Python'sdictsince 3.7), scanning the whole map on every query throws away the
benefit of an online algorithm. - A common bug is popping from the deque unconditionally instead of only while the front is
disqualified; that would discard characters that are still valid candidates. - This generalizes directly to the first non-repeating word problem if you tokenize on word
boundaries instead of characters: same data structures, same amortized-O(1)-per-token
argument, as long as the vocabulary fits in memory. - For a bounded alphabet (fixed character set), the space bound is a true constant, not just
"bounded by input"; for an open-ended token vocabulary (arbitrary words), space instead grows
with distinct tokens seen, which matters for a long-running service.
A social app's home feed mixes posts, ads and friend suggestions, and the mobile client currently makes many calls to render it. Design server-side strategies that minimize the number of calls the client needs. Consider personalization, A/B tests and privacy filters, and show the API shape and caching approach.
Sample Answer
Direct answer
Give the mobile app one screen endpoint, GET /v1/home?cursor=&limit=, that returns an ordered list of lightweight references plus a table of the entities they point to. The server (a BFF, meaning a backend built for one client's screens) asks the ranking service (an internal service that decides which posts, ads and suggestions this viewer sees and in what order, and returns only ids) for the order, removes anything the viewer must not see before paging, assigns the A/B arm, hydrates each distinct entity once (hydrating means looking up the full record, such as the post text or the author's name, for an id; doing it once per distinct id means an author with five posts is fetched once), and returns everything in one response. Cache the shared pieces (post bodies, ad creatives, media) on the server and in a CDN (content delivery network); treat the per-user ordering as private.
API shape
GET /v1/home?limit=20 HTTP/1.1
Authorization: Bearer <token>
If-None-Match: "feed-4f19"
{
"experiment": { "compact-cards": "control" },
"items": [
{ "type": "post", "id": "p1" },
{ "type": "post", "id": "p2" },
{ "type": "ad", "id": "ad0" },
{ "type": "suggestion", "id": "sg1" }
],
"entities": {
"posts": { "p1": { "id": "p1", "authorId": "u4", "text": "...", "likes": 312 } },
"ads": { "ad0": { "id": "ad0", "headline": "Ad 0", "image": "https://cdn.example/ad/0.jpg" } },
"suggestions": { "sg1": { "id": "sg1", "userId": "u1", "mutual": 1 } },
"users": { "u4": { "id": "u4", "name": "User 4", "avatar": "https://cdn.example/a/u4.jpg" } }
},
"nextCursor": "20"
}
items carries the order and the type; entities carries the content keyed by id. A client store (a normalized cache, meaning one record per id that every screen reads) updates a like count in one place and every card showing that post reflects it.
Why it cuts calls
Calls are counted from code, not estimated. The model below builds a seeded 20-item page (16 posts, 2 ads, 2 suggestions) and counts what a client would need if it assembled the screen itself.
| Strategy | Calls for page 1 | Dependency depth |
|---|---|---|
| Client fetches ranking, then each item, then each user | 30 (1 ranking + 20 items + 9 users) | 3 |
| Client batches hydration per type | 5 (ranking, posts, ads, suggestions, users) | 3 |
| Screen endpoint | 1 | 1 |
Dependency depth is the number of calls that must finish before the next can start: the client cannot ask for an item until the ranking names it, and cannot ask for a user until the item names the author, so ranking, items and users form three levels (depth 3). The screen endpoint does all three levels on the server, next to the data, so the client sees depth 1. Depth matters as much as count on a weak connection, because each level costs a full round trip.
Personalization, A/B tests and privacy filters
- Personalization stays in the ranking service. The BFF receives references in order and never scores anything, so the model can change without a client release.
- A/B tests: assign the arm (the variant group, such as
controlorcompact, that a user is placed in for an experiment) on the server from a stable hash of the user id and experiment name, and echo it inexperimentso the client can log which arm was shown. A hash function turns the same input into the same number every time, so the assignment is identical on every request without storing it. ForbucketOfin the model below: SHA-256 of the textviewer-1:compact-cardsgives 32 bytes;readUInt32BE(0)reads the first four bytes (hexbd800f0e) as the unsigned number 3,179,286,286; that number modulo the number of arms (2) is 0, and arm 0 iscontrol. Another user id hashes to a different number and so lands in either arm, which spreads users across the arms roughly evenly. To keep the shared cache effective, vary layout by arm on the client, using the same entities; do not generate different server fragments per arm unless the content itself differs. - Privacy filters run on the server, before the page is cut. Blocked and muted authors never reach the response or the entity table, and filtering first keeps page sizes and cursors consistent. In the model below the ranking service returns 45 references (40 posts, 3 ads, 2 suggestions); the filter removes 9, leaving 36 visible. Page 1 takes 20, so page 2 holds the remaining 36 - 20 = 16, and the cursor
"20"points at the right place. Paging first and filtering afterwards would instead leave pages with a varying number of cards. Filtering on the client would already have shipped the data, and would also make pages that contain 20 refs show fewer cards (for example 17 if three belong to blocked authors).
Caching approach
| Layer | What | Rule |
|---|---|---|
| Server fragment cache | Post bodies, ad creatives, user cards, keyed by id and version | Viewer-independent, so shared across users; invalidate on edit. |
| Visibility decision | Blocked / muted / audience checks | Recomputed per request from small per-user sets; never cached in a shared fragment. |
| Ranking session | The ordered refs for this viewer | Cached for a few minutes per user so page 2 continues the same list instead of re-ranking and shifting items. The cursor carries the session id and position. |
| HTTP response | Cache-Control: private plus an ETag | private means only the user's own device may store it; MDN warns that a personalized response without private can be stored in a shared cache and reused for other users. Pull-to-refresh sends If-None-Match and gets 304 Not Modified when the ranking has not changed. |
| Media | Images and video | Long-lived, immutable URLs on the CDN. |
Runnable model
Seeded data, a ranking stand-in that returns references, the privacy filter, a stable arm assignment and the counters above. Run in a node:22 container (Node 22.23.3) with node feed.mjs; there is nothing to install.
import { createHash } from 'node:crypto';
// ---- deterministic data (seeded generator) ----
let seed = 42;
const rnd = () => (seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32;
const pick = (a) => a[Math.floor(rnd() * a.length)];
const authors = Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`u${i}`, { id: `u${i}`, name: `User ${i}`, avatar: `https://cdn.example/a/u${i}.jpg` }]));
const posts = Object.fromEntries(Array.from({ length: 60 }, (_, i) => [`p${i}`, { id: `p${i}`, authorId: pick(Object.keys(authors)), text: 'Post body '.repeat(8) + i, likes: Math.floor(rnd() * 500) }]));
const ads = Object.fromEntries(Array.from({ length: 6 }, (_, i) => [`ad${i}`, { id: `ad${i}`, headline: `Ad ${i}`, image: `https://cdn.example/ad/${i}.jpg`, advertiser: `Brand ${i}` }]));
const suggestions = Object.fromEntries(Array.from({ length: 8 }, (_, i) => [`sg${i}`, { id: `sg${i}`, userId: `u${i}`, mutual: i }]));
// ---- per-request inputs ----
const viewer = { id: 'viewer-1', blocked: new Set(['u3', 'u7']), muted: new Set(['u5']) };
const bucketOf = (userId, experiment, arms) =>
arms[createHash('sha256').update(userId + ':' + experiment).digest().readUInt32BE(0) % arms.length];
// ---- the ranking service output: ordered refs only, no bodies ----
function rankedRefs() {
const refs = [];
for (let i = 0; i < 40; i++) refs.push({ type: 'post', id: `p${i}` });
[4, 12, 24].forEach((at, k) => refs.splice(at, 0, { type: 'ad', id: `ad${k}` }));
refs.splice(8, 0, { type: 'suggestion', id: "sg1" }, { type: "suggestion", id: "sg2" });
return refs;
}
// ---- the BFF: filter, hydrate once, dedupe into an entity table ----
function homeFeed({ cursor = 0, limit = 20 }) {
const arm = bucketOf(viewer.id, 'compact-cards', ['control', 'compact']);
const visible = rankedRefs().filter((r) => {
if (r.type === 'post') { const a = posts[r.id].authorId; return !viewer.blocked.has(a) && !viewer.muted.has(a); }
if (r.type === 'suggestion') return !viewer.blocked.has(suggestions[r.id].userId);
return true;
});
const page = visible.slice(cursor, cursor + limit);
const entities = { posts: {}, ads: {}, suggestions: {}, users: {} };
for (const r of page) {
if (r.type === 'post') { const p = posts[r.id]; entities.posts[r.id] = p; entities.users[p.authorId] = authors[p.authorId]; }
if (r.type === 'ad') entities.ads[r.id] = ads[r.id];
if (r.type === 'suggestion') { const s = suggestions[r.id]; entities.suggestions[r.id] = s; entities.users[s.userId] = authors[s.userId]; }
}
return { removedByPrivacy: rankedRefs().length - visible.length, experiment: { 'compact-cards': arm }, items: page, entities, nextCursor: cursor + limit < visible.length ? String(cursor + limit) : null };
}
const page1 = homeFeed({});
const bytes = (o) => Buffer.byteLength(JSON.stringify(o));
// Same screen with the "N+1" pattern a client would build itself: embed full author inside every post
const embedded = page1.items.map((r) => {
if (r.type === 'post') return { ...posts[r.id], author: authors[posts[r.id].authorId] };
if (r.type === 'ad') return ads[r.id];
const s = suggestions[r.id]; return { ...s, user: authors[s.userId] };
});
// Round trips if the client composes the screen itself
const idsCall = 1;
const perItem = page1.items.length;
const uniqueAuthors = Object.keys(page1.entities.users).length;
console.log('items on page 1:', page1.items.length, '| types:', JSON.stringify(page1.items.reduce((m, r) => (m[r.type] = (m[r.type] ?? 0) + 1, m), {})));
console.log('client-composed calls (1 ranking + 1 per item + 1 per unique user: authors and suggested users):', idsCall + perItem + uniqueAuthors);
console.log('client-composed calls if hydration is batched per type:', idsCall + 3 + 1, "(ranking, then posts + ads + suggestions in parallel, then users): dependency depth 3");
console.log('BFF calls from the client: 1');
console.log("refs removed by the privacy filter before paging:", page1.removedByPrivacy, "| blocked or muted authors still in response:", JSON.stringify(Object.keys(page1.entities.users).filter((u) => viewer.blocked.has(u) || viewer.muted.has(u))));
console.log('bytes, authors embedded in every post:', bytes(embedded));
console.log('bytes, entity table (items + entities):', bytes({ items: page1.items, entities: page1.entities }));
console.log('A/B arm for viewer-1 is stable across calls:', bucketOf('viewer-1', 'compact-cards', ['control', 'compact']) === page1.experiment['compact-cards'], page1.experiment);
const page2 = homeFeed({ cursor: +page1.nextCursor });
const overlap = page2.items.filter((r) => page1.items.some((q) => q.id === r.id));
console.log('page 2 cursor:', page1.nextCursor, '| items:', page2.items.length, '| ids repeated from page 1:', overlap.length);
console.log('sample item refs:', JSON.stringify(page1.items.slice(0, 3)));
It prints:
items on page 1: 20 | types: {"post":16,"ad":2,"suggestion":2}
client-composed calls (1 ranking + 1 per item + 1 per unique user: authors and suggested users): 30
client-composed calls if hydration is batched per type: 5 (ranking, then posts + ads + suggestions in parallel, then users): dependency depth 3
BFF calls from the client: 1
refs removed by the privacy filter before paging: 9 | blocked or muted authors still in response: []
bytes, authors embedded in every post: 3778
bytes, entity table (items + entities): 3769
A/B arm for viewer-1 is stable across calls: true { 'compact-cards': 'control' }
page 2 cursor: 20 | items: 16 | ids repeated from page 1: 0
sample item refs: [{"type":"post","id":"p1"},{"type":"post","id":"p2"},{"type":"ad","id":"ad0"}]
In this model the cursor is the bare offset "20" because its ranking is a fixed list; a production cursor would also carry the ranking session id, as the caching table says. The privacy filter removed 9 references before paging, and none of the blocked or muted authors appears in the response. Page 2 repeats no ids from page 1. The embedded-author and entity-table byte counts are within 0.3% of each other on this page (3,778 against 3,769 bytes), so the entity table is chosen for consistent updates in the client store, not for size.
Trade-offs and pitfalls
- Slow ad or suggestion service. Give each hydration call a deadline and return the feed without that slot rather than waiting; the feed is useful with posts alone.
- Cursor drift. A pure offset cursor ("start at item 20") breaks when the ranking changes between page requests, because items move and the client sees duplicates or skips some; tie the cursor to a ranking session so page 2 continues the list page 1 came from.
- Shared-cache leaks. The failure to avoid is a personalized body or ordering stored under a public key. Keep user-specific data out of any shared cache key.
- Over-fetching in the first page. Return a small first page (for example 10) with
limitset by the client for time to first content, then larger pages. - Impression logging (recording that an ad or post was shown on screen) belongs in a separate fire-and-forget event call (the client sends it and does not wait for or depend on the reply), not in the feed response, so ad measurement does not make the read slower.
Your team reduced the authentication endpoint's p95 latency from 500ms to 350ms, a 30% improvement. For three audiences: a non-technical CEO, external developer customers, and internal engineering managers, write a short tailored message explaining the business value and one key metric each audience should track.
Sample Answer
Direct answer
The number doesn't change across audiences, but what it's evidence for does: to a CEO it's a business outcome (conversion, retention, cost), to external developers it's a reliability guarantee they can build on, to internal engineering managers it's a load and capacity signal. Same 30% improvement, three different "so what," each with the one metric that audience should actually track next.
Structured elaboration
The technique is picking, per audience, which consequence of the number they actually own:
- Translate the metric into the currency that audience is measured on before stating it. A CEO is measured on revenue and retention; an external developer is measured on their own app's reliability; an internal engineering manager is measured on system load and incident risk.
- Give exactly one metric to track next, not a dashboard's worth. Too many numbers reads as "we're not sure which one matters"; one number reads as a clear owner and a clear signal.
- State the baseline and direction explicitly, down from 500ms to 350ms, not just "faster," so nobody has to ask what the improvement actually was.
This same three-move pattern is what you would reuse for a different metric to the same or different audiences: messaging a lazy-loading improvement to executives, sales, and developers, an API deprecation to engineering, customers, and executives, or a throughput doubling to a CTO, operations, and sales. The technique is constant; only which consequence you lead with changes per audience.
Worked example
p95 latency means the response time that 95% of requests are faster than, so it's a measure of how slow the worst-but-common cases are, not the average case.
To the CEO: "We cut the time it takes customers to sign in from half a second to a third of a second, 500ms to 350ms, a 30% improvement, on the slowest 5% of requests, the ones customers actually notice as lag. Faster sign-in means fewer people abandoning at login and less friction on every visit. Metric to track: conversion rate on the sign-up-to-first-action flow over the next two weeks, to see if that translates into fewer drop-offs."
To external developer customers: "Our authentication endpoint's p95 latency, the response time 95% of your calls beat, dropped from 500ms to 350ms. You should see fewer client-side timeouts and retries against this endpoint. Metric to track: your own timeout and retry rate against our auth endpoint, it should trend down."
To internal engineering managers: "We cut auth p95 from 500ms to 350ms through caching and query tuning, which lowers tail latency for every downstream service that calls auth before doing its own work. Metric to track: queue length and tail latency on the services immediately downstream of auth, to confirm the improvement is propagating rather than just moving the bottleneck."
Trade-offs and pitfalls
Reusing the same "30% faster" framing for every audience without a metric attached invites the follow-up "compared to what, and how would I know it's working," which is exactly what the per-audience metric answers in advance. It's also a mistake to promise a business outcome, like "this will increase conversion," as a fact rather than a hypothesis. Latency and conversion correlate but aren't guaranteed to move together for every product, so the honest version says "we would expect to see," not "this will." And if a later measurement shows a segment of customers saw no improvement, say a region or client version, that needs its own honest message rather than folding it quietly into the aggregate number.
Walk me through your career, starting with your first relevant role and ending with where you are today.
Sample Answer
Direct answer: Structure this as a small number of milestones (three to six), each with employer context, title, and approximate timeframe, one line on what you did, and the reason you moved to the next step. Open with a one-line frame of what connects these jobs (your through-line) rather than a start date, and don't treat every job change as equally important.
Structured elaboration
The milestone model, not a diary
Pick three to six career milestones (a promotion, a title change, a deliberate move) rather than narrating every job change. For a deep-technical background, emphasize technical growth across those milestones: scope of systems owned, complexity of problems solved, or seniority of team, not just tenure.
What to name at each milestone
For each milestone, give: the employer context and title (for example, "a small startup, as the second backend hire" rather than a bare timeline), the approximate timeframe, team size and the stack central to that stage, and one sentence on why you moved to the next step. Naming promotions and title changes explicitly signals growth the interviewer would otherwise have to infer from your resume. If you're naming a real former employer, that's fine to do live in the room; when practicing or writing this out generically, use employer type and context rather than a name so the shape of the answer stays reusable across interviews.
Explaining the "why" at each transition
For every step, answer two questions in one breath: how this role prepared you for the next one, and why you moved on. A career that reads as a sequence of things that happened to you reads as passive; a career narrated as a sequence of deliberate choices reads as intentional.
Timeline shape: highlight two moments, not every moment
Across the whole walkthrough, spend real time on exactly two things: one early-career learning moment (a mistake, a skill gap you closed, a foundational lesson) and one major turning point (a promotion, a pivot, a project that changed your trajectory). Everything else gets one line.
Worked example
Skeleton: "I started at [employer type], as a [title], on a team of [size], working mainly in [stack]. [One early-career learning: what I didn't know yet and how I closed the gap]. After [timeframe], I moved to [next employer type/title], because [reason tied to growth] [team size/stack if it changed]. [Major turning point: the milestone that changed my trajectory]. Today I'm at [current stage], where [what prepared me specifically for this next move]."
Filled illustration: "I started at a small agency as a junior data analyst on a two-person team, mostly writing SQL against a single reporting database. I didn't yet know how to translate a stakeholder's vague question into a testable metric, and closing that gap became the thing I got known for. After about two years, I moved into a data analyst role at a mid-size product company, because I wanted to work closer to product decisions instead of reporting after the fact. That's also where I was promoted to senior analyst on a team of six, once I'd built the first self-serve dashboard the product org relied on daily. That promotion was the turning point: it shifted me from someone who answered questions to someone who framed which questions were worth asking. Today I lead analytics for one product area, which is what draws me to a role that combines that ownership with a bigger surface area."
Trade-offs & pitfalls
- A pure date-by-date recitation (title, dates, title, dates) has no through-line and makes the interviewer do the synthesis work themselves.
- Treating every job change as equally important dilutes the two moments that actually matter: the early lesson and the big turning point.
- Omitting why you moved makes moves look reactive (laid off, bored, following a friend) rather than deliberate, even when the real reason was a good one.
- For senior candidates, spending equal time on early junior work as on recent scope is a common miscalibration; weight time toward the stages most relevant to this role.
A colleague submitted a small Python utility that parses syslog files and prints a summary. The snippet:
def parse(lines):
counts = {}
for l in lines:
level = l.split()[2]
counts.setdefault(level, 0)
counts[level] += 1
print(counts)
Identify code smells, maintainability and correctness problems, and suggest a refactor that improves clarity, testability, and robustness.
Sample Answer
Direct answer
The function has one real correctness bug (l.split()[2] assumes every line has at least three whitespace-separated tokens, and crashes on any line that doesn't) plus several maintainability smells: a single-letter variable name that's easy to misread, a hardcoded print instead of a return value, and no way to unit test it without capturing stdout. The fix is to make it a pure function that returns a dictionary of counts, validate or skip malformed lines instead of assuming they're well-formed, and push the printing to a separate, thin caller.
Structured elaboration
Correctness problem. level = l.split()[2] indexes into the result of split() without checking its length first. Any line with fewer than three tokens, a blank line, a truncated line, a line in a slightly different format, raises IndexError and crashes the whole batch instead of just that one line.
Maintainability smells.
las a variable name for a log line is easy to misread as the digit1;linecosts nothing and is unambiguous.- The function both computes and prints, so it can never be reused somewhere that needs the counts as data (an API response, a different report format) without also printing.
print(counts)is untestable directly: a test would have to capture stdout and parse it back out, instead of asserting on a return value.- No handling for malformed input is documented anywhere, so a caller has no way to know this function is fragile without reading the implementation.
Refactor. Split into a pure counting function and a thin printing function, and decide explicitly what to do with malformed lines (skip them, which is what the version below does) rather than let that be an accident of the indexing bug.
Worked example
The original function actually crashing on a realistic mixed batch of syslog-style lines (one blank line, one truncated line):
def parse(lines):
counts = {}
for l in lines:
level = l.split()[2]
counts.setdefault(level, 0)
counts[level] += 1
print(counts)
sample_lines = [
"Jun 10 ERROR disk full on /dev/sda1",
"Jun 10 INFO service restarted",
"Jun 10 ERROR connection refused",
"",
"Jun 10 WARN retrying",
"malformed",
]
try:
parse(sample_lines)
except Exception as e:
print(f"{type(e).__name__}: {e}")
Output:
IndexError: list index out of range
The refactored version, run on the exact same input:
from collections import Counter
from typing import Iterable, Dict
def parse_levels(lines: Iterable[str]) -> Dict[str, int]:
"""Count the syslog severity level (3rd whitespace-separated token) per line.
Lines with fewer than 3 tokens are skipped rather than raising."""
counts: Counter = Counter()
for line in lines:
parts = line.split()
if len(parts) < 3:
continue
counts[parts[2]] += 1
return dict(counts)
def print_summary(counts: Dict[str, int]) -> None:
for level, n in sorted(counts.items()):
print(f"{level}: {n}")
result = parse_levels(sample_lines)
print(result)
print_summary(result)
Output:
{'ERROR': 2, 'INFO': 1, 'WARN': 1}
ERROR: 2
INFO: 1
WARN: 1
Complexity
Time is O(n * m), where n is the number of lines and m is the average tokens per line from split(); space is O(k) for k distinct severity levels. The refactor doesn't change this, it changes which lines survive to be counted at all.
Edge cases
- A blank line or a line with fewer than 3 tokens is now skipped silently instead of crashing the whole batch. Whether "skip silently" or "skip and log a warning" or "raise in a strict mode" is correct depends on whether malformed lines are expected noise or a symptom of an upstream bug, worth asking the author.
- A line where the 3rd token isn't actually a severity level (a genuinely different log format mixed into the same file) will still get counted as if it were one;
parse_levelstrusts position, not content, same as the original. - An empty
linesiterable returns{}cleanly in both versions.
Trade-offs and pitfalls
Silently skipping malformed lines trades visibility for robustness: it keeps the batch from crashing, but a caller who cares about data quality needs a way to know how many lines were skipped, which this version doesn't surface. A stricter parser using a regex anchored to the real syslog format would catch more malformed input explicitly, at the cost of more code and a format assumption that's easier to get wrong than "at least 3 tokens." The most common wrong turn here is fixing only the crash (add a length check) without also fixing the testability problem (still printing instead of returning), which leaves the function just as hard to unit test as before.
Design a program (not just a tool rollout) to raise coding standards across an organization: what training, mentoring, and measurable milestones would you include, and how do you get buy-in from engineers who see this as overhead?
Sample Answer
Direct answer. Treat this as a change-management program, not a tooling rollout: pair mandatory automation (which removes debate entirely) with voluntary, incentivized skill-building (training, mentoring, visible wins) so the standards feel like a shared craft investment rather than a compliance mandate imposed from outside.
Program design
- Content: start from a small, high-leverage set of standards (naming, function size, the specific smells causing the MOST real pain in this codebase's incident history) rather than a comprehensive style guide nobody will read -- credibility comes from solving real, felt pain first.
- Automation for anything mechanical: formatting and simple lint rules are enforced via tooling from day one, removing them entirely from human debate or 'training' -- nobody needs a workshop on tab-vs-space.
- Training for judgment-based standards: run short, practical workshops (not lectures) using REAL examples from the team's own codebase/incident history, since judgment-based standards (when to extract an abstraction, how to name well) don't automate and need practiced instinct, not just awareness.
- Mentoring/pairing: pair newer or more skeptical engineers with engineers who already practice these standards well, on REAL work, so the standard is demonstrated in context rather than asserted in a slide deck.
- Measurable goals: track leading indicators (percentage of PRs passing automated checks without manual intervention, review comment volume on style/naming trending down) and lagging indicators (incident rate, time-to-onboard a new engineer) -- both matter, since leading indicators show adoption and lagging indicators show it's actually working.
- KPIs with guardrails against gaming: pair any metric with periodic qualitative sampling (an experienced engineer reviews a sample of recent PRs) so metrics can't be satisfied by superficial compliance (renaming one variable to 'pass' a linter check while leaving the underlying design smell untouched).
Building buy-in, not just compliance
- Involve skeptical senior engineers in DEFINING the standards, not just receiving them -- standards that feel imposed by a committee they weren't part of get quiet resistance; standards they helped shape get real ownership.
- Celebrate and publicize concrete wins (an incident that WOULD have happened but didn't, because a new test caught it) so the program has visible, credible evidence of value beyond an abstract mandate.
Trade-offs and pitfalls
- A program that's ALL mandate (enforcement) with no visible value story tends to produce compliance without real behavior change -- people satisfy the letter of the rule while resenting it, which shows up later as pushback the moment enforcement weakens.
- Don't let the KPI dashboard become the goal itself (Goodhart's Law) -- pair quantitative tracking with periodic human judgment sampling so the program stays honest about whether it's actually improving outcomes, not just moving a number.
Explain Redux-style state management for a React Native application. Describe the single source of truth, pure reducers, unidirectional data flow, and where side-effects and async work belong. Illustrate with an example: handling an offline form that can be saved locally and synced later.
Sample Answer
Single source of truth
Store the entire UI state in one Redux store object (e.g., { auth, forms, network }). Mobile apps benefit because different screens, background sync, and native modules read from the same place.
Pure reducers
Reducers are pure functions: (state, action) => newState. They must not perform I/O, async work, or mutate state. Use immutable updates (spread, immer).
Unidirectional data flow
Actions -> reducers -> new store -> React Native components subscribe and re-render. Components dispatch actions; reducers compute state; UI reads state.
Where side-effects & async belong
Use middleware (redux-thunk, redux-saga, or redux-observable). Keep API calls, persistence, network checks, and background sync in middleware/epics/sagas. Use libraries: redux-persist for local storage, @react-native-community/netinfo for connectivity, and BackgroundFetch/HeadlessJS for background sync.
Example: offline form flow
- User fills form -> component dispatches SAVE_FORM_LOCAL action with payload.
- Reducer (pure) appends form to state.forms.pending.
- Middleware intercepts SAVE_FORM_LOCAL to write to AsyncStorage via redux-persist or directly; returns success/failure actions.
- On network change (NetInfo event), middleware dispatches SYNC_PENDING_FORMS; saga/thunk reads pending forms, POSTs to server, dispatches REMOVE_FORM_ON_SUCCESS.
Result: UI stays responsive, state remains consistent, side-effects isolated in middleware, and local persistence ensures offline reliability.
Explain the difference between the main (UI) thread and background threads in a mobile application. Describe specific consequences of performing long-running or blocking work on the main thread, give concrete examples of tasks that must run on the main thread, and explain how iOS and Android frameworks enforce or expect main-thread confinement.
Sample Answer
Brief distinction
The main (UI) thread is the single thread responsible for handling user input, drawing views, and running lifecycle callbacks. Background threads (worker threads) run non-UI work: networking, file I/O, heavy computation.
Consequences of blocking the main thread
- UI jank, dropped frames, and stuttering (Android: >16ms per frame causes 60fps drop)
- Unresponsive UI and ANRs (Android) or watchdog terminations (iOS) if the app doesn’t respond
- Delayed input handling, frozen animations, poor perceived performance
- Increased battery/thermal issues if long loops run instead of cooperative async work
Concrete examples of tasks that must run on the main thread
- All view updates and UIKit/AppKit calls (iOS): creating/updating UIView, changing CALayer properties that affect presentation
- Android UI operations: modifying Views, calling RecyclerView adapter notify methods, interacting with ViewModel LiveData observers that expect main thread
- Dispatching UI-driven animations, presenting view controllers, showing dialogs/toasts
Platform expectations/enforcement
- iOS: UIKit is main-thread confined; calling UIKit from background can cause race conditions and runtime warnings. DispatchQueue.main.async is the standard way to marshal to main thread. Main-thread checker (runtime) flags violations during debugging.
- Android: Many framework APIs expect main thread (Looper/Handler/RecyclerView/LiveData). Android throws CalledFromWrongThreadException for some view operations. Use AsyncTask (deprecated), Executors, coroutines with Dispatchers.Main/IO, or Handler threads to switch contexts.
Best practice
Keep UI work on main thread; offload heavy work to background threads and marshal results back to main thread for UI updates. Use platform async primitives (GCD/DispatchQueues or Kotlin coroutines/Dispatchers).
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 Mobile Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs