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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

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
Max-Heap
Greedy
Strings
Rearrangement
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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...


Submit Your Answer
Markdown supported