Assign Ads to Browser Positions
eBaySoftware Engineer · Technical ScreenLast updated
This question evaluates algorithmic problem-solving around randomized selection, constraint-based resource allocation, and per-user state management, including enforcing eligibility rules and incrementing display counts.
Implement a function that assigns ads to browser positions for a single user.
You are given:
positions: a list of browser position identifiers, such as"top","sidebar", or"bottom".candidateAds: a list of ads that may be shown. Each ad has:adId: a unique string identifier.perUserLimit: the maximum number of times this ad may be shown to the same user.userAdState: a dictionary keyed byadId, where each value is the number of times that ad has already been displayed to this user.
Write a function that returns an assignment of ads to browser positions and updates the user's ad state.
Requirements:
- Assign ads randomly among eligible candidates.
- An ad is eligible only if its current display count for this user is less than its
perUserLimit. - If there are enough eligible ads to fill all positions, do not assign the same ad to more than one position in the same call.
- If there are fewer eligible ads than positions, assign as many positions as possible. You may reuse an ad only if doing so still respects its remaining per-user limit.
- Every time an ad is assigned, increment its count in
userAdState. - Return both the position-to-ad assignment and the updated state.
Example input:
positions = ["top", "middle", "bottom"]
candidateAds = [
{ adId: "ad_a", perUserLimit: 2 },
{ adId: "ad_b", perUserLimit: 1 },
{ adId: "ad_c", perUserLimit: 3 }
]
userAdState = {
"ad_a": 1,
"ad_b": 1
}
One valid randomized output could be:
assignments = {
"top": "ad_c",
"middle": "ad_a",
"bottom": null
}
updatedUserAdState = {
"ad_a": 2,
"ad_b": 1,
"ad_c": 1
}
The exact assignment may vary because the selection is random.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.