Streaming Home Feed: Visible-Grid Deduplication
System DesignModel answerLast updated
Design the algorithm and surrounding system that ensures every show tile visible on a streaming home page appears at most once, across all rows and columns.
Context
A streaming platform's home page is a grid of rows — "Popular Now", "Because You Watched X", "New Releases", and so on. Each row is generated independently by a separate ranking service and can contain 50–100 candidate titles in priority order. Because rows are generated independently, the same show can appear in multiple rows at the same time.
Product wants a hard guarantee: no show appears more than once anywhere in the first visible screen. Below the fold and past the horizontal scroll boundary, duplicates are tolerable but should be minimized.
What you're asked to design
- Define your terms. What counts as the "visible grid"? What makes two tiles duplicates? What device differences matter?
- Propose an algorithm. Walk through the logic step by step. Justify the traversal order you choose.
- Place it in a system. Where does this logic live — client, server, or both? How does it fit in the page-assembly pipeline?
- Handle edge cases. What happens when a row runs out of unique candidates before filling its visible columns? What if the grid shrinks or grows, for example on a browser resize?
- Discuss trade-offs. Greedy vs. global optimization, row-major vs. column-major fill, server-side vs. client-side enforcement, and how you'd validate the change.
A strong answer: states assumptions before diving in, presents a clean working algorithm, correctly characterizes its complexity, and explains what you'd give up with a simpler approach versus what you'd gain with a more expensive one.
Hints
Hint 1
Start by pinning down the two key ambiguities — what 'visible' means per device and what makes two titles the same show — before touching any algorithm. Interviewers look for this grounding step.
Hint 2
Think about traversal order: filling each row left-to-right before moving to the next row is simpler, but filling the entire leftmost column first (column-major) better respects how users actually scan. Work out which order is more defensible and why.
Hint 3
When a row exhausts its unique candidates before filling its visible slots, you have two choices: leave the row short or drop it and promote the next one. Think through what 'dropping a row' means for the seen-set — should those titles stay reserved?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify before designing
The first thing to nail down is what the visible grid actually is, because it varies by device:
- TV: roughly 4–5 rows × 6 columns
- Web browser: roughly 3–4 rows × 5–7 columns (depends on window width)
- Mobile: roughly 3 rows × 3 columns
The client sends its viewport dimensions — R rows, C columns — so the server knows exactly which slots need the hard uniqueness guarantee.
The second thing to nail down is the duplicate definition. Two tiles are duplicates if they resolve to the same canonical show ID. "Stranger Things Season 4" and "Stranger Things" are the same show, so the system needs a title-to-canonical-show mapping before the deduplication pass. Without this step, the algorithm solves the wrong problem.
Scope of the rule:
- Inside the viewport: uniqueness is a hard constraint.
- Below the fold / horizontal overflow: uniqueness is a soft goal — best effort, not guaranteed.
2. Where deduplication lives
Deduplication belongs in a server-side page-assembly service, for three reasons:
- It sees all rows simultaneously, which is necessary to make cross-row decisions.
- It enforces the rule identically for every client, platform, and experiment variant.
- It can be A/B tested and rolled back without a client release.
The client keeps a lightweight fallback that re-deduplicates when the viewport changes — for example, a browser window resize — but the server result is authoritative.
The pipeline looks like this:
Row generators (parallel, per-row rankers)
↓
Page-level row ordering model
↓
Page assembly service ← deduplication lives here
↓
Edge cache (per profile × device class, short TTL)
↓
Client
3. Core algorithm: column-major greedy fill
Why column-major? Users scan the left edge of every row before scrolling right, so the leftmost column slot in each row is higher value than the rightmost. Column-major fill means each row gets its best available unique title for column 0 before any row takes a column 1 slot. Row-major fill (complete row 1, then row 2) lets the top row consume many strong titles before lower rows get a chance, which degrades row relevance downstream. Column-major is the more defensible choice.
The algorithm in plain English:
- Maintain a
seenset of canonical show IDs already placed in the visible grid. - Walk columns 0 through C−1. For each column, walk every active row top to bottom.
- For each (row, column) slot, advance that row's pointer until it finds a candidate not in
seen, place it, and add it toseen. - If a row exhausts its candidates before filling its required minimum columns, drop that row: remove its already-placed titles from
seen(freeing them for lower rows), and promote the next candidate row. Catch the promoted row up to the current column before continuing.
from typing import Dict, List, Optional
def dedupe_viewport(
rows: List[List[str]], # ranked canonical IDs per row, in page order
num_rows: int, # R: visible row count
num_cols: int, # C: visible column count
min_visible: Optional[int] = None # drop a row that can't show this many unique tiles
) -> List[List[str]]:
if min_visible is None:
min_visible = num_cols
seen: set[str] = set()
pointers: Dict[int, int] = {}
filled: Dict[int, List[str]] = {}
active: List[int] = []
next_row = 0
def admit_row() -> bool:
nonlocal next_row
if next_row >= len(rows):
return False
idx = next_row
active.append(idx)
pointers[idx] = 0
filled[idx] = []
next_row += 1
return True
# Seed the initial viewport rows
while len(active) < num_rows and admit_row():
pass
for col in range(num_cols): # column-major traversal
i = 0
while i < len(active):
r = active[i]
p = pointers[r]
# Advance past already-seen candidates
while p < len(rows[r]) and rows[r][p] in seen:
p += 1
if p < len(rows[r]):
# Found a unique candidate: place it
seen.add(rows[r][p])
filled[r].append(rows[r][p])
pointers[r] = p + 1
i += 1
else:
# Row exhausted
pointers[r] = p
if len(filled[r]) < min_visible:
# Drop the row: free its titles so lower rows can use them
seen.difference_update(filled[r])
active.pop(i)
del filled[r]
# Promote the next row and catch it up to the current column
if admit_row():
nr = active[-1]
for _ in range(col):
q = pointers[nr]
while q < len(rows[nr]) and rows[nr][q] in seen:
q += 1
if q < len(rows[nr]):
seen.add(rows[nr][q])
filled[nr].append(rows[nr][q])
pointers[nr] = q + 1
else:
pointers[nr] = q
break
else:
i += 1 # Row is short but meets minimum; keep it
return [filled[r] for r in active]
Complexity:
- Time: O(total candidates scanned). Every pointer moves forward only, and
seenlookups are O(1). In practice ~40 rows × 100 candidates = ~4K operations, well under a millisecond. - Space: O(R × C + number of rows) for
seen,filled, andpointers.
4. Greedy vs. global optimization
The greedy approach can be suboptimal. Consider: row 1 takes title A in column 4, but row 3's only strong candidate was A. A global formulation is a weighted bipartite matching — slots on one side, titles on the other, edge weights encoding relevance × slot attention — that maximizes total relevance across the visible grid. This finds the true optimum.
The trade-off is cost: bipartite matching is O(n³) or O(n² log n) with priority queues, versus effectively O(n) for greedy. For a ~30-slot viewport the runtime is still fine, but the implementation complexity and operational risk are higher. Greedy is the right default; global matching is worth revisiting only if metric analysis shows meaningful relevance degradation on rows below the first two.
5. Edge cases and common mistakes
- Not canonicalizing IDs first. This is the most common mistake. Without a title → canonical show mapping, the algorithm misses duplicates that appear under different title IDs.
- Forgetting to free the seen-set when dropping a row. If you drop a row but keep its titles in
seen, lower rows can never reclaim those titles. This produces a grid with fewer unique strong shows than necessary. - Viewport resize on the client. The server returns more than C candidates per row so the client can re-flow on a resize without a round trip. The client re-runs a lightweight version of the same algorithm.
- min_visible tuning. Setting this too high drops rows aggressively and produces a sparse page. Setting it to 1 means rows with a single visible tile clutter the grid. A reasonable default is
ceil(num_cols / 2), tuned by experiment.
6. Validating the rollout
Run an A/B test. Primary metric: duplicate tile rate in the viewport (should drop to zero in the treatment arm). Guardrail metrics: row fill rate, per-row relevance scores, and engagement (clicks, plays) on rows 2 and below — if deduplication is hurting relevance downstream, it will show up there first.