Process Morse Signals and Provider Coverage
Dynamic ProgrammingAuto-graded · 13 test casesLast updated
Evaluate string encoding, ambiguous Morse code decoding via dynamic programming, and spatial coverage checking for network members.
You are tasked with building an analytics processor that handles two separate utility functions in a single batch processing routine:
-
Morse Code Translation & Ambiguous Signal Parsing
- Encoding: Translate a plain text string (containing lowercase English letters
'a'through'z') into its concatenated International Morse Code signal (without spaces or separators). - Decoding: Given an unsegmented sequence of Morse symbols (
'.'and'-'), compute all possible valid plaintext word combinations of lowercase English letters that could yield this exact Morse pattern.
Standard International Morse mapping:
a:.-,b:-...,c:-.-.,d:-..,e:.,f:..-.,g:--.,h:....,i:..,j:.---,k:-.-,l:.-..,m:--,n:-..,o:---,p:.--.,q:--.-,r:.-.,s:...,t:-,u:..-,v:...-,w:.--,x:-..-,y:-.--,z:--..
- Encoding: Translate a plain text string (containing lowercase English letters
-
Healthcare Provider Network Access Analysis
- You are given a network configuration consisting of a list of service providers, a list of plan members, and a maximum allowed radial reach distance
max_distance. - Each provider is represented by a dictionary:
{"id": int, "specialty": str, "location": [x, y]}. - Each member is represented by a dictionary:
{"id": int, "location": [x, y], "required_specialties": [str, ...]}. - A member has adequate coverage if and only if, for every specialty listed in their
required_specialties, there exists at least one provider offering that specialty located within Euclidean distance $\le$max_distancefrom the member's coordinates. - Find all members who fail to achieve adequate coverage.
- You are given a network configuration consisting of a list of service providers, a list of plan members, and a maximum allowed radial reach distance
Return a dictionary with three key-value pairs:
"encoded": Astrrepresenting the Morse signal oftext."possible_texts": AList[str]containing all valid word decodings ofmorse, sorted in lexicographical order."inadequate_member_ids": AList[int]containing the IDs of all members with inadequate access, preserving the relative order in which they appear inmembers.
Constraints
textconsists only of lowercase English letters ('a'-'z').morseconsists only of characters'.'and'-'.- All
locationcoordinates are 2D pairs of numbers[x, y]. - Euclidean distance is measured as $\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}$. Distances $\le$
max_distanceare considered covered. - Duplicate entries or zero required specialties should be handled according to standard logic (a member with zero required specialties is adequately covered).
Examples
Example 1
Input: solve_morse_and_network_access('gin', '--...-.', [{'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: {'encoded': '--...-.', 'possible_texts': ['geae', 'geen', 'geete', 'ger', 'gf', 'gin', 'gite', 'gue', 'meeae', 'meeen', 'meeete', 'meer', 'mef', 'mein', 'meite', 'meue', 'miae', 'mien', 'miete', 'mir', 'msn', 'mste', 'mve', 'tbn', 'tbte', 'tdae', 'tden', 'tdete', 'tdr', 'tneae', 'tneen', 'tneete', 'tner', 'tnf', 'tnin', 'tnite', 'tnue', 'tteeae', 'tteeen', 'tteeete', 'tteer', 'ttef', 'ttein', 'tteite', 'tteue', 'ttiae', 'ttien', 'ttiete', 'ttir', 'ttsn', 'ttste', 'ttve', 'zae', 'zen', 'zete', 'zr'], 'inadequate_member_ids': [102]}
Hints
Hint 1
For Morse encoding, map each character in text to its standard representation and join them into a single string.
Hint 2
To decode the unsegmented Morse string, use dynamic programming or memoized recursion starting from the end of the string. At each index i, try matching every alphabet letter's code as a prefix of morse[i:].
Hint 3
To compute spatial distance safely without float precision issues, compare the squared Euclidean distance directly with max_distance * max_distance.
Hint 4
Group provider locations by specialty in a dictionary mapping specialty -> list of (x, y) coordinates for fast lookup during coverage verification.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Explanation
The task requires solving two sub-problems and returning the consolidated outputs in a dictionary:
-
Morse Encoding & Decoding:
- Encoding: Translate each character in
textusing a pre-defined Morse lookup table and concatenate them into a single string. - Decoding: We are given an unsegmented string of dots and dashes. Since multiple distinct character sequences can produce the exact same Morse code stream, this is similar to the classic Word Break II dynamic programming problem. We define dynamic programming array
decodings[i]as the list of all decoded word suffixes starting from positioniofmorse. We iterate backwards from index $N-1$ to $0$, checking which character's Morse symbol matchesmorse[i:]. For every valid match of length $L$, we append the character to each decoded suffix indecodings[i + L]. Finally, we sortdecodings[0]lexicographically.
- Encoding: Translate each character in
-
Network Coverage Evaluation:
- First, group all provider coordinate locations by their specialty using a hash table (
providers_by_spec). - For each member, iterate over their
required_specialties. - To avoid potential floating-point inaccuracies when calculating $\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}$, we compare the squared distance $(x_1 - x_2)^2 + (y_1 - y_2)^2$ against $\text{max_distance}^2$.
- If for any required specialty there is no provider within distance $\le \text{max_distance}$, the member is inadequate and their ID is collected.
- First, group all provider coordinate locations by their specialty using a hash table (
Complexity Analysis
- Encoding: $\mathcal{O}(|text|)$ time and space.
- Decoding: $\mathcal{O}(N \cdot K + S \log S)$ where $N = |morse|$, $K = 26$ alphabet codes, and $S$ is the number of valid generated decodings.
- Network Access: Grouping providers takes $\mathcal{O}(P)$ where $P$ is the number of providers. Checking coverage takes $\mathcal{O}(M \cdot R \cdot P_{spec})$ where $M$ is the number of members, $R$ is average required specialties per member, and $P_{spec}$ is the average number of providers per specialty.
Python Reference Solution
import math
from typing import Dict, List
MORSE_TABLE = {
'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.',
'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---',
'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---',
'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-',
'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--',
'z': '--..'
}
def solve_morse_and_network_access(text: str, morse: str, providers: List[Dict], members: List[Dict], max_distance: float) -> Dict:
# 1a. Encode text
encoded = ''.join(MORSE_TABLE[ch] for ch in text)
# 1b. Decode morse string into all possible valid plaintexts
n = len(morse)
decodings = [[] for _ in range(n + 1)]
decodings[n] = ['']
codes = sorted((code, letter) for letter, code in MORSE_TABLE.items())
for i in range(n - 1, -1, -1):
for code, letter in codes:
if morse.startswith(code, i):
end_idx = i + len(code)
decodings[i].extend(letter + suffix for suffix in decodings[end_idx])
possible_texts = sorted(decodings[0])
# 2. Check coverage for network members
providers_by_spec = {}
for p in providers:
spec = p['specialty']
loc = p['location']
if spec not in providers_by_spec:
providers_by_spec[spec] = []
providers_by_spec[spec].append(loc)
inadequate_ids = []
max_dist_sq = max_distance * max_distance
for member in members:
mx, my = member['location']
is_covered = True
for req_spec in member['required_specialties']:
locations = providers_by_spec.get(req_spec, [])
found_provider = False
for px, py in locations:
dist_sq = (mx - px) ** 2 + (my - py) ** 2
if dist_sq <= max_dist_sq:
found_provider = True
break
if not found_provider:
is_covered = False
break
if not is_covered:
inadequate_ids.append(member['id'])
return {
'encoded': encoded,
'possible_texts': possible_texts,
'inadequate_member_ids': inadequate_ids
}