Identify Clients Missing Nearby Specialty Care
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement find_uncovered_clients(clients, providers, distance) to audit regional specialty coverage across a 2D map:
def find_uncovered_clients(
clients: List[Dict],
providers: List[Dict],
distance: float,
) -> List[int]:
Each entry in clients and providers is a dictionary with three keys:
- 'id': an integer record identifier,
- 'coords': a 2D integer point (x, y) (given as a 2-tuple or 2-element list),
- 'specialties': a collection (such as a set or list) of specialty name strings—for a client, the specialties needed; for a provider, the specialties offered at that clinic.
Straight-line separation between (x1, y1) and (x2, y2) is measured with standard 2D Euclidean geometry: sqrt((x1 - x2)^2 + (y1 - y2)^2). A single specialty need for a client counts as satisfied whenever at least one provider offering that specialty sits at Euclidean distance at most distance (<= distance) from the client's coordinates. Distinct specialties needed by the same client may be fulfilled by separate providers, and a client with an empty 'specialties' collection automatically has all needs met.
Return the 'id' values of every client who lacks in-range coverage for one or more needed specialties, keeping those IDs in the exact sequence they appear in clients (with each uncovered client listed at most once).
Examples
Example 1
Input:
clients = [
{"id": 101, "coords": (2, 1), "specialties": {"Ortho", "Neuro"}},
{"id": 102, "coords": (10, 10), "specialties": {"Pediatrics"}}
]
providers = [
{"id": 50, "coords": (4, 2), "specialties": {"Ortho"}},
{"id": 51, "coords": (13, 14), "specialties": {"Pediatrics", "Neuro"}}
]
distance = 5.0
Output:
[101]
Explanation:
- Client 101 at (2, 1) reaches "Ortho" via provider 50 at (4, 2) (sqrt(2^2 + 1^2) = sqrt(5) ≈ 2.24 <= 5.0), whereas the sole "Neuro" clinic at (13, 14) sits sqrt(11^2 + 13^2) = sqrt(290) ≈ 17.03 > 5.0 away. Because "Neuro" is unmet, 101 is included.
- Client 102 at (10, 10) reaches "Pediatrics" via provider 51 at (13, 14) right on the boundary (sqrt(3^2 + 4^2) = 5.0 <= 5.0), so 102 is fully covered.
Example 2
Input:
clients = [
{"id": 7, "coords": (-1, 0), "specialties": {"Oncology", "Radiology"}}
]
providers = [
{"id": 20, "coords": (-3, 1), "specialties": {"Oncology"}},
{"id": 21, "coords": (1, -1), "specialties": {"Radiology"}}
]
distance = 3.0
Output:
[]
Explanation: Client 7 is sqrt(5) ≈ 2.24 <= 3.0 units from provider 20 ("Oncology") and sqrt(5) ≈ 2.24 <= 3.0 units from provider 21 ("Radiology"). Separate nearby clinics satisfy both requirements, leaving zero uncovered clients.
Constraints
0 <= len(clients), len(providers) <= 10,000.- Every coordinate component
xandyis an integer in[-10,000, 10,000]. - Specialty identifiers are strings;
distanceis a floating-point value (whendistance < 0, no provider is in range). - The solution should avoid quadratic all-pairs scans on typical spatial distributions.
Step-by-step walkthrough
Understand the problem and coverage rules
We receive a list of
clients, a list ofproviders, and a maximum straight-line radiusdistance. Every client and provider dictionary carries:'id': an integer identifier,'coords': a 2D coordinate pair(x, y)(passed as a tuple or a two-item list),'specialties': a collection of specialty names such as'Ortho'or'Neuro'.
A client is fully covered when every specialty in
client['specialties']is offered by at least one provider whose Euclidean distancesqrt((px - cx)^2 + (py - cy)^2)is at mostdistance(<=). Different specialties can be satisfied by different providers.We must return the IDs of all uncovered clients — those missing one or more required specialties within range — preserving the exact order in which those clients appeared in
clients. Notice that a client whosespecialtiescollection is empty has zero unmet needs, so they are automatically covered.Why checking every provider for every client is too slow
The most direct approach is a triple loop: for each client, check each required specialty by scanning the entire
providerslist from start to finish.With up to
10,000clients and10,000providers, scanning every provider for every client can perform10,000 * 10,000 = 100,000,000distance checks. In Python, a hundred million loop iterations takes several seconds. Almost all of that work is wasted measuring distances to providers on the far side of the map who could never sit withindistanceanyway.Key idea: divide the map into square grid cells
Suppose
distance = 5.0, and we draw a checkerboard of5 x 5square cells over the 2D plane. Every point(x, y)lands in cell(x // cell_size, y // cell_size), wherecell_size >= distance.Now ask: if a client
Csits inside cell(cx_cell, cy_cell), which cells could possibly contain a provider withindistanceofC?col - 1 col col + 1 +----------+----------+----------+ | (-1, +1) | ( 0, +1) | (+1, +1) | row + 1 +----------+----------+----------+ | (-1, 0) | C here | (+1, 0) | row <-- cell_size >= distance, so a circle of | | (0, 0) | | radius `distance` around C can NEVER +----------+----------+----------+ reach two full cells away! | (-1, -1) | ( 0, -1) | (+1, -1) | row - 1 +----------+----------+----------+Because each square is at least
distancewide and tall, moving at mostdistanceunits horizontally or vertically shifts a point by at most one cell inxand at most one cell iny. That guarantees every in-range provider lives in either the client's own cell or one of its 8 immediate neighbors (a3 x 3block of 9 cells).Two practical details make this rock-solid in Python:
- Choose
cell_size = max(1, math.ceil(distance)):math.ceil(distance)rounds fractional radii like2.3up to3socell_size >= distancealways holds, andmax(1, ...)prevents division by zero whendistance == 0. - Negative coordinates work automatically: Python's floor-division operator
//always rounds toward-infinity, so-1 // 3 == -1and1 // 3 == 0sit right next to each other as adjacent cells.
- Choose
Phase 1: Put providers into `(specialty, cell_x, cell_y)` buckets
If we also include the
specialtyname in the dictionary key —(specialty, cell_x, cell_y)— then asking "is there a'Neuro'clinic near clientC?" never wastes time inspecting'Ortho'or'Pediatrics'providers in those cells.Inside each bucket we store a
setof(px, py)integer tuples. Using asetdoes two helpful things: it collapses multiple doctors sharing the exact same clinic address into a single coordinate check, and unpackingpx, py = provider["coords"]safely turns list coordinates like[4, 2]into hashable tuples.from typing import Any, Dict, List, Optional, Set, Tuple import math def _build_specialty_grid( providers: List[Dict], cell_size: int ) -> Dict[Tuple[str, int, int], Set[Tuple[int, int]]]: """Group unique provider coordinates into (specialty, cell_x, cell_y) grid buckets.""" # buckets: maps (specialty, cell_x, cell_y) -> set of (px, py) int tuples. # Using a set deduplicates multiple providers offering the same specialty at one address. buckets: Dict[Tuple[str, int, int], Set[Tuple[int, int]]] = {} for provider in providers: px, py = provider["coords"] cell_x = px // cell_size cell_y = py // cell_size for specialty in provider["specialties"]: key = (specialty, cell_x, cell_y) if key not in buckets: buckets[key] = set() buckets[key].add((px, py)) return bucketsPhase 2: Check the 3x3 neighborhood for one specialty
To test whether one
(client, specialty)pair is covered, we find the client's cell(cx // cell_size, cy // cell_size)and loopoffset_xandoffset_yover(-1, 0, 1)to visit all 9 candidate cells.For each provider coordinate
(px, py)in those buckets, we checkmath.hypot(px - cx, py - cy) <= distanceand returnTruethe moment we find one match. Usingmath.hypotcomputessqrt((px - cx)^2 + (py - cy)^2)accurately and avoids subtle floating-point rounding bugs thatdistance * distancecan hit whendistanceitself is an inexact float such asmath.sqrt(26).def _is_specialty_covered( buckets: Dict[Tuple[str, int, int], Set[Tuple[int, int]]], specialty: str, cx: int, cy: int, cell_size: int, distance: float, ) -> bool: """Return True if at least one provider for `specialty` lies within `distance` of (cx, cy).""" client_cell_x = cx // cell_size client_cell_y = cy // cell_size # Because cell_size >= distance, any provider within `distance` on both axes # must sit in the client's own grid cell or one of its 8 immediate neighbors. for offset_x in (-1, 0, 1): for offset_y in (-1, 0, 1): neighbor_key = (specialty, client_cell_x + offset_x, client_cell_y + offset_y) for px, py in buckets.get(neighbor_key, ()): # Use <= because coverage includes providers exactly `distance` away. # math.hypot computes exact Euclidean sqrt((px - cx)^2 + (py - cy)^2) # without rounding errors when `distance` itself is a float like sqrt(26). if math.hypot(px - cx, py - cy) <= distance: return True return FalsePhase 3: Scan clients in order and trace Example 1
Before building the grid, we guard against
distance < 0: Euclidean distance is never negative, so any client who needs at least one specialty is immediately uncovered.Otherwise, we build
bucketsonce and walkclientsin input order. As soon as a client is missing one specialty, we appendclient["id"]andbreakout of the inner specialty loop so that a client missing two or three specialties is still recorded only once.Let's trace Example 1 (
distance = 5.0, socell_size = 5):Provider 50 at (4, 2), specialties={'Ortho'}: cell = (4 // 5, 2 // 5) = (0, 0) Provider 51 at (13, 14), specialties={'Pediatrics', 'Neuro'}: cell = (13 // 5, 14 // 5) = (2, 2) buckets = { ('Ortho', 0, 0): {(4, 2)}, ('Pediatrics', 2, 2): {(13, 14)}, ('Neuro', 2, 2): {(13, 14)}, } Client 101 at (2, 1), specialties={'Ortho', 'Neuro'}: client cell = (2 // 5, 1 // 5) = (0, 0), checks 3x3 cells (-1..1, -1..1) 1. Check 'Ortho': bucket ('Ortho', 0, 0) has (4, 2) -> hypot(2, 1) = 2.236 <= 5.0 (covered!) 2. Check 'Neuro': all 9 ('Neuro', -1..1, -1..1) buckets are empty (cell (2, 2) is outside!) -> NOT covered! Append client ID 101 and break. Client 102 at (10, 10), specialties={'Pediatrics'}: client cell = (10 // 5, 10 // 5) = (2, 2), checks 3x3 cells (1..3, 1..3) 1. Check 'Pediatrics': bucket ('Pediatrics', 2, 2) has (13, 14) -> hypot(3, 4) = 5.0 <= 5.0 (covered!) Output: [101]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import math def _build_specialty_grid( providers: List[Dict], cell_size: int ) -> Dict[Tuple[str, int, int], Set[Tuple[int, int]]]: """Group unique provider coordinates into (specialty, cell_x, cell_y) grid buckets.""" # buckets: maps (specialty, cell_x, cell_y) -> set of (px, py) int tuples. # Using a set deduplicates multiple providers offering the same specialty at one address. buckets: Dict[Tuple[str, int, int], Set[Tuple[int, int]]] = {} for provider in providers: px, py = provider["coords"] cell_x = px // cell_size cell_y = py // cell_size for specialty in provider["specialties"]: key = (specialty, cell_x, cell_y) if key not in buckets: buckets[key] = set() buckets[key].add((px, py)) return buckets def _is_specialty_covered( buckets: Dict[Tuple[str, int, int], Set[Tuple[int, int]]], specialty: str, cx: int, cy: int, cell_size: int, distance: float, ) -> bool: """Return True if at least one provider for `specialty` lies within `distance` of (cx, cy).""" client_cell_x = cx // cell_size client_cell_y = cy // cell_size # Because cell_size >= distance, any provider within `distance` on both axes # must sit in the client's own grid cell or one of its 8 immediate neighbors. for offset_x in (-1, 0, 1): for offset_y in (-1, 0, 1): neighbor_key = (specialty, client_cell_x + offset_x, client_cell_y + offset_y) for px, py in buckets.get(neighbor_key, ()): # Use <= because coverage includes providers exactly `distance` away. # math.hypot computes exact Euclidean sqrt((px - cx)^2 + (py - cy)^2) # without rounding errors when `distance` itself is a float like sqrt(26). if math.hypot(px - cx, py - cy) <= distance: return True return False def find_uncovered_clients( clients: List[Dict], providers: List[Dict], distance: float ) -> List[int]: # Phase 1: Guard against negative thresholds. Euclidean distance is always >= 0, # so any client who requires at least one specialty cannot be covered. if distance < 0: uncovered = [] for client in clients: if client["specialties"]: uncovered.append(client["id"]) return uncovered # Phase 2: Index providers in square cells at least `distance` wide. # max(1, ...) prevents division by zero when distance == 0. cell_size = max(1, math.ceil(distance)) buckets = _build_specialty_grid(providers, cell_size) # Phase 3: Check clients in their original list order and record any client # missing at least one required specialty. uncovered = [] for client in clients: cx, cy = client["coords"] for specialty in client["specialties"]: if not _is_specialty_covered(buckets, specialty, cx, cy, cell_size, distance): uncovered.append(client["id"]) # Stop checking further specialties so this client ID is added only once. break return uncovered✅ Submit now — all tests should pass.
Intuition & how it works
Imagine checking whether you have both an orthopedist and a neurologist within 5 miles of your home using a city map ruled into 5-mile-by-5-mile squares. Instead of measuring the distance from your house to every clinic across the entire state, you locate the square containing your home and look only inside that square and the 8 squares touching it. That technique is spatial hashing (grid bucketing) — dividing 2D space into fixed-size square cells with integer floor division (x // cell_size) so nearby points automatically land in the same or adjacent dictionary buckets. Within those 9 squares, we check straight-line Euclidean distance — the ordinary ruler distance sqrt((x1 - x2)^2 + (y1 - y2)^2) between two points.
Why does the naive approach fall short? Checking every provider against every client requires C * P distance calculations, which reaches 10,000 * 10,000 = 100,000,000 checks at the maximum input size. Nearly all of those checks measure distances to clinics miles outside the radius or offering completely unrelated specialties. By keying our grid buckets as (specialty, cell_x, cell_y) with cell_size = max(1, ceil(distance)), each specialty lookup inspects only matching providers inside a 3 x 3 neighborhood and stops at the very first clinic in range.
Let's trace Example 1 (distance = 5.0, cell_size = 5) across two clients and two providers:
Providers:
P50 at (4, 2) offering {'Ortho'} -> cell (4 // 5, 2 // 5) = (0, 0)
P51 at (13, 14) offering {'Pediatrics','Neuro'} -> cell (13 // 5, 14 // 5) = (2, 2)
Clients:
C101 at (2, 1) needing {'Ortho', 'Neuro'} (cell (0, 0), checks cells -1..1 x -1..1):
- 'Ortho': found (4, 2) in ('Ortho', 0, 0), distance = sqrt(5) ≈ 2.24 <= 5.0 -> covered
- 'Neuro': ('Neuro', 2, 2) lies outside the 3x3 neighborhood -> NOT covered -> record ID 101
C102 at (10, 10) needing {'Pediatrics'} (cell (2, 2), checks cells 1..3 x 1..3):
- 'Pediatrics': found (13, 14) in ('Pediatrics', 2, 2), distance = 5.0 <= 5.0 -> covered
Result: [101]
Complexity
Let C be the number of clients, P be the number of providers, and S be the average number of specialties per client or provider.
- Time:
O((P + C * k) * S)on average,O((P + C * P) * S)in the worst case, wherekis the number of unique provider coordinates for a given specialty inside the3 x 3cells around a client. Building the grid scans allPproviders once and inserts each(provider, specialty)pair into a hash-table bucket inO(1)average time (O(P * S)total). Each(client, specialty)query checks9dictionary keys inO(1)time each and scans only thekunique locations stored there, stopping early as soon as one sits withindistance; when points are spread out,kis tiny, while in the adversarial worst case (many distinct provider coordinates packed into the3 x 3block just outside the circle of radiusdistance),kcan be up toP. - Space:
O(P * S + C). Each provider coordinate is stored once per specialty it offers inbuckets(O(P * S)), and the output listuncoveredholds at mostCclient IDs.
Edge cases
- Provider right on the boundary (
distanceaway): Provider51at(13, 14)sits5.0units from(10, 10)and covers client102whendistance = 5.0because coverage uses<=, not<. - Specialties satisfied by different providers: As in Example 2, a client needing
{'Oncology', 'Radiology'}is covered when one nearby clinic offers'Oncology'and another nearby clinic offers'Radiology'. - Client with empty
specialties: The inner loop overclient["specialties"]runs zero times, so the client is treated as covered and never added touncovered. - Empty
providerslist: All buckets are empty, so every client requiring at least one specialty is returned in input order. distance == 0:cell_size = max(1, math.ceil(0)) = 1avoids dividing by zero, andmath.hypot(px - cx, py - cy) <= 0accepts only providers at the client's exact(cx, cy)point.- Negative coordinates: Python's floor division
//rounds consistently toward-infinity(-1 // 3 == -1and1 // 3 == 0), keeping points across the axes in adjacent cells. - Negative
distance: Handled up front — since straight-line distances are never negative, every client with non-emptyspecialtiesis uncovered. - Multiple missing specialties or duplicate clinic addresses:
breakensures each uncovered client ID appears at most once, and storing asetper bucket deduplicates doctors sharing the exact same building coordinates.
Common mistakes
- Requiring a single provider to offer all of a client's specialties: Coverage is evaluated specialty by specialty; different doctors can satisfy different needs.
- Using
<instead of<=for the distance check: Coverage includes clinics at distance<= distance, so points right on the circle boundary must count. - Picking
cell_size < distancewhile only checking a3 x 3neighborhood: Ifcell_sizeis smaller thandistance(for example,int(distance)truncating2.8down to2), a provider2.5units away can sit two cells over and be missed. Always round up withmath.ceil(distance). - Dividing by
cell_size = 0whendistance == 0: Wrapping withmax(1, math.ceil(distance))keeps cell coordinates valid for zero radius. - Returning a
setor sorting client IDs: The output must preserve the entry order ofclients. - Comparing
dx*dx + dy*dy <= distance*distancewithout care: Squaring a negativedistanceturns-2into radius+2, and for inexact floats likedistance = math.sqrt(26)(5.0990195135927845),distance * distancerounds to25.999999999999996 < 26and wrongly rejects a provider at(1, 5). Usingmath.hypotwith an upfrontdistance < 0check avoids both traps. - Adding raw
provider["coords"]directly to aset: Inputs may pass coordinates as a Pythonlist([4, 2]), which is unhashable; unpackingpx, py = provider["coords"]and storing(px, py)always creates a hashable tuple.
Alternative approaches
- Push coverage from providers onto bucketed clients: Put clients into grid cells, iterate over providers, and mark each nearby client's specialties as satisfied. This avoids re-querying dense provider clusters when clients are sparse, though it cannot stop early once a client is already covered.
- Sort providers by
xand binary search: For each specialty, sort provider coordinates byxand use binary search to scan only the vertical strip[cx - distance, cx + distance]. It needsO(log P)to find the strip, but can still scan many providers that are close inxyet far away iny. - Build a k-d tree per specialty: A k-d tree is a binary search tree that recursively splits 2D points along alternating
xandylines so nearest-neighbor lookups run inO(log P)time on typical point distributions, regardless ofdistance. Unlike grid buckets, it adapts well to wildly uneven point densities, though Python's standard library does not include one built in.
Follow-up questions
- How would you scale the coverage check if both clients and providers grew to one million records? First, deduplicate identical queries by grouping clients who share the same
(coords, specialty)check, and tune the spatial index (or use a k-d tree / R-tree, a balanced tree of nested bounding rectangles built into spatial databases like PostGIS) so uneven urban vs. rural densities do not create huge single buckets. Beyond one machine, partition the map into geographic shards and replicate providers withindistanceof each shard boundary (a "halo" region) so every worker machine can evaluate its assigned clients independently in parallel. With real-world latitude and longitude, replace flat Euclidean distance with haversine distance (great-circle distance over the curved Earth) and index points using geohash or H3 hexagonal cells. - Which data structures would support fast incremental updates when clinics add or drop specialties dynamically? Maintain a lookup table
provider_id -> (coords, current_specialties)and store each grid bucket(specialty, cell_x, cell_y)as a reference count dictionary{(px, py): doctor_count}(or a set ofprovider_ids). When a clinic adds or drops a specialty, you only touch the single(specialty, cell_x, cell_y)bucket for its fixed location inO(1)time per changed specialty instead of rebuilding the entire index. If uncovered-client lists must also update live, index clients in a grid as well and keep acovering_provider_countper(client_id, specialty), flagging a client whenever any count drops to0. - How would the asymptotic runtime and memory usage change if the output had to list every missing specialty per uncovered client? Asymptotically, the worst-case time complexity stays the same (
O((P + C * P) * S)), because covered clients already had to check allSof their specialties anyway. The only extra work happens on uncovered clients, where we remove the earlybreakand finish checking their remaining specialties instead of stopping at the first gap. Output space increases fromO(C)client IDs toO(C * S)(client_id, missing_specialties)pairs.
Follow-up questions
- How would you scale the coverage check if both clients and providers grew to one million records?
- Which data structures would support fast incremental updates when clinics add or drop specialties dynamically?
- How would the asymptotic runtime and memory usage change if the output had to list every missing specialty per uncovered client?
Similar questions
- Morse Code Translation and Provider Proximity
- Automated Patient Outreach Sequence Service
- State-Licensed Virtual Care Queue
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses