Decode Delimited and Ambiguous Morse Strings
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given a lookup dictionary morse_to_letter mapping Morse code strings (composed of characters such as '.' and '-') to lowercase English letters, implement decode_morse_messages(morse_to_letter, encoded, char_sep, word_sep) to translate an encoded message under two operating modes:
-
Delimited letter mode (
char_sep != ""):- Split
encodedinto encoded words usingword_sepfirst (ifword_sep == "", treat the entireencodedstring as a single encoded word). - Split each non-empty encoded word on
char_sepinto symbol tokens, translate each token viamorse_to_letter, concatenate the letters of each word, and join decoded words with a single space" ". - Return a single-element list
[sentence]if every word is non-empty and every token appears inmorse_to_letter; otherwise return[].
- Split
-
Ambiguous unsegmented letter mode (
char_sep == ""):- Split
encodedinto encoded words usingword_sep(again treatingencodedas one word whenword_sep == ""), where letters within each word have no separator between them. - For each encoded word, find all valid ways to partition the entire word into contiguous non-empty substrings present in
morse_to_letterand translate each partition into a decoded word. - Combine valid decoded words across all word positions (joining adjacent words with
" ") and return all unique resulting sentences sorted in ascending alphabetical order. If any encoded word is empty or has zero valid partitions, return[].
- Split
Examples
Example 1
Input:
morse_to_letter = {".-": "a", "-..": "d", ".": "e", "--": "m", "-": "t"}
encoded = "-- .|.- -"
char_sep = " "
word_sep = "|"
Output:
["me at"]
Explanation: char_sep is " ", so letter boundaries are explicit. Splitting on "|" produces two encoded words "-- ." and ".- -". Splitting each on " " yields ["--", "."] ("me") and [".-", "-"] ("at"), which join with " " to give ["me at"].
Example 2
Input:
morse_to_letter = {".-": "a", ".": "e", "--": "m", "-": "t"}
encoded = ".-|--"
char_sep = ""
word_sep = "|"
Output:
["a m", "a tt", "et m", "et tt"]
Explanation: char_sep is "", so each "|"-delimited word is partitioned in all valid ways:
- Word 1 (".-"): ".-" -> "a", or "." + "-" -> "et".
- Word 2 ("--"): "--" -> "m", or "-" + "-" -> "tt".
Pairing every decoding of word 1 with every decoding of word 2 in alphabetical order produces ["a m", "a tt", "et m", "et tt"].
Example 3
Input:
morse_to_letter = {".-": "a", "--": "m", ".": "e"}
encoded = ".-|-- -"
char_sep = ""
word_sep = "|"
Output:
[]
Explanation: Splitting on "|" produces ".-" and "-- -". Because char_sep == "", every character of "-- -" must belong to a pattern in morse_to_letter, yet neither ' ' nor a single '-' is in morse_to_letter. Since the second word has no valid partition, the entire message returns [].
Constraints
1 <= len(morse_to_letter) <= 26, mapping non-empty pattern strings to single lowercase letters'a'–'z'.0 <= len(encoded) <= 100- Always split on
word_sepbeforechar_sep(so cases likechar_sep = " "andword_sep = " "preserve word boundaries). - Decoded words in every returned sentence are separated by
" ", with unique sentences ordered lexicographically.
Step-by-step walkthrough
Restate the two modes and output rules
We are given a dictionary
morse_to_letter(such as{".-": "a", ".": "e", "--": "m", "-": "t"}), anencodedstring, a character delimiterchar_sep, and a word delimiterword_sep. One functiondecode_morse_messageshandles both operating modes:- Mode 1 (
char_sep != ""): Letters inside each word are separated bychar_sep, and words are separated byword_sep. Every letter boundary is explicit, so at most one valid sentence exists (in Example 1,"-- .|.- -"withchar_sep = " "andword_sep = "|"returns["me at"]). - Mode 2 (
char_sep == ""): Onlyword_sepseparates words; letters inside each word are concatenated directly. Because".-"could be"a"(".-") or"et"("."+"-"), we enumerate all valid decoded sentences (Example 2 returns["a m", "a tt", "et m", "et tt"]).
Verify the exact boundary rules so edge cases stay rock-solid: - Output words are always joined with a single space
" ", regardless ofword_sep(Examples 1 and 2). - If no valid decoding exists, return[]. - Every character of an unsegmented word must be covered by valid patterns inmorse_to_letter. In Example 3 (".-|-- -"withchar_sep = ""andword_sep = "|"), neither' 'nor a lone'-'exists in{".-": "a", "--": "m", ".": "e"}, so word 2 fails and the call returns[]. - Empty words (fromencoded == ""or consecutive/trailing word delimiters like".-|") have no letters and return[].- Mode 1 (
Split words before splitting letters
Always split
encodedonword_sepfirst, before touchingchar_sep. Why? In standard Morse conventions, letters are separated by one space (char_sep = " ") and words by three spaces (word_sep = " "):encoded = ".... .. - .... . .-. ." Correct (word_sep " " first): words -> [".... ..", "- .... . .-. ."] letters -> [["....", ".."], ["-", "....", ".", ".-.", "."]] -> "hi there" Wrong (char_sep " " first): pieces -> ["....", "..", "", "", "-", ...] (word boundary shattered into ""!)We also guard against
word_sep == "", because Python'sstr.split("")raises aValueError— an emptyword_sepsimply means the whole string is a single encoded word.from typing import Dict, List, Optional, Set def split_words(encoded: str, word_sep: str) -> List[str]: # Python's str.split("") raises ValueError; empty word_sep means a single word. if word_sep == "": return [encoded] return encoded.split(word_sep)Mode 1: deterministic lookup when char_sep is given
When
char_sepis non-empty, each word splits cleanly into candidate patterns. We look up every pattern inmorse_to_letter; if any word is empty or any pattern is missing from the dictionary, we immediately returnNone(whichdecode_morse_messagesconverts into[]).from typing import Dict, List, Optional def decode_with_separators( morse_to_letter: Dict[str, str], encoded_words: List[str], char_sep: str, ) -> Optional[str]: # decoded_words: list of decoded word strings, e.g. ["me", "at"] decoded_words = [] for encoded_word in encoded_words: if not encoded_word: return None letters = [] for pattern in encoded_word.split(char_sep): if pattern not in morse_to_letter: return None letters.append(morse_to_letter[pattern]) decoded_words.append("".join(letters)) return " ".join(decoded_words)Mode 2 naive search, and the dead-end trap
When
char_sep == "", words do not interact with each other: we can find all valid decodings for each word independently, then combine them at the end. So the core subproblem is decoding one unsegmented word of lengthL.A word of length
LhasL - 1internal cut points, giving2^(L - 1)ways to slice it. Even if we use backtracking (stepping forward left-to-right whenever a prefix matchesmorse_to_letter, and undoing our last step when stuck), we can fall into an exponential dead-end trap:Dictionary: {".": "e", "..": "i"} (note: "-" is NOT in the dictionary!) Word: "............................................................-" |<---------------- 60 dots: > 10^12 ways! ---------------->|X| fails!Plain left-to-right backtracking explores over a trillion ways to slice the
60dots into"."and".."before discovering — at the end of every single branch — that the trailing"-"cannot be decoded!Key idea: precompute suffix reachability from right to left
We eliminate dead ends completely with a tiny right-to-left dynamic programming pass (solving smaller suffixes from the end of the word back toward index
0). Definecan_finish[i]asTrueifencoded_word[i:]can be completely partitioned into valid patterns:- Base case:
can_finish[word_len] = True(the empty suffix at the end needs zero patterns). - Step for index
i: try pattern lengths1up tomax_pattern_len(at most4in standard Morse). Ifencoded_word[i : i + length]is inmorse_to_letterandcan_finish[i + length]isTrue, setcan_finish[i] = True.
Compare a valid word against Example 3's failing word
"-- -":Valid word: "..-" with {"..": "i", ".-": "a", "-": "t", ".": "e"} index: 0 1 2 3 char: . . - (end) can_finish: [ T, T, T, T ] <-- can_finish[0] is True: safe to decode! Failing word (Example 3): "-- -" with {".-": "a", "--": "m", ".": "e"} index: 0 1 2 3 4 char: - - ' ' - (end) can_finish: [ F, F, F, F, T ] <-- can_finish[0] is False: return [] in O(L)!- Base case:
Pruned backtracking for a single word
Once
can_finishis built, we backtrack from index0, only stepping tonext_indexwhencan_finish[next_index]isTrue. Because every allowed step is guaranteed to have a valid completion to the end of the word, zero recursive calls are ever wasted!Decision tree for "..-" with {"..": "i", ".-": "a", "-": "t", ".": "e"}: index 0 ("..-") +-- take "." ("e") -> index 1 (".-") | +-- take "." ("e") -> index 2 ("-") | | +-- take "-" ("t") -> index 3 (end) ==> "eet" | +-- take ".-" ("a") -> index 3 (end) ==> "ea" +-- take ".." ("i") -> index 2 ("-") +-- take "-" ("t") -> index 3 (end) ==> "it"We collect completed words in a
set(unique_words) so that even if a custom table maps two different patterns to the same letter, duplicate strings are automatically merged.from typing import Dict, List, Set def all_letter_sequences( morse_to_letter: Dict[str, str], encoded_word: str, ) -> List[str]: word_len = len(encoded_word) if word_len == 0: return [] # max_pattern_len caps how far ahead we slice from any index i (4 for standard Morse). max_pattern_len = 0 for pattern in morse_to_letter: if len(pattern) > max_pattern_len: max_pattern_len = len(pattern) # Phase 1 — Right-to-left reachability DP: # can_finish: bool list of length word_len + 1 where can_finish[i] is True # iff encoded_word[i:] can be completely partitioned into known Morse patterns. can_finish = [False] * (word_len + 1) can_finish[word_len] = True for i in range(word_len - 1, -1, -1): max_step = min(max_pattern_len, word_len - i) # Start length at 1 so an empty "" key in morse_to_letter can never loop in place. for length in range(1, max_step + 1): piece = encoded_word[i : i + length] if piece in morse_to_letter and can_finish[i + length]: can_finish[i] = True break # If index 0 cannot reach the end, no valid decoding exists for this word. if not can_finish[0]: return [] # Phase 2 — Pruned backtracking over valid suffixes only: # unique_words: set of decoded strings (e.g. {"a", "et"}), deduplicating cuts # when two different Morse patterns happen to map to the same letter. unique_words: Set[str] = set() # current_letters: active path of chosen letters, e.g. ["e", "t"] current_letters: List[str] = [] def backtrack(index: int) -> None: if index == word_len: unique_words.add("".join(current_letters)) return max_step = min(max_pattern_len, word_len - index) for length in range(1, max_step + 1): next_index = index + length piece = encoded_word[index:next_index] # Checking can_finish[next_index] guarantees every recursive branch # reaches a full decoding — zero time is wasted on dead-end suffixes. if piece in morse_to_letter and can_finish[next_index]: current_letters.append(morse_to_letter[piece]) backtrack(next_index) current_letters.pop() backtrack(0) return sorted(unique_words)Combine per-word decodings into full sentences
Finally, we decode every word first. If any word produces
[], the whole message has no valid decoding and we return[]immediately before building combinations. Otherwise, we take the Cartesian product (pairing every prefix sentence built so far with every valid option for the next word, joined by" "):Example 2: encoded = ".-|--" -> encoded_words = [".-", "--"] word 1 (".-") options: ["a", "et"] word 2 ("--") options: ["m", "tt"] Combine word 1 x word 2: "a" + " " + "m" -> "a m" "a" + " " + "tt" -> "a tt" "et" + " " + "m" -> "et m" "et" + " " + "tt" -> "et tt"from typing import Dict, List def decode_without_separators( morse_to_letter: Dict[str, str], encoded_words: List[str], ) -> List[str]: # options_per_word: list of sorted valid decodings per word, e.g. [["a", "et"], ["m", "tt"]] options_per_word = [] for encoded_word in encoded_words: word_options = all_letter_sequences(morse_to_letter, encoded_word) # If even one word has zero valid decodings, the entire sentence fails immediately. if not word_options: return [] options_per_word.append(word_options) # Combine per-word options left-to-right (Cartesian product joined by single spaces). sentences = options_per_word[0] for word_options in options_per_word[1:]: next_sentences = [] for prefix_sentence in sentences: for decoded_word in word_options: next_sentences.append(prefix_sentence + " " + decoded_word) sentences = next_sentences return sorted(sentences)Complete solution
Putting
decode_morse_messagesand all helper functions together:from typing import Any, Dict, List, Optional, Set, Tuple def decode_morse_messages( morse_to_letter: Dict[str, str], encoded: str, char_sep: str, word_sep: str, ) -> List[str]: # Always split words BEFORE characters so multi-space word separators # (like word_sep=" ", char_sep=" ") are not chewed up by char_sep first. encoded_words = split_words(encoded, word_sep) # Non-empty char_sep means Mode 1 (deterministic single-sentence decoding). if char_sep != "": sentence = decode_with_separators(morse_to_letter, encoded_words, char_sep) if sentence is None: return [] return [sentence] # Empty char_sep means Mode 2 (enumerate every valid letter partition per word). return decode_without_separators(morse_to_letter, encoded_words) def split_words(encoded: str, word_sep: str) -> List[str]: # Python's str.split("") raises ValueError; empty word_sep means a single word. if word_sep == "": return [encoded] return encoded.split(word_sep) def decode_with_separators( morse_to_letter: Dict[str, str], encoded_words: List[str], char_sep: str, ) -> Optional[str]: # decoded_words: list of decoded word strings, e.g. ["me", "at"] decoded_words = [] for encoded_word in encoded_words: if not encoded_word: return None letters = [] for pattern in encoded_word.split(char_sep): if pattern not in morse_to_letter: return None letters.append(morse_to_letter[pattern]) decoded_words.append("".join(letters)) return " ".join(decoded_words) def all_letter_sequences( morse_to_letter: Dict[str, str], encoded_word: str, ) -> List[str]: word_len = len(encoded_word) if word_len == 0: return [] # max_pattern_len caps how far ahead we slice from any index i (4 for standard Morse). max_pattern_len = 0 for pattern in morse_to_letter: if len(pattern) > max_pattern_len: max_pattern_len = len(pattern) # Phase 1 — Right-to-left reachability DP: # can_finish: bool list of length word_len + 1 where can_finish[i] is True # iff encoded_word[i:] can be completely partitioned into known Morse patterns. can_finish = [False] * (word_len + 1) can_finish[word_len] = True for i in range(word_len - 1, -1, -1): max_step = min(max_pattern_len, word_len - i) # Start length at 1 so an empty "" key in morse_to_letter can never loop in place. for length in range(1, max_step + 1): piece = encoded_word[i : i + length] if piece in morse_to_letter and can_finish[i + length]: can_finish[i] = True break # If index 0 cannot reach the end, no valid decoding exists for this word. if not can_finish[0]: return [] # Phase 2 — Pruned backtracking over valid suffixes only: # unique_words: set of decoded strings (e.g. {"a", "et"}), deduplicating cuts # when two different Morse patterns happen to map to the same letter. unique_words: Set[str] = set() # current_letters: active path of chosen letters, e.g. ["e", "t"] current_letters: List[str] = [] def backtrack(index: int) -> None: if index == word_len: unique_words.add("".join(current_letters)) return max_step = min(max_pattern_len, word_len - index) for length in range(1, max_step + 1): next_index = index + length piece = encoded_word[index:next_index] # Checking can_finish[next_index] guarantees every recursive branch # reaches a full decoding — zero time is wasted on dead-end suffixes. if piece in morse_to_letter and can_finish[next_index]: current_letters.append(morse_to_letter[piece]) backtrack(next_index) current_letters.pop() backtrack(0) return sorted(unique_words) def decode_without_separators( morse_to_letter: Dict[str, str], encoded_words: List[str], ) -> List[str]: # options_per_word: list of sorted valid decodings per word, e.g. [["a", "et"], ["m", "tt"]] options_per_word = [] for encoded_word in encoded_words: word_options = all_letter_sequences(morse_to_letter, encoded_word) # If even one word has zero valid decodings, the entire sentence fails immediately. if not word_options: return [] options_per_word.append(word_options) # Combine per-word options left-to-right (Cartesian product joined by single spaces). sentences = options_per_word[0] for word_options in options_per_word[1:]: next_sentences = [] for prefix_sentence in sentences: for decoded_word in word_options: next_sentences.append(prefix_sentence + " " + decoded_word) sentences = next_sentences return sorted(sentences)✅ Submit now — all tests should pass.
Intuition & how it works
Decoding Morse strings with character delimiters (char_sep != "") works like reading ordinary spaced text: you split the input into words, split each word into individual symbol tokens, and look every token up in morse_to_letter. Decoding without character delimiters (char_sep == "") is like reading words whose internal letter spaces were erased — a two-symbol sequence ".-" could represent 'a' (".-") or 'e' (".") followed by 't' ("-"), so we must find every valid way to partition each encoded word into known patterns and then combine those decoded words into full sentences.
A naive brute-force search checks all 2^(L - 1) internal cut combinations of a word of length L, which is exponential even when only one valid cut exists. Plain backtracking (stepping forward whenever a prefix matches morse_to_letter and undoing the last step when stuck) is better, yet it still hits catastrophic slowdowns on dead ends — for instance, 60 dots followed by an unknown '-' tricks plain backtracking into exploring over 10^12 dot-splits before failing on '-' every single time. We eliminate that completely with a fast right-to-left dynamic programming pass (computing answers for smaller suffixes first and storing them in a boolean list can_finish[i]), ensuring our backtracking search only steps onto indices whose remaining suffix is guaranteed to reach the end cleanly.
Trace Example 2 (encoded = ".-|--", char_sep = "", word_sep = "|", morse_to_letter = {".-": "a", ".": "e", "--": "m", "-": "t"}):
1. Split on "|" first to obtain two independent encoded words: ".-" and "--".
2. For ".-", can_finish evaluates to [True, True, True]: from index 0, taking "." ('e') then "-" ('t') yields "et", while taking ".-" ('a') yields "a" -> sorted options ["a", "et"].
3. For "--", slicing as "-" + "-" gives "tt" and taking "--" gives "m" -> sorted options ["m", "tt"].
4. Taking the Cartesian product (pairing every valid decoding of word 1 with every valid decoding of word 2, joined by " ") returns ["a m", "a tt", "et m", "et tt"].
Complexity
Let N be the total length of encoded, L the length of a single encoded word, P the length of the longest pattern in morse_to_letter (4 for standard a–z), K the number of valid pattern partitions of a word, and S the total number of output sentences of length M.
- Time (Mode 1,
char_sep != ""):O(N)time, because splitting onword_sep, splitting each word onchar_sep, hash-table lookups, and joining the output characters each visit every character ofencodeda constant number of times. - Time (Mode 2,
char_sep == ""): Buildingcan_finishfor one word takesO(L * P^2)time (Lindices, up toPcandidate slice lengths, andO(P)characters copied/hashed per slice). Becausecan_finishprunes every dead end, every recursive call inbacktracklies on at least one of theKvalid partitions (each at mostL + 1steps deep), takingO(K * L * P^2 + K * log(K) * L)per word, plusO(S * log(S) * M)to build and sort allScombined sentences — work that scales strictly with the valid output whenPis bounded. - Space:
O(N)in Mode 1 for the split tokens and output string; in Mode 2,O(L)auxiliary memory per word forcan_finish,current_letters, and recursion stack frames, plus the memory required to hold theSoutput sentences.
Edge cases
- Overlapping multi-character delimiters (
char_sep = " ",word_sep = " "): Splitting onword_sepbeforechar_seppreserves triple-space word boundaries cleanly instead of shattering them into empty tokens. - Empty
word_sep(word_sep == ""): Guarded explicitly insplit_wordsso we return[encoded]instead of crashing with Python'sValueError: empty separator. - Unrecognized characters inside an unsegmented word (Example 3): When
encoded = ".-|-- -"withchar_sep = ""andword_sep = "|", neither' 'nor a single'-'appears in{".-": "a", "--": "m", ".": "e"}, socan_finishevaluates toFalseon word 2 and returns[]. - One undecodable word among valid words: Decoding all words before forming the Cartesian product catches an empty option list right away and returns
[]without building large intermediate prefix lists. - Distinct patterns mapping to the same letter: Collecting per-word decodings in a
set(unique_words) ensures two different cuts that spell the exact same word appear only once. - Empty message or trailing/double
word_sep(""or".-|"): Produces an emptyencoded_word, which both modes reject cleanly by returning[].
Common mistakes
- Splitting on
char_sepbeforeword_sep: Breaks standard Morse spacing (" "vs" ") because single-space splits destroy triple-space word boundaries first. - Using greedy longest-match in Mode 2: Always taking the longest valid prefix returns at most one answer and can even miss the only valid answer — for
"..-"with{"..": "i", ".-": "a", ".": "e"}, greedy picks".."and gets stuck on"-", missing"." + ".-" = "ea". - Backtracking without
can_finish(or memoization): Hangs on inputs like"." * 60 + "-"where billions of valid prefixes run into a single dead-end suffix. - Joining decoded words with
word_sepinstead of" ": Example 1 passesword_sep = "|"and expects["me at"]separated by" ", not"me|at". - Allowing zero-length slices: If
morse_to_letterever contained"", starting slice lengths at0would recurse infinitely at the same index; startingrange(1, ...)prevents that completely.
Alternative approaches
- Top-down recursion with memoization (Word Break II): Memoization caches each call's return value by index
isodecode(i)computes the full list of decoded suffixes ofencoded_word[i:]only once. It also avoids dead ends, though storing suffix string lists at every index uses more intermediate memory than a booleancan_finisharray plus one shared backtracking buffer. - Trie-accelerated pattern matching: A trie (a prefix tree whose edges are symbol characters like
.and-and whose nodes store valid letters) lets you step character by character from indexiinstead of slicing substrings of lengths1 .. P, saving a factor ofPwhen patterns are long.
Follow-up questions
- How would your approach change if you only needed to return the total count of valid decoded sentences rather than generating every string? Replace the boolean
can_finishlist with an integer count arraywayscomputed right-to-left: setways[L] = 1, and at each indexiaddways[i + length]across every valid sliceencoded_word[i : i + length]. Multiplyingways[0]across all words yields the exact sentence count inO(N * P^2)time andO(L)space — effortlessly handling inputs like60dots (~2.5 * 10^12sentences) that could never fit in memory as strings (assuming distinct Morse patterns map to distinct letters so partitions correspond 1-to-1 with decoded words). - How could you constrain the unsegmented decoder so that every output word belongs to a valid English dictionary? Filter each word's
all_letter_sequencesoutput against a vocabularysetimmediately before taking the Cartesian product, pruning gibberish combinations early. Better yet, when the vocabulary is fixed ahead of time, encode every dictionary word into its unsegmented Morse string once (morse_word -> list of English words), turning Mode 2 per-word decoding into a singleO(L)hash-table lookup! - What if word delimiters are also omitted, leaving one unbroken stream of dots and dashes across the entire message? Without word boundaries or a lexicon, short patterns like
"." = 'e'and"-" = 't'make almost every cut legal, producing astronomically many meaningless strings. Given an English vocabulary, pre-encode every vocabulary word into its concatenated Morse pattern to build a word-level Morse dictionary, then run the exact same right-to-leftcan_finishpass plus pruned backtracking over the full stream where each transition matches a complete English word rather than a single letter.
Follow-up questions
- How would your approach change if you only needed to return the total count of valid decoded sentences rather than generating every string?
- How could you constrain the unsegmented decoder so that every output word belongs to a valid English dictionary?
- What if word delimiters are also omitted, leaving one unbroken stream of dots and dashes across the entire message?
Similar questions
- Single-Cluster K-Means Centroid
- Express Soft K-Means Assignment as a Single Linear Layer
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance