Ad Targeting Engine and Route Optimization
Data Structure DesignModel answerLast updated
Build an ad matcher with inverted indexes and a delivery router using shortest-path precomputation plus TSP heuristics.
You are building two independent services:
Part A: Ad Targeting Engine
Design and implement a data structure that manages ad campaigns and matches them to incoming requests.
Operations:
add(campaign): Register a new campaign or update an existing oneremove(campaign_id): Unregister a campaignmatch(request, k): Return up to k best-matching campaigns
Specifications:
- Each campaign has: unique ID, targeting rules (attribute → allowed values), bid amount, and remaining budget
- A request contains attributes (e.g.,
{"location": "NYC", "device": "mobile", "interests": ["sports", "tech"]}) - A campaign matches if all its targeted attributes are satisfied by the request. Attributes can be single-valued or multi-valued (sets).
- Only campaigns with
budget >= bidare eligible - Return the top k campaigns ranked by bid (break ties by ID)
Optimize for high read throughput (matching happens far more often than campaign updates). Discuss time/space complexity and trade-offs.
Part B: Delivery Route Planner
Given a road network (weighted directed graph with non-negative edges), a depot location, and N delivery stops, compute an efficient round-trip route.
Input:
- Graph: nodes, edges with weights (distances or travel times)
- Depot: starting/ending node
- Stops: list of N nodes to visit
Output:
- Ordered list of stops forming a route (depot → stops → depot)
- Total route cost
Compare exact and approximate approaches. Discuss complexity, practical scaling limits, and how to handle real-world constraints like vehicle capacity or time windows.
Hints
Hint 1
For ad matching: Think about reversing the lookup direction—instead of scanning campaigns, index by attribute values
Hint 2
For routing: Precompute pairwise distances first, then solve the ordering problem separately
Hint 3
Consider when exact solutions become impractical and what heuristics give acceptable results
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Ad Targeting Engine and Route Optimization
Both problems share a common theme: choosing the right precomputation to make the frequent operation fast, and being explicit about where you trade optimality for speed.
Part A: Ad Targeting Engine
Approach
Contract definition:
- Targeting rules map attributes to sets of acceptable values
- Missing attributes in targeting mean "accept any value"
- For multi-valued request attributes (like interests), at least one value must be in the campaign's allowed set
- Empty allowed sets in targeting mean impossible to match
Naive solution: Iterate through all campaigns on each request, checking every targeting rule. This costs O(C · A) per match, where C is campaign count and A is average attributes per campaign.
Optimized solution: Build an inverted index mapping (attribute, value) → set of campaign IDs. Use a counting algorithm:
- For each request attribute-value pair, look up which campaigns accept that value
- Increment a counter for each found campaign
- A campaign matches when its counter equals the number of attributes it targets
- Campaigns with no targeting rules go in a separate set and always match
- Filter by budget, then return top k by bid
Why counting works:
- Each campaign accumulates at most one count per attribute (union values before counting for multi-valued fields)
- A campaign's counter reaches
target_countonly when all its rules are satisfied - Attributes not in the campaign's targeting never block a match
Implementation
from collections import defaultdict
from dataclasses import dataclass
import heapq
@dataclass
class Campaign:
id: str
targeting: dict # attr → set of allowed values
bid: float
budget: float
class AdTargetingEngine:
def __init__(self):
self.campaigns = {}
self.inverted_index = defaultdict(lambda: defaultdict(set))
self.universal_campaigns = set() # no targeting rules
def add(self, campaign: Campaign) -> None:
# Remove old version if updating
if campaign.id in self.campaigns:
self.remove(campaign.id)
self.campaigns[campaign.id] = campaign
if not campaign.targeting:
self.universal_campaigns.add(campaign.id)
return
# Index each (attribute, value) pair
for attr, allowed_values in campaign.targeting.items():
for value in allowed_values:
self.inverted_index[attr][value].add(campaign.id)
def remove(self, campaign_id: str) -> bool:
campaign = self.campaigns.pop(campaign_id, None)
if not campaign:
return False
self.universal_campaigns.discard(campaign_id)
for attr, allowed_values in campaign.targeting.items():
for value in allowed_values:
self.inverted_index[attr][value].discard(campaign_id)
# Cleanup empty sets
if not self.inverted_index[attr][value]:
del self.inverted_index[attr][value]
return True
def match(self, request: dict, k: int = 1) -> list:
match_counts = defaultdict(int)
# Count satisfied attributes per campaign
for attr, value in request.items():
if attr not in self.inverted_index:
continue
# Handle multi-valued attributes
values = value if isinstance(value, (set, list, tuple)) else [value]
# Union all campaigns matching any of the values
satisfied_campaigns = set()
for v in values:
satisfied_campaigns |= self.inverted_index[attr].get(v, set())
for cid in satisfied_campaigns:
match_counts[cid] += 1
# Find fully matched campaigns
matched = []
for cid, count in match_counts.items():
campaign = self.campaigns[cid]
if count == len(campaign.targeting) and campaign.budget >= campaign.bid:
matched.append(campaign)
# Add universal campaigns if eligible
for cid in self.universal_campaigns:
campaign = self.campaigns[cid]
if campaign.budget >= campaign.bid:
matched.append(campaign)
# Return top k by bid (descending), then by ID
return [c.id for c in heapq.nlargest(k, matched, key=lambda c: (c.bid, -hash(c.id)))]
Complexity Analysis
| Operation | Time | Space |
|---|---|---|
add | O(T) where T = total targeted values | O(T) per campaign |
remove | O(T) | - |
match | O(P + M log k) where P = posting list sizes, M = matched campaigns | O(M) |
The match cost is proportional to campaigns actually examined, not total campaign count.
Trade-offs and Extensions
Common value problem: Popular values like device=mobile create massive posting lists. Mitigations:
- Process selective attributes first, intersect posting lists
- Use compressed bitmaps (Roaring Bitmaps) instead of sets
- Bloom filters for quick negative lookups
Range predicates: Age ranges (18-34) need interval trees or segment trees, not hash-based indexing.
Complex boolean logic: Full DNF/CNF expressions require the algorithm from "Indexing Boolean Expressions" papers. This design handles conjunctive predicates.
Budget management: In distributed systems, use rate limiting and approximate counters rather than strict synchronization. Accept slight overspend for throughput.
Update patterns: High churn benefits from lazy deletion with periodic index rebuilds rather than eager cleanup.
Part B: Delivery Route Planner
Approach
Decompose into two phases:
Phase 1: Distance Matrix Construction Run shortest-path algorithm from depot and each stop to compute all-pairs distances. This creates a metric space where the triangle inequality holds.
Phase 2: Tour Optimization Solve the Traveling Salesman Problem on the resulting complete graph:
- Exact: Dynamic programming (Held-Karp) for N ≤ 12-15
- Heuristic: Nearest neighbor initialization + 2-opt improvement for larger N
Implementation
import heapq
from itertools import combinations
def dijkstra(graph, start):
"""Compute shortest paths from start to all nodes."""
dist = {start: 0}
pq = [(0, start)]
while pq:
d, u = heapq.heappop(pq)
if d > dist.get(u, float('inf')):
continue
for v, weight in graph.get(u, []):
new_dist = d + weight
if new_dist < dist.get(v, float('inf')):
dist[v] = new_dist
heapq.heappush(pq, (new_dist, v))
return dist
def build_distance_matrix(graph, depot, stops):
"""Precompute all pairwise shortest paths."""
locations = [depot] + stops
n = len(locations)
dist_matrix = [[float('inf')] * n for _ in range(n)]
for i, loc in enumerate(locations):
distances = dijkstra(graph, loc)
for j, target in enumerate(locations):
dist_matrix[i][j] = distances.get(target, float('inf'))
return dist_matrix, locations
def held_karp_tsp(dist_matrix):
"""Exact TSP solution via dynamic programming. O(2^n * n^2)"""
n = len(dist_matrix)
if n == 1:
return [0], 0
# dp[mask][i] = min cost to visit nodes in mask, ending at i
dp = {}
parent = {}
# Base case: paths of length 1 from depot (index 0)
for i in range(1, n):
dp[(1 << i, i)] = (dist_matrix[0][i], 0)
# Iterate over subset sizes
for size in range(2, n):
for subset in combinations(range(1, n), size):
mask = sum(1 << i for i in subset)
for last in subset:
prev_mask = mask ^ (1 << last)
candidates = []
for prev in subset:
if prev == last:
continue
prev_cost, _ = dp.get((prev_mask, prev), (float('inf'), None))
candidates.append((prev_cost + dist_matrix[prev][last], prev))
if candidates:
dp[(mask, last)] = min(candidates)
# Find best ending node
full_mask = (1 << n) - 2 # All stops except depot
final_costs = [(dp.get((full_mask, i), (float('inf'),))[0] + dist_matrix[i][0], i)
for i in range(1, n)]
total_cost, last_node = min(final_costs)
# Reconstruct path
path = [last_node]
mask = full_mask
while mask:
_, prev = dp[(mask, path[-1])]
mask ^= (1 << path[-1])
if prev:
path.append(prev)
return [0] + path[::-1] + [0], total_cost
def nearest_neighbor_tsp(dist_matrix):
"""Greedy TSP heuristic. O(n^2)"""
n = len(dist_matrix)
unvisited = set(range(1, n))
tour = [0]
while unvisited:
current = tour[-1]
nearest = min(unvisited, key=lambda i: dist_matrix[current][i])
tour.append(nearest)
unvisited.remove(nearest)
tour.append(0)
cost = sum(dist_matrix[tour[i]][tour[i+1]] for i in range(len(tour)-1))
return tour, cost
def two_opt_improve(dist_matrix, tour):
"""Local search improvement. O(n^2) per iteration."""
n = len(tour)
improved = True
while improved:
improved = False
for i in range(1, n - 2):
for j in range(i + 1, n - 1):
# Try reversing segment [i, j]
old_cost = (dist_matrix[tour[i-1]][tour[i]] +
dist_matrix[tour[j]][tour[j+1]])
new_cost = (dist_matrix[tour[i-1]][tour[j]] +
dist_matrix[tour[i]][tour[j+1]])
if new_cost < old_cost:
tour[i:j+1] = reversed(tour[i:j+1])
improved = True
break
if improved:
break
cost = sum(dist_matrix[tour[i]][tour[i+1]] for i in range(len(tour)-1))
return tour, cost
def plan_route(graph, depot, stops):
"""Main routing function."""
dist_matrix, locations = build_distance_matrix(graph, depot, stops)
n = len(stops)
if n <= 12:
# Use exact algorithm
tour_indices, cost = held_karp_tsp(dist_matrix)
else:
# Use heuristic
tour_indices, cost = nearest_neighbor_tsp(dist_matrix)
tour_indices, cost = two_opt_improve(dist_matrix, tour_indices)
# Convert indices back to node IDs
route = [locations[i] for i in tour_indices]
return route, cost
Complexity Analysis
| Component | Time | Space |
|---|---|---|
| Distance matrix (K Dijkstras) | O(K(E + V log V)) | O(K² + V) |
| Held-Karp DP | O(2^N · N²) | O(2^N · N) |
| Nearest neighbor | O(N²) | O(N) |
| 2-opt | O(N²) per pass | O(N) |
Where K = N + 1 (stops plus depot).
Practical Considerations
Scaling threshold: Held-Karp becomes impractical beyond N ≈ 15. Nearest neighbor + 2-opt typically gives solutions within 5-10% of optimal.
Capacity constraints (CVRP): Split stops into multiple vehicle trips using bin packing or clustering, then route each trip.
Time windows: Use constraint programming solvers or modify 2-opt to respect time feasibility.
Asymmetric graphs: 2-opt assumes symmetric distances. For directed graphs, use 3-opt or Or-opt moves.
Real-time updates: Maintain the distance matrix incrementally and use fast re-optimization (relocate single stops) rather than full replanning.
Alternative heuristics: Christofides algorithm (1.5-approximation), genetic algorithms, or simulated annealing for better quality at higher cost.
Common Mistakes
- Forgetting that TSP needs the metric closure—running Dijkstra from every location first
- Applying 2-opt to the original graph structure instead of the complete distance matrix
- Not handling unreachable nodes or disconnected graphs
- Assuming exact solutions scale beyond 15-20 stops
- Ignoring the symmetric/asymmetric distinction in local search