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 x and y is an integer in [-10,000, 10,000].
  • Specialty identifiers are strings; distance is a floating-point value (when distance < 0, no provider is in range).
  • The solution should avoid quadratic all-pairs scans on typical spatial distributions.

Step-by-step walkthrough

  1. Understand the problem and coverage rules

    We receive a list of clients, a list of providers, and a maximum straight-line radius distance. 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 distance sqrt((px - cx)^2 + (py - cy)^2) is at most distance (<=). 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 whose specialties collection is empty has zero unmet needs, so they are automatically covered.

  2. 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 providers list from start to finish.

    With up to 10,000 clients and 10,000 providers, scanning every provider for every client can perform 10,000 * 10,000 = 100,000,000 distance 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 within distance anyway.

  3. Key idea: divide the map into square grid cells

    Suppose distance = 5.0, and we draw a checkerboard of 5 x 5 square cells over the 2D plane. Every point (x, y) lands in cell (x // cell_size, y // cell_size), where cell_size >= distance.

    Now ask: if a client C sits inside cell (cx_cell, cy_cell), which cells could possibly contain a provider within distance of C?

        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 distance wide and tall, moving at most distance units horizontally or vertically shifts a point by at most one cell in x and at most one cell in y. That guarantees every in-range provider lives in either the client's own cell or one of its 8 immediate neighbors (a 3 x 3 block 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 like 2.3 up to 3 so cell_size >= distance always holds, and max(1, ...) prevents division by zero when distance == 0.
    • Negative coordinates work automatically: Python's floor-division operator // always rounds toward -infinity, so -1 // 3 == -1 and 1 // 3 == 0 sit right next to each other as adjacent cells.
  4. Phase 1: Put providers into `(specialty, cell_x, cell_y)` buckets

    If we also include the specialty name in the dictionary key — (specialty, cell_x, cell_y) — then asking "is there a 'Neuro' clinic near client C?" never wastes time inspecting 'Ortho' or 'Pediatrics' providers in those cells.

    Inside each bucket we store a set of (px, py) integer tuples. Using a set does two helpful things: it collapses multiple doctors sharing the exact same clinic address into a single coordinate check, and unpacking px, 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 buckets
    
  5. Phase 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 loop offset_x and offset_y over (-1, 0, 1) to visit all 9 candidate cells.

    For each provider coordinate (px, py) in those buckets, we check math.hypot(px - cx, py - cy) <= distance and return True the moment we find one match. Using math.hypot computes sqrt((px - cx)^2 + (py - cy)^2) accurately and avoids subtle floating-point rounding bugs that distance * distance can hit when distance itself is an inexact float such as math.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 False
    
  6. Phase 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 buckets once and walk clients in input order. As soon as a client is missing one specialty, we append client["id"] and break out 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, so cell_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]
    
  7. 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, where k is the number of unique provider coordinates for a given specialty inside the 3 x 3 cells around a client. Building the grid scans all P providers once and inserts each (provider, specialty) pair into a hash-table bucket in O(1) average time (O(P * S) total). Each (client, specialty) query checks 9 dictionary keys in O(1) time each and scans only the k unique locations stored there, stopping early as soon as one sits within distance; when points are spread out, k is tiny, while in the adversarial worst case (many distinct provider coordinates packed into the 3 x 3 block just outside the circle of radius distance), k can be up to P.
  • Space: O(P * S + C). Each provider coordinate is stored once per specialty it offers in buckets (O(P * S)), and the output list uncovered holds at most C client IDs.

Edge cases

  • Provider right on the boundary (distance away): Provider 51 at (13, 14) sits 5.0 units from (10, 10) and covers client 102 when distance = 5.0 because 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 over client["specialties"] runs zero times, so the client is treated as covered and never added to uncovered.
  • Empty providers list: 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)) = 1 avoids dividing by zero, and math.hypot(px - cx, py - cy) <= 0 accepts only providers at the client's exact (cx, cy) point.
  • Negative coordinates: Python's floor division // rounds consistently toward -infinity (-1 // 3 == -1 and 1 // 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-empty specialties is uncovered.
  • Multiple missing specialties or duplicate clinic addresses: break ensures each uncovered client ID appears at most once, and storing a set per 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 < distance while only checking a 3 x 3 neighborhood: If cell_size is smaller than distance (for example, int(distance) truncating 2.8 down to 2), a provider 2.5 units away can sit two cells over and be missed. Always round up with math.ceil(distance).
  • Dividing by cell_size = 0 when distance == 0: Wrapping with max(1, math.ceil(distance)) keeps cell coordinates valid for zero radius.
  • Returning a set or sorting client IDs: The output must preserve the entry order of clients.
  • Comparing dx*dx + dy*dy <= distance*distance without care: Squaring a negative distance turns -2 into radius +2, and for inexact floats like distance = math.sqrt(26) (5.0990195135927845), distance * distance rounds to 25.999999999999996 < 26 and wrongly rejects a provider at (1, 5). Using math.hypot with an upfront distance < 0 check avoids both traps.
  • Adding raw provider["coords"] directly to a set: Inputs may pass coordinates as a Python list ([4, 2]), which is unhashable; unpacking px, 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 x and binary search: For each specialty, sort provider coordinates by x and use binary search to scan only the vertical strip [cx - distance, cx + distance]. It needs O(log P) to find the strip, but can still scan many providers that are close in x yet far away in y.
  • Build a k-d tree per specialty: A k-d tree is a binary search tree that recursively splits 2D points along alternating x and y lines so nearest-neighbor lookups run in O(log P) time on typical point distributions, regardless of distance. 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 within distance of 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 of provider_ids). When a clinic adds or drops a specialty, you only touch the single (specialty, cell_x, cell_y) bucket for its fixed location in O(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 a covering_provider_count per (client_id, specialty), flagging a client whenever any count drops to 0.
  • 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 all S of their specialties anyway. The only extra work happens on uncovered clients, where we remove the early break and finish checking their remaining specialties instead of stopping at the first gap. Output space increases from O(C) client IDs to O(C * S) (client_id, missing_specialties) pairs.

Follow-up questions

Similar questions

More Oscar interview questions

All 4 Oscar questions →