Identify Customers With Unmet Service Needs
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests spatial hashing and set union logic to find customers whose required service tags are not collectively offered by any nearby vendor within a radius.
Problem Statement
You are given a list of customers, a list of vendors, and a numeric range value. Each customer is situated at a 2D coordinate and needs a particular collection of service tags. Each vendor is located at a 2D coordinate and supplies a particular collection of service tags.
A vendor is within range of a customer when the Euclidean distance between their coordinates does not exceed range. Euclidean distance between (x1, y1) and (x2, y2) is sqrt((x1 - x2)^2 + (y1 - y2)^2).
A customer is fully served when every service tag they need appears in the combined offerings of all vendors within range. Tags can come from different vendors — no single vendor must supply all of them.
A customer is underserved when at least one needed tag is missing from every vendor within range. Return the IDs of all underserved customers in the same order they appear in the input.
Input Format
Each element of customers is a dict with:
'id': an integer identifier'coords': a list or tuple[x, y]of integer coordinates'specialties': a set or list of string tags the customer needs
Each element of vendors is a dict with:
'id': an integer identifier'coords': a list or tuple[x, y]of integer coordinates'specialties': a set or list of string tags the vendor offers
range is a float or int.
Edge Case Rules
- A customer whose
specialtiesis empty needs nothing and is never underserved. - If
rangeis negative, no vendor can ever be within range, so every customer with at least one needed tag is underserved. - If
rangeis zero, only vendors at the exact same coordinates as the customer count as within range. - Distance comparison is inclusive: a vendor at exactly
rangedistance is within range.
Constraints
- Number of customers and vendors: up to 10,000 each.
- Coordinates: integers in the range
[-10,000, 10,000]. - Service tags: non-empty strings.
range: any numeric value (including zero and negatives).- The returned list must preserve the original ordering of
customers.
Examples
Example 1
Input: find_uncovered_clients([{'id': 1, 'coords': [0, 0], 'specialties': ['Cardio', 'Dentist']}], [{'id': 10, 'coords': [1, 1], 'specialties': ['Cardio']}], 2)
Output: [1]
Example 2
Input: find_uncovered_clients([{'id': 2, 'coords': [0, 0], 'specialties': ['Eye']}], [{'id': 11, 'coords': [0, 1], 'specialties': ['Eye']}], 2)
Output: []
Hints
Hint 1
Pairing every customer with every vendor is O(C·V) which can reach 10^8 comparisons. Consider bucketing vendors by location to prune candidates.
Hint 2
A uniform grid with cell side length equal to `range` guarantees any vendor within distance `range` of a customer lies in one of the 9 cells surrounding the customer's own cell. Use `math.floor(coord / range)` for cell keys, not `int()` which truncates toward zero for negatives.
Hint 3
Coverage is a union across vendors. Track the set of still-unmet tags per customer, subtract each nearby vendor's tags, and stop early when the set is empty. Handle `range == 0` separately to avoid division by zero by grouping vendors by exact coordinate.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why brute force is too slow
Checking every customer against every vendor requires O(C · V) distance computations, which can reach 10^8 at maximum input sizes. We need a way to quickly skip vendors that cannot possibly be within range.
Uniform grid (spatial hashing)
Divide the plane into square cells with side length equal to range. Place each vendor into the cell containing its coordinates, keyed by (floor(x / range), floor(y / range)).
Geometric guarantee: if a vendor is within Euclidean distance range of a customer, their coordinates differ by at most range on each axis. Two values that differ by at most range produce floor values that differ by at most 1. Therefore every in-range vendor must reside in one of the 9 cells in the 3x3 block centered on the customer's own cell. We only examine those cells.
Each candidate that survives the cell filter still gets an exact squared-distance check (dx^2 + dy^2 <= range^2), which avoids sqrt and stays exact for integer coordinates.
Coverage as set subtraction
A customer's coverage is the union of tags across all in-range vendors, not any single one. We maintain a remaining set of still-unmet tags. For each in-range vendor we subtract its tags from remaining. As soon as remaining empties, the customer is fully served and we stop early. If anything remains after scanning all candidates, the customer is underserved.
Special cases
- Empty specialties: the customer needs nothing, so skip immediately and never report them.
- Negative range: no vendor can be within a negative distance. Every customer with at least one needed tag is underserved. Return their IDs without any spatial work.
- Zero range: dividing by zero in the cell formula is undefined. Coverage collapses to exact coordinate matches, so group vendors by
(x, y)in a dict and check subset membership. math.floorvsint():int()truncates toward zero, soint(-0.5)gives0butfloor(-0.5)gives-1. Usingfloorkeeps cell boundaries consistent across negative coordinates.- Input safety: we copy the customer's tags into a fresh set before mutating, so the original dicts are never modified.
Correctness argument
- No in-range vendor is missed: proved by the plus-or-minus 1 cell difference bound.
- No out-of-range vendor is counted: the exact squared-distance check is applied before any vendor contributes to coverage.
- Order preserved: we iterate customers in input order and append to the result in that same pass.
Complexity
Let C = number of customers, V = number of vendors, T = average tags per entity.
- Build phase: O(V) to bucket all vendors.
- Query phase: each customer inspects 9 cells. If the average occupancy per cell is k, the cost per customer is O(k · T). With uniformly spread data k is small, giving close to O((C + V) · T) overall. In the worst case where all vendors cluster in one neighborhood it degrades to O(C · V · T), matching brute force, but the early exit on
remainingmitigates this in practice. - Space: O(V) for the grid, O(T) per customer for the working set.
Reference solution
from math import floor
from typing import List, Dict
def find_uncovered_clients(customers: List[Dict], vendors: List[Dict], range: float) -> List[int]:
if range < 0:
return [c['id'] for c in customers if c['specialties']]
if range == 0:
by_location = {}
for v in vendors:
x, y = v['coords']
by_location.setdefault((x, y), set()).update(v['specialties'])
result = []
for c in customers:
needed = set(c['specialties'])
if not needed:
continue
x, y = c['coords']
if not needed.issubset(by_location.get((x, y), set())):
result.append(c['id'])
return result
grid = {}
for v in vendors:
x, y = v['coords']
key = (floor(x / range), floor(y / range))
grid.setdefault(key, []).append(v)
limit_sq = range * range
result = []
for c in customers:
remaining = set(c['specialties'])
if not remaining:
continue
x, y = c['coords']
cx = floor(x / range)
cy = floor(y / range)
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for v in grid.get((cx + dx, cy + dy), ()):
vx, vy = v['coords']
if (x - vx) ** 2 + (y - vy) ** 2 <= limit_sq:
remaining.difference_update(v['specialties'])
if not remaining:
break
if not remaining:
break
if not remaining:
break
if remaining:
result.append(c['id'])
return result