20 real Dream11 interview questions with full model answers — Coding, Technical, System design, Behavioral. Drawn from the same verified bank ChannelPulse drills from (30 Dream11 questions in total).
30 Dream11 questions in the bank
4 categories covered
2 roles: Frontend Engineer, Software Engineer
BehavioralMediumDream11Frontend EngineerHiring Manager/Culture Fit
1. Describe your past projects and experience.
Model answer
Situation — In my recent frontend role, I worked on a React and TypeScript product for discovering and entering live sports contests. The contest lobby served a few hundred thousand monthly users, and we saw a noticeable rise in traffic around match start times. My work focused on making the experience fast and dependable on mobile, where most users browsed and joined contests.
Task — I owned improvements to the contest discovery and entry flow. The goal was to reduce the time and friction between opening a match and joining a suitable contest, without making the interface harder to understand or introducing stale contest information.
Action
I started by reviewing funnel analytics and session recordings with product and design. We found users often scrolled past relevant contests, while slower devices showed delayed updates and layout shifts.
I worked with design to simplify the contest cards, making entry fee, prize pool, and available spots easier to compare. I kept the key action prominent while preserving the information users needed to make a decision.
I split the lobby into reusable React components and used stable keys and memoization where profiling showed unnecessary rerenders. I also added skeleton states and reserved space for dynamic content to reduce perceived loading time and layout movement.
I partnered with backend engineers to define clear loading, empty, and error states, and to ensure contest availability was refreshed before entry. I avoided treating cached lobby data as authoritative for a join action.
I added frontend performance and funnel measurements, then helped run a staged A/B test. We checked not only contest-entry conversion but also error rates and page responsiveness on lower-end devices.
Result — The test improved contest-entry conversion by about 8% relative to the control and reduced the lobby’s median render time by roughly 25%. Entry errors did not increase, and the shared components made subsequent match-page changes quicker to deliver. I learned to treat performance, data freshness, and user confidence as parts of the same frontend problem—not separate polish tasks.
CodingEasyDream11Software Engineer
2. Final Prices With a Special Discount in a Shop (LeetCode)
Model answer
The task
For each item, subtract the price of the first item to its right that costs no more than it does. If there is no such item, keep its price unchanged.
Key idea
A monotonic stack tracks earlier items still waiting for a qualifying discount. When the current price is no greater than the price at the top of the stack, it is the first qualifying discount for that item.
Approach
Create a stack of indices whose discounts have not yet been found.
Scan prices from left to right.
While the stack is nonempty and the current price is no greater than the price at its top index, subtract the current price from that earlier item and pop its index.
Push the current index; it may receive a discount later.
Return the modified prices.
from typing import List
class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
result = prices[:]
waiting = [] # Indices awaiting their first qualifying discount
for i, price in enumerate(prices):
while waiting and prices[waiting[-1]] >= price:
index = waiting.pop()
result[index] -= price
waiting.append(i)
return result
Complexity:
Time: O(n), since each index is pushed and popped at most once.
Space: O(n) for the stack and the result copy.
Common follow-ups
Could the result be computed in place? Yes; subtract discounts directly from the input list if mutation is permitted.
What changes if the discount must come from a strictly cheaper item? Replace >= with >.
How would you return the discount source for each item? Store the matching index when popping, alongside applying the discount.
CodingEasyDream11Frontend EngineerHackerRank test
3. Convert a binary linked list to a decimal number.
Model answer
Assuming each node contains a bit (0 or 1) and the head is the most significant bit, I can build the value one bit at a time: shift the current value left, then add the next bit.
// A linked-list node has the shape: { val: 0 | 1, next: Node | null }
function binaryListToDecimal(head) {
let value = 0;
for (let node = head; node !== null; node = node.next) {
if (node.val !== 0 && node.val !== 1) {
throw new Error("Each node must contain 0 or 1");
}
// Shift left to make room for the next bit, then append that bit.
value = value * 2 + node.val;
}
return value;
}
// Example: 1 -> 0 -> 1 represents binary 101, which is decimal 5.
const head = { val: 1, next: { val: 0, next: { val: 1, next: null } } };
console.log(binaryListToDecimal(head)); // 5
Each iteration uses the recurrence value = value * 2 + bit, so no binary string conversion is needed.
Complexity: Time O(n); space O(1).
CodingMediumDream11Software Engineer
4. Rotting Oranges (LeetCode)
Model answer
The task
Given a grid of empty cells, fresh oranges, and rotten oranges, find the minimum number of minutes until no fresh oranges remain. Each minute, a rotten orange makes any fresh orange directly above, below, left, or right of it rotten; return -1 if some fresh oranges can never be reached.
Key idea
Use multi-source breadth-first search: all initially rotten oranges spread at the same time, so put them all in the queue at the start. Process the queue one minute at a time, counting newly rotten oranges to detect whether any fresh ones remain unreachable.
Approach
Count the fresh oranges and enqueue every initially rotten orange.
If there are no fresh oranges, return 0.
For each BFS layer, rot adjacent fresh oranges, decrement the fresh count, and enqueue them.
Count each processed layer as one minute.
Return the minutes if all fresh oranges rotted; otherwise return -1.
from collections import deque
from typing import List
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
queue = deque()
fresh = 0
# Gather all initial sources and count oranges that still need to rot.
for r in range(rows):
for c in range(cols):
if grid[r][c] == 2:
queue.append((r, c))
elif grid[r][c] == 1:
fresh += 1
if fresh == 0:
return 0
minutes = 0
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue and fresh > 0:
# Process exactly the oranges rotten before this minute began.
for _ in range(len(queue)):
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if (
0 <= nr < rows
and 0 <= nc < cols
and grid[nr][nc] == 1
):
grid[nr][nc] = 2
fresh -= 1
queue.append((nr, nc))
minutes += 1
return minutes if fresh == 0 else -1
Complexity:
Time: O(rows × cols), since each cell is visited at most once.
Space: O(rows × cols) for the BFS queue in the worst case.
Common follow-ups
What if diagonal neighbors also spread rot? Add the four diagonal directions to the neighbor list.
Can the original grid be preserved? Copy it first, or track visited cells separately.
How would you return which oranges rot each minute? Store each BFS layer’s cells or record a rot-time value per cell.
CodingMediumDream11Software Engineer
5. 3Sum (LeetCode)
Model answer
The task
Given an integer array, return every distinct triplet of values whose sum is zero. Triplets are considered the same if they contain the same values, regardless of order.
Key idea
Sort the array, then fix each value in turn and use two pointers to find pairs that complete its sum to zero. Skipping repeated values prevents duplicate triplets.
Approach
Sort the input array.
For each index, treat its value as the first element of a triplet.
Skip the index if its value is the same as the previous value.
Set two pointers immediately after the fixed index and at the end of the array.
Move a pointer according to whether the current sum is too small or too large.
When a triplet is found, record it and advance past duplicate pointer values.
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
triplets = []
n = len(nums)
for i in range(n - 2):
# Only use the first occurrence of each fixed value.
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total < 0:
left += 1
elif total > 0:
right -= 1
else:
triplets.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
# Avoid repeating the same pair for this fixed value.
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
return triplets
Complexity:
Time: O(n²), from fixing each value and scanning with two pointers.
Space: O(n) for Python's in-place sort; excludes the returned triplets.
Common follow-ups
How would you return unique index triplets instead of value triplets? Track original indices while sorting, then return the corresponding index triples.
What if the target sum is a variable? Replace the zero-sum check with a comparison against the target.
Can the approach be extended to four values? Fix two values and use two pointers for the remaining pair, giving O(n³) time.
CodingMediumDream11Software Engineer
6. Asteroid Collision (LeetCode)
Model answer
The task
Given a sequence of signed asteroid sizes, simulate their movement and collisions. Return the asteroids that remain, in their original order.
Key idea
A collision can happen only when a right-moving asteroid is followed by a left-moving one. Keep surviving asteroids in a stack; resolve each possible collision with the stack’s most recent survivor.
Approach
Start with an empty stack.
Process asteroids from left to right.
While the stack’s top moves right and the current asteroid moves left, compare their sizes.
Remove the smaller asteroid; if they are equal, remove both. Stop resolving if the current asteroid is destroyed.
Add the current asteroid if it survives, then return the stack.
from typing import List
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
survivors: List[int] = []
for asteroid in asteroids:
alive = True
# Only a right-moving survivor can collide with a left-moving one.
while (
alive
and asteroid < 0
and survivors
and survivors[-1] > 0
):
top = survivors[-1]
if top < -asteroid:
# The top asteroid is smaller and is destroyed.
survivors.pop()
elif top == -asteroid:
# Both asteroids are destroyed.
survivors.pop()
alive = False
else:
# The current asteroid is smaller and is destroyed.
alive = False
if alive:
survivors.append(asteroid)
return survivors
Complexity:
Time: O(n), since each asteroid is pushed and popped at most once.
Space: O(n) for the stack of surviving asteroids.
Common follow-ups
How would you handle zero-sized asteroids? Define their movement and collision behavior, then adjust the collision rules accordingly.
Can the result be computed in place? Yes, use the input list’s prefix as the stack, if modifying the input is allowed.
What if collisions occur in multiple dimensions? A single stack is no longer sufficient; the model needs spatial positions and directions.
CodingMediumDream11Software Engineer
7. Minimum Falling Path Sum (LeetCode)
Model answer
The task
Given a square grid of integers, choose one cell from each row, moving from top to bottom. Each move may stay in the same column or shift by one column; return the smallest possible sum of the chosen cells.
Key idea
For each cell, the cheapest path ending there is its value plus the minimum cost of reaching one of its allowed predecessor cells. Keep only the previous row of costs, since earlier rows are no longer needed.
Approach
Initialize the previous-row costs from the first row.
For each later cell, find the minimum cost among valid cells directly above or diagonally adjacent.
Add the current cell’s value to that minimum and store it in the current row.
Replace the previous-row costs with the newly computed row.
Return the smallest cost in the last row.
from typing import List
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
n = len(matrix)
if n == 0:
return 0
# Minimum path sums ending at each cell of the first row.
previous = matrix[0][:]
for row in range(1, n):
current = [0] * n
for col in range(n):
# Consider only predecessor columns inside the grid.
best_predecessor = min(
previous[prev_col]
for prev_col in (col - 1, col, col + 1)
if 0 <= prev_col < n
)
current[col] = matrix[row][col] + best_predecessor
previous = current
return min(previous)
Complexity:
Time: O(n²), since each cell is processed once.
Space: O(n), for the two rows of path costs.
Common follow-ups
Can the matrix be modified in place? Yes; accumulate each cell’s minimum path sum directly into the matrix, using O(1) extra space.
What if moves can shift by up to k columns? Minimize over the valid predecessor range from col - k through col + k.
How would you recover the actual path? Store the chosen predecessor column for each cell, then backtrack from the cheapest cell in the final row.
CodingMediumDream11Software Engineer
8. 3Sum Closest (LeetCode)
Model answer
The task
Given an integer array and a target, choose three distinct elements whose sum is as close as possible to the target. Return that sum.
Key idea
Sort the array, then fix each element in turn and use two pointers to search for the best pair among the elements to its right. If a sum is too small, move the left pointer up; if it is too large, move the right pointer down.
Approach
Sort the array and initialize the best sum using its first three elements.
For each index, set pointers just after it and at the end of the array.
Compute the three-element sum and update the best sum if this one is closer to the target.
Return immediately if the sum equals the target.
Move a pointer according to whether the sum is below or above the target.
class Solution:
def threeSumClosest(self, nums: list[int], target: int) -> int:
nums.sort()
best = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
left, right = i + 1, len(nums) - 1
while left < right:
current = nums[i] + nums[left] + nums[right]
if abs(current - target) < abs(best - target):
best = current
if current == target:
return current
elif current < target:
left += 1
else:
right -= 1
return best
Complexity:
Time: O(n²), from one two-pointer scan for each fixed element.
Space: O(n) auxiliary space for Python’s in-place sort; the scan itself uses O(1).
Common follow-ups
How would you handle ties? Define a tie-breaking rule, then apply it when distances are equal.
Can the array contain duplicates? Yes; duplicates are valid elements at different indices, and the pointer scan handles them.
What if the array is too short? Validate that there are at least three elements before starting; the usual problem guarantees this.
Can this be faster? Not generally for arbitrary input: the standard approach takes O(n²), after sorting.
CodingMediumDream11Software Engineer
9. Container With Most Water (LeetCode)
Model answer
The task
Given nonnegative heights arranged along a line, choose two positions to form a container with the greatest possible area. Its area is the distance between the positions multiplied by the shorter of their two heights.
Key idea
Start with the widest possible pair, at the two ends. The shorter side limits the area, so moving the taller side inward cannot improve that limiting height and only reduces the width. Move the shorter side instead, hoping to find a taller boundary.
Approach
Set pointers to the first and last positions.
Compute the area using their distance and the shorter height; update the best area.
Move the pointer at the shorter height inward by one position.
Repeat until the pointers meet.
Return the greatest area seen.
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
best_area = 0
while left < right:
width = right - left
limiting_height = min(height[left], height[right])
best_area = max(best_area, width * limiting_height)
# The shorter side limits this container's area.
# Moving the taller side inward cannot improve that limit.
if height[left] <= height[right]:
left += 1
else:
right -= 1
return best_area
Complexity:
Time: O(n), because each pointer moves inward at most n times.
Space: O(1), since only a few variables are used.
Common follow-ups
What if heights can be negative? A negative height does not describe a valid container; clarify the input rules, or treat invalid heights as unusable.
Why is it safe to discard the shorter side? With the same shorter boundary, every inward pair has less width, so it cannot produce a larger area.
Can this be done with extra memory? Not usefully for this objective; the two-pointer scan already processes the candidates in linear time with constant space.
CodingMediumDream11Software Engineer
10. Gas Station (LeetCode)
Model answer
The task
Given circular arrays of fuel available and fuel required for each leg, find a starting station from which a vehicle can complete the full loop, or return -1 if no such start exists.
Key idea
If the total fuel is less than the total cost, no start can work. Otherwise, when the running fuel balance becomes negative, none of the stations in the current candidate segment can be a valid start, so begin a new candidate at the next station.
Approach
Track the total fuel surplus across all stations.
Track the surplus from the current candidate start.
At each station, add its fuel minus its travel cost to both totals.
If the candidate’s running surplus drops below zero, discard that segment and set the next station as the candidate.
Return the candidate if the total surplus is nonnegative; otherwise, return -1.
class Solution:
def canCompleteCircuit(self, gas: list[int], cost: list[int]) -> int:
total_surplus = 0
current_surplus = 0
start = 0
for i in range(len(gas)):
surplus = gas[i] - cost[i]
total_surplus += surplus
current_surplus += surplus
# No station in the current segment can be a valid start.
if current_surplus < 0:
start = i + 1
current_surplus = 0
return start if total_surplus >= 0 else -1
Complexity:
Time: O(n), where n is the number of stations; each station is processed once.
Space: O(1), using only a fixed number of variables.
Common follow-ups
Why can the candidate segment be discarded after the balance goes negative? Starting at any station within that segment leaves less fuel by the time it reaches the failure point, so it cannot succeed.
What if multiple valid starts exist? The algorithm returns one valid start; uniqueness is not guaranteed.
Can this be solved without storing prefix sums? Yes. The running surplus and total surplus are sufficient, as shown above.
CodingMediumDream11Software Engineer
11. Partition Equal Subset Sum (LeetCode)
Model answer
The task
Determine whether the given numbers can be split into two groups with the same sum. Each number must belong to exactly one group.
Key idea
If the total is odd, an equal split is impossible. Otherwise, the problem becomes finding a subset that sums to half the total—a 0-1 knapsack decision problem, where each number can be used at most once.
Approach
Sum the numbers; return False if the total is odd.
Set the target to half the total.
Track which sums up to the target can be formed, starting with sum zero.
For each number, update reachable sums in descending order so that number is not reused.
Return whether the target is reachable.
from typing import List
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total = sum(nums)
if total % 2 != 0:
return False
target = total // 2
reachable = [False] * (target + 1)
reachable[0] = True
for value in nums:
# Descending order ensures this value is used at most once.
for current_sum in range(target, value - 1, -1):
if reachable[current_sum - value]:
reachable[current_sum] = True
return reachable[target]
Complexity:
Time: O(n × target), updating up to target sums for each of n numbers.
Space: O(target), for the reachable-sum table.
Common follow-ups
How can the actual partition be returned? Store predecessor information when each sum first becomes reachable, then backtrack from the target.
What if the numbers can be negative? A simple table indexed from zero no longer suffices; use an offset range of possible sums or a set of reachable sums.
How can the number of valid subsets be counted instead? Replace reachability booleans with counts and update sums in descending order.
Can the space usage be reduced in practice? Use a bitset to represent reachable sums and update it with a shift-and-OR operation.
CodingMediumDream11Frontend EngineerHackerRank test
12. Solve the Last Stone Weight problem.
Model answer
Repeatedly combine the two heaviest stones. A max-heap makes retrieving those stones efficient; JavaScript does not provide a built-in heap, so this solution implements one.
class MaxHeap {
constructor(values = []) {
this.data = [];
for (const value of values) this.push(value);
}
get size() {
return this.data.length;
}
push(value) {
const data = this.data;
data.push(value);
let index = data.length - 1;
while (index > 0) {
const parent = Math.floor((index - 1) / 2);
if (data[parent] >= data[index]) break;
[data[parent], data[index]] = [data[index], data[parent]];
index = parent;
}
}
pop() {
if (this.data.length === 0) return undefined;
const data = this.data;
const maximum = data[0];
const last = data.pop();
if (data.length > 0) {
data[0] = last;
let index = 0;
while (true) {
const left = 2 * index + 1;
const right = left + 1;
let largest = index;
if (left < data.length && data[left] > data[largest]) largest = left;
if (right < data.length && data[right] > data[largest]) largest = right;
if (largest === index) break;
[data[index], data[largest]] = [data[largest], data[index]];
index = largest;
}
}
return maximum;
}
}
function lastStoneWeight(stones) {
const heap = new MaxHeap(stones);
while (heap.size > 1) {
const heaviest = heap.pop();
const nextHeaviest = heap.pop();
if (heaviest !== nextHeaviest) {
heap.push(heaviest - nextHeaviest);
}
}
return heap.size === 0 ? 0 : heap.pop();
}
console.log(lastStoneWeight([2, 7, 4, 1, 8, 1])); // 1
If the two heaviest stones differ, put their difference back; if they are equal, both are destroyed.
function memoize(fn) {
// Each node separates object keys (identity-based) from primitive keys.
const createNode = () => ({
objects: new WeakMap(),
primitives: new Map(),
hasValue: false,
value: undefined,
});
const root = createNode();
function memoized(...args) {
// Include `this` so calls with different receivers do not share results.
const keys = [this, ...args];
let node = root;
for (const key of keys) {
const isObjectKey =
(typeof key === "object" && key !== null) || typeof key === "function";
const cache = isObjectKey ? node.objects : node.primitives;
if (!cache.has(key)) cache.set(key, createNode());
node = cache.get(key);
}
// `hasValue` distinguishes a cached undefined from a cache miss.
if (node.hasValue) return node.value;
node.value = fn.apply(this, args);
node.hasValue = true;
return node.value;
}
// Replaces the cache so callers can explicitly invalidate all entries.
memoized.clear = () => {
root.objects = new WeakMap();
root.primitives = new Map();
root.hasValue = false;
root.value = undefined;
};
return memoized;
}
// Example:
// const add = memoize((a, b) => a + b);
// add(2, 3); // computes
// add(2, 3); // returns cached result
Arguments use identity for objects/functions and value equality for primitives; this avoids unreliable JSON serialization.
The cache also distinguishes cached undefined from a miss. Use clear() when results may become stale.
Complexity: Lookup is O(k) for k arguments; space grows with distinct argument tuples.
CodingMediumDream11Software Engineer
15. Longest Substring Without Repeating Characters (LeetCode)
Model answer
The task
Find the length of the longest contiguous section of a string in which every character appears at most once.
Key idea
Maintain a sliding window with no repeated characters. When a character repeats within the window, move the left edge just past its previous occurrence.
Approach
Track each character’s most recent index in a dictionary.
Keep left as the window’s starting index and best as its longest length so far.
For each character, move left forward if its previous occurrence is inside the current window.
Record the character’s current index and update best using the window length.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
last_seen = {}
left = 0
best = 0
for right, char in enumerate(s):
# Skip past a repeated character if it is in the current window.
if char in last_seen and last_seen[char] >= left:
left = last_seen[char] + 1
last_seen[char] = right
best = max(best, right - left + 1)
return best
Complexity:
Time: O(n), because each character is processed once.
Space: O(k), where k is the number of distinct characters encountered.
Common follow-ups
Return the substring itself: store the best window’s start and end indices when updating best.
Handle a stream of characters: keep the same window state and process each arriving character incrementally.
Use a fixed-size character set: replace the dictionary with an array of last-seen indices.
System designHardDream11Frontend EngineerSystem design
16. Design a book reader using these APIs: /books returns a list of books with IDs, /book/:book_id/page_count returns the page count for a book, and /b…
The full question
Design a book reader using these APIs: /books returns a list of books with IDs, /book/:book_id/page_count returns the page count for a book, and /book/:book_id/page/:page_number returns page content in rich-text-editor format. The reader should display the book list, open a selected book, and load subsequent pages as the user scrolls without pagination. Explain how you would handle latency, debounce, jumping to a random page, page caching, preloading, buffer zones, and optimization.
Model answer
1. Requirements & scale
Functional requirements
Show the book list, open a selected book, and display its rich-text pages in a continuous, non-paginated reader.
Load pages on demand as the reader approaches them; support direct jumps to a page.
Preserve reading position and avoid duplicate requests when scrolling quickly.
Non-functional requirements
Keep scrolling responsive while network requests are pending.
Bound browser memory, tolerate slow or failed requests, and preserve the rich-text content safely.
Make the current page available quickly and keep nearby content ready where possible.
Estimates: Assume 100,000 concurrent readers, each generating 0.1 page requests/second on average: about 10,000 page requests/second. At 25 KB compressed per page, that is roughly 250 MB/s of response traffic. If each client retains 20 pages, the browser cache is bounded to about 500 KB of compressed page data, excluding parsed editor structures and images. These are planning assumptions; actual content size and reading behavior should be measured.
2. High-level architecture
The browser owns rendering, scroll behavior, request scheduling, and a bounded page cache. The service routes the existing APIs; a CDN can serve cacheable book metadata or page responses where authorization and freshness permit.
flowchart TD
subgraph Client
A[Book list and reader]
B[Virtual page list]
C[Page scheduler and LRU]
A --> B
B --> C
end
subgraph EdgeCDN[Edge CDN]
D[Static assets]
E[Optional API cache]
end
subgraph LoadBalancer[Load Balancer]
F[API ingress]
end
subgraph APIServices[API Services]
G[Book API]
H[Page API]
end
subgraph Cache
I[Metadata cache]
J[Page response cache]
end
subgraph Datastores
K[Book database]
L[Page content store]
end
subgraph MessageQueue[Message Queue]
M[Cache refresh events]
end
subgraph Workers
N[Cache warmer]
end
A -->|GET books| E
C -->|GET page count and content| E
E -->|cache miss| F
F --> G
F --> H
G --> I
H --> J
I --> K
J --> L
L -->|content updates| M
M --> N
N -->|refresh| J
Diagram
3. API design
GET /books — return book IDs and display metadata. Cache briefly if the list is not user-specific.
GET /book/:book_id/page_count — fetch once when opening a book; use the result to bound the virtual list and reject invalid jumps.
GET /book/:book_id/page/:page_number — fetch one rich-text page. Responses should include a version or ETag so caches can revalidate content.
Cancel obsolete browser requests where supported; otherwise ignore responses whose book ID or request generation no longer matches the active reader.
4. Data model & storage
The client models Book(id, title, metadata) and Page(bookId, pageNumber, content, version, fetchedAt).
Keep the server’s canonical book metadata in a relational store and page content in a store suited to the content representation. The precise backend storage is an implementation choice; the client depends on the API contract, not its physical layout.
Key server page caches by (bookId, pageNumber, version). Partition stored pages by book ID and page number to distribute large books.
In the browser, use a 20-page LRU cache keyed by book and page. Pin visible pages and the active jump target; evict distant pages first. Persisting content in IndexedDB is optional and should respect account and offline requirements.
5. Deep dive
I would use a virtualized list: it represents every page position, but mounts rich-text editor content only for visible pages and a small overscan window. Each unloaded page keeps a placeholder with an estimated height. When actual content arrives, update its measured height while preserving the visible scroll anchor so the reader does not jump unexpectedly.
The scheduler combines visible-page demand with a configurable buffer. For example, request the next page when the user is within two viewport heights of the end of loaded content; request one or two pages ahead, but limit concurrent requests to avoid flooding a slow connection. A short debounce coalesces rapid scroll events; it is not a delay to add after each request. Deduplicate by page key and prioritize visible pages above speculative preloads.
sequenceDiagram
participant U as User
participant R as Reader
participant C as Page cache
participant A as Page API
U->>R: Open book
R->>A: Fetch page count
A-->>R: Page count
R->>C: Check visible and buffer pages
C-->>R: Cache misses
R->>A: Fetch missing pages
A-->>R: Rich-text pages
R->>C: Store and evict by LRU
R-->>U: Render measured pages and placeholders
Diagram
On a jump, validate the target against page count, set it as the high-priority virtual-list index, and fetch that page directly rather than downloading all intervening pages. Keep the target slot mounted as a placeholder until content arrives, then correct its measured height without losing the target position. On errors, show a retry affordance in the affected slot and use bounded exponential backoff; do not silently turn an error into an empty page.
6. Scale, bottlenecks & trade-offs
Use virtualization and an LRU limit to control DOM, editor-instance, and memory growth. Rich-text parsing can cost more than the compressed response, so profile parsed content and images separately.
Preloading improves perceived latency but competes with visible work and data usage. Adapt buffer size to observed latency, connection hints, and scroll velocity; stop speculative fetches when the user reverses direction.
Cache immutable/versioned pages aggressively; revalidate mutable pages. Avoid shared caching for personalized responses unless cache keys include the required authorization context.
The reader should remain usable during latency with stable placeholders, but content consistency still comes from the server. A failed preload is less urgent than a failed visible-page fetch.
Measure page-request latency, cache-hit rate, blank-placeholder duration, scroll-anchor corrections, memory, and error rate. Use those measurements to tune overscan and concurrency rather than choosing a large fixed buffer.
System designHardDream11Frontend EngineerSystem design
17. If a 2 ms debounce is used to load the next page but the response takes 10 ms on a 2G network, how would you handle loading the page?
The full question
If a 2 ms debounce is used to load the next page but the response takes 10 ms on a 2G network, how would you handle loading the page? If memory can store only 20 pages at a time, how would you jump from page 100 to page 300, when would you fetch the page, would you show a blank page, and how would you ensure scrolling ends at page 300?
Model answer
1. Requirements & scale
Functional requirements
Open a book, know its page count, display a continuous virtualized reader, and jump directly from page 100 to page 300.
Keep the browser cache bounded to 20 pages while making the target page appear at the requested position.
Continue rendering and scrolling while page requests are in flight.
Non-functional requirements
A 2 ms debounce must not be treated as a guarantee that content will arrive in 2 ms. Requests and rendering must handle the stated 10 ms response time, plus slower real-world tails.
Avoid blank gaps, duplicate requests, stale responses, and scroll jumps; recover visibly from failures.
Estimates: With 10,000 concurrent readers making 0.1 page requests/second each, the service sees about 1,000 page requests/second. At 25 KB compressed per page, that is about 25 MB/s. A 20-page cache bounds page payloads to roughly 500 KB per client, before parsed rich-text and image overhead.
2. High-level architecture
The browser schedules fetches and virtualizes the list. A jump requests page 300 directly; it does not fetch pages 101–299. The target index is positioned immediately using estimated page heights, while a placeholder remains until content arrives.
flowchart TD
subgraph Client
A[Reader view]
B[Virtual list and placeholders]
C[Request scheduler and 20 page LRU]
A --> B
B --> C
end
subgraph EdgeCDN[Edge CDN]
D[API cache when permitted]
end
subgraph LoadBalancer[Load Balancer]
E[API ingress]
end
subgraph APIServices[API Services]
F[Book API]
G[Page API]
end
subgraph Cache
H[Page cache]
end
subgraph Datastores
I[Book database]
J[Page store]
end
subgraph MessageQueue[Message Queue]
K[Content update events]
end
subgraph Workers
L[Cache refresh worker]
end
A -->|page count| D
C -->|target and nearby pages| D
D -->|miss| E
E --> F
E --> G
F --> I
G --> H
H --> J
J -->|updates| K
K --> L
L -->|refresh| H
Diagram
3. API design
GET /book/:book_id/page_count — call on book open and retain the result for bounds checks.
GET /book/:book_id/page/:page_number — request the target page directly, followed by nearby pages if useful.
Keep requests keyed by (bookId, pageNumber). Deduplicate concurrent requests; cancel obsolete work where possible and discard late responses that do not match the active book or request generation.
4. Data model & storage
Maintain pageCount, activePage, measured page heights, and the visible range in reader state.
Store cached pages as (bookId, pageNumber, content, version, fetchedAt) in a 20-entry LRU. Pin visible pages and the current jump target; evict the farthest non-visible pages first.
Use placeholders for all virtual indexes, not cached rich-text editor instances. This lets the reader represent page 300 without keeping pages 101–299 in memory.
5. Deep dive
A 2 ms debounce only coalesces rapid scroll or navigation events. When the debounce fires, the scheduler starts the request; it does not wait for the response before rendering the list. If a response takes 10 ms, keep a skeleton or estimated-height placeholder on screen during those 10 ms. In production, design for much longer tail latency too. Never insert an empty page that looks like valid content.
For a jump from page 100 to page 300:
Validate 300 against the fetched page count, set page 300 as the active high-priority target, and calculate its virtual-list offset from measured heights plus an average-height estimate for unmeasured pages.
Immediately scroll the virtualizer to index 300 and render a placeholder there. This gives the user the correct location without waiting for the network.
Fetch page 300 immediately. Do not fetch pages 101–299: they are not needed to render a random jump. Once page 300 is available, optionally fetch 299 and 301 if they are likely to be read next and cache capacity permits.
On arrival, replace the placeholder, measure the actual page height, and update virtual offsets. Preserve the target page and a stable scroll anchor while correcting any accumulated height estimate error. Thus scrolling remains positioned at page 300 rather than snapping back to the old position.
Keep page 300 pinned until it is no longer visible or the user navigates away. Evict distant pages as needed to stay within the 20-page cap.
sequenceDiagram
participant U as User
participant V as Virtual reader
participant S as Scheduler and LRU
participant P as Page API
U->>V: Jump to page 300
V->>V: Set target and estimate offset
V-->>U: Scroll to page 300 placeholder
V->>S: Request page 300 at high priority
S->>P: GET page 300
P-->>S: Rich-text page after network latency
S->>S: Insert page and evict unpinned LRU entries
S-->>V: Page 300 content
V->>V: Measure height and preserve anchor
V-->>U: Render page 300 at stable position
Diagram
If the target request fails, leave the target position intact and show an inline retry state. Use bounded retries with backoff, and do not let a late response from page 100 overwrite the current jump state. If the user jumps again before the response arrives, reprioritize the new target and ignore or cancel the obsolete request.
6. Scale, bottlenecks & trade-offs
A placeholder avoids a visually blank reader and makes navigation immediate, but estimated heights can cause small offset corrections. Improve estimates using measured page heights and preserve the scroll anchor on every correction.
Direct target fetch minimizes latency and bandwidth; fetching every intermediate page would waste both and exceed a 20-page cache. Nearby preloading is a trade-off: make it low priority and conditional on network quality and likely reading direction.
Limit concurrent requests and prioritize visible pages, then the jump target, then buffer pages. The 2 ms debounce must not create a queue of redundant requests; deduplicate by page key and coalesce scroll events.
Virtualize both DOM nodes and rich-text editor instances. A 20-page payload limit alone does not bound memory if parsed content or editor objects remain mounted.
Track time from jump to target content, placeholder duration, scroll correction distance, cache evictions, request failures, and memory. Use these metrics to tune page-height estimates, prefetch distance, and concurrency.
18. What is the difference between useEffect and useLayoutEffect?
Model answer
useEffect runs after React commits the render and lets the browser/native renderer paint first when possible. Use it for effects that do not need to block the visible update: fetching data, subscriptions, analytics, and timers. On the web, it generally avoids delaying paint; in React Native, effects run after the commit rather than during render.
useLayoutEffect runs synchronously after the commit but before the browser paints. Use it when you must read layout and apply a correction before the user sees the frame—for example, measuring an element and positioning a tooltip. Because it can delay paint, keep it small; it is not a general replacement for useEffect.
sequenceDiagram
participant R as React render
participant C as Commit
participant L as useLayoutEffect
participant P as Paint
participant E as useEffect
R->>C: Commit UI changes
C->>L: Run synchronously
L-->>C: Measurements or updates
C->>P: Paint frame
P->>E: Run after commit
Diagram
Both hooks run after commit, never during render. Their setup functions may return cleanup functions, which React calls before rerunning the effect and when the component unmounts. In development Strict Mode, React may run an extra setup/cleanup cycle to expose effects that are not resilient to remounting.
19. What is the difference between display: none, visibility: hidden, and opacity: 0?
Model answer
display: none removes the element from layout, so it takes up no space. It is generally also removed from the accessibility tree. Use it when the content should be absent from both the visual layout and normal assistive-technology navigation.
visibility: hidden keeps the element’s layout space but does not paint it. It is generally hidden from the accessibility tree, too. It can be useful when hiding content without shifting surrounding layout.
opacity: 0 makes the element transparent, but it still occupies layout space and remains in the accessibility tree. It can also still receive pointer events and keyboard focus unless you handle those separately—for example, with pointer-events: none and appropriate focus management.
The practical distinction is layout: display: none removes the box; the other two preserve it. For accessibility, do not use opacity: 0 alone to hide interactive content. If the intent is to hide content from everyone, use a suitable hidden-state pattern and ensure its focus and accessibility behavior matches the interaction.
20. How can you optimize large lists in React Native?
Model answer
Virtualize the list. Use FlatList or SectionList rather than rendering every row in a ScrollView. They render a window around the viewport; tune initialNumToRender, maxToRenderPerBatch, updateCellsBatchingPeriod, and windowSize against scroll smoothness and memory. Consider Shopify's FlashList for large, variable-content feeds after measuring it in your app.
Make rows cheap to render. Extract a row component, wrap it in React.memo, and pass stable props. Use useCallback for callbacks and avoid creating new objects or functions for every item on each parent render. Keep state local to the row where possible, and avoid expensive formatting or filtering inside renderItem.
Give the list reliable identity and geometry. Provide a stable keyExtractor; do not use array indexes when items can be inserted, removed, or reordered. If row height is fixed or computable, implement getItemLayout so the list can skip measurement and scroll accurately.
Control data and media costs. Paginate or append data incrementally with onEndReached; avoid replacing the entire dataset for a small update. Size images for their rendered dimensions, use caching, and show placeholders while loading. For frequently changing data, update only affected rows rather than rebuilding the list.
Profile before tuning. Measure release builds on representative low-end devices. Use React DevTools/Profiler and native performance tools to distinguish JS-thread render work from UI-thread layout, image decoding, or animation jank. Tune one setting at a time and watch memory as well as frame rate.
Practice these out loud, don't memorise them
Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.