Rearrange Ad Slots So No Two Adjacent Ads Share an Advertiser
Last updated: November 29, 2026
Quick Overview
Given a list of ads tagged by advertiser, reorder them so that no two consecutive slots show the same advertiser. Return any valid order, or an empty list if none exists.
0
0
0 solved
Given a list of ads tagged by advertiser, reorder them so that no two consecutive slots show the same advertiser. Return any valid order, or an empty list if none exists.
A Google onsite favorite reframed for ad diversity on a results page. The interviewer checks the feasibility condition (no advertiser more than ceil(n/2) times) and the max-heap greedy that holds back the last-used advertiser.
What the Interviewer Expects
- States the feasibility bound ceil(n / 2)
- Uses a max-heap of counts
- Holds the previous advertiser out for one step
- Returns empty when infeasible
- Explains why the greedy never gets stuck when feasible
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Generalize to a gap of at least k between same advertisers
- What if some slots are pinned to specific ads?
- Can you do it in O(n) without a heap?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: list of advertiser IDs (strings), length n.
- Output: a permutation where adjacent entries differ, or
[]if impossible. - Any valid arrangement is accepted....
High-Level Design
Impossible exactly when some advertiser appears more than (n + 1) // 2 times, because even alternating perfectly leaves two of its ads adjacent.
Greedy: repeatedly place the advertiser with the mos...