Find Members Missing a Nearby Provider Specialty
Arrays & HashingAuto-graded · 15 test casesLast updated
Given providers and members on a 2D plane, find members with a required specialty that has no provider within a distance limit, using hashing and spatial grouping.
Find Members Missing a Nearby Provider Specialty
A health plan wants to check that each of its members can reach every kind of care they need without traveling too far.
Input
providers: a list of dictionaries, each with:id: integer provider IDspecialty: string naming the provider's specialtylocation: a pair[x, y](or tuple) of coordinates
members: a list of dictionaries, each with:id: integer member IDlocation: a pair[x, y]of coordinatesrequired_specialties: a list of specialty strings the member needs
max_distance: a non-negative number, the farthest a member is willing to travel
Distances are straight-line (Euclidean) distances between points.
Task
A member is served if, for every specialty in their required_specialties, at least one provider of that specialty lies at distance less than or equal to max_distance from the member.
A member is underserved if at least one required specialty has no provider within that distance. This includes a specialty that no provider offers at all.
Return the IDs of all underserved members, in the same order in which those members appear in members.
Rules and edge cases
- A distance exactly equal to
max_distancecounts as within range. Compare squared distance with the squared limit to avoid taking square roots. - If
max_distanceis0, a provider is in range only if it sits at exactly the member's coordinates. - A member with an empty
required_specialtieslist is always served. - A specialty may be repeated in a member's list, and several providers may share a location or specialty.
- If every member is served, or
membersis empty, return an empty list.
Constraints
0 <= len(providers), len(members) <= 10^5- Each member's
required_specialtieslist is short (on the order of a few entries). - Coordinates are integers or floats of moderate magnitude.
max_distance >= 0- Member IDs are unique.
Examples
Example 1
Input: find_underserved_members([{'id': 1, 'specialty': 'Cardiology', 'location': [1, 2]}, {'id': 2, 'specialty': 'Dermatology', 'location': [3, 4]}], [{'id': 101, 'location': [2, 3], 'required_specialties': ['Cardiology', 'Dermatology']}, {'id': 102, 'location': [10, 10], 'required_specialties': ['Cardiology']}], 5)
Output: [102]
Hints
Hint 1
Group providers by specialty first, so a member's check for one specialty only looks at providers offering it.
Hint 2
Comparing every member against every provider of a specialty can be too slow. Bucket each specialty's providers into square grid cells whose side equals max_distance, so a nearby provider must lie in the member's own cell or one of the 8 neighbouring cells.
Hint 3
Handle max_distance == 0 separately: only an identical coordinate counts, so a hash lookup on the exact (x, y) point works. Compare squared distances against max_distance squared, and stop checking a member as soon as one specialty is unmet.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
For each member we must confirm that every required specialty has some provider within range. Checking every provider for every requirement is too slow on large inputs, so we organise providers spatially.
- Group by specialty. Build a map from specialty to that specialty's providers. A missing specialty means any member requiring it is underserved.
- Grid buckets. Within each specialty, place every provider into a square cell of side
max_distance, identified by(floor(x / d), floor(y / d)). - Query. For a member at
(x, y)and a specialty, find the member's cell and examine only that cell and its 8 neighbours. Any provider within distancedmust lie in one of these 9 cells, because a point at distance at mostddiffers by at mostdin each axis, so its cell index differs by at most 1. Within those cells, compare squared distance tod^2(inclusive). - Zero radius. If
max_distance == 0, cells are undefined. Only providers at exactly the member's point count, so we key the buckets by the exact(x, y)and do a hash lookup. - Early exit. As soon as one required specialty is unmet, record the member's ID and move on. Iterating members in order gives the required output order. Members with no requirements are never added.
Why it is correct
The 3x3 cell neighbourhood contains every provider that could be within range, and the exact squared-distance test rejects those that are not, so a specialty is judged covered exactly when some provider of it is within max_distance. A member is reported exactly when some requirement fails, which matches the definition.
Complexity
Let P be the number of providers, M the number of members and R the average number of requirements per member.
- Building the grids:
O(P)time and space. - Queries: each looks at 9 cells. When providers are spread out, a cell holds few points, so the total is about
O(M * R)on average. In the worst case, where many providers of one specialty are packed in a single cell, a query can scanO(P)points, givingO(M * R * P). - Space:
O(P).
Reference solution
import math
from collections import defaultdict
from typing import Dict, List
def find_underserved_members(providers: List[Dict], members: List[Dict], max_distance: float) -> List[int]:
radius = max_distance
radius_sq = radius * radius
# specialty -> cell -> list of provider points
grids = defaultdict(lambda: defaultdict(list))
if radius > 0:
for provider in providers:
x, y = provider["location"]
cell = (math.floor(x / radius), math.floor(y / radius))
grids[provider["specialty"]][cell].append((x, y))
else:
for provider in providers:
x, y = provider["location"]
grids[provider["specialty"]][(x, y)].append((x, y))
def has_provider(specialty, x, y):
grid = grids.get(specialty)
if not grid:
return False
if radius > 0:
cx, cy = math.floor(x / radius), math.floor(y / radius)
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
for px, py in grid.get((cx + dx, cy + dy), ()):
if (x - px) ** 2 + (y - py) ** 2 <= radius_sq:
return True
return False
return (x, y) in grid
underserved = []
for member in members:
x, y = member["location"]
for specialty in member["required_specialties"]:
if not has_provider(specialty, x, y):
underserved.append(member["id"])
break
return underserved