Split-or-Enumerate Symbol Sequence Decoder
Dynamic ProgrammingAuto-graded · 27 test casesLast updated
Tests string parsing, memoized backtracking, and combinatorial enumeration by decoding a symbol-encoded message with either explicit or missing letter boundaries.
Split-or-Enumerate Symbol Sequence Decoder
You are given a codebook: a dictionary mapping symbol patterns (strings of . and -) to single lowercase letters. You are also given an encoded message string, a letter delimiter letter_sep, and a word delimiter word_sep.
Your function must handle two distinct decoding modes depending on whether letter_sep is empty or not.
Mode 1 — Explicit letter boundaries (letter_sep is non-empty)
When letter_sep is provided, every letter boundary inside a word is marked by letter_sep, and word boundaries are marked by word_sep. Decode the message as follows:
- Split
encodedonword_septo recover individual encoded words. Ifword_sepis empty, treat the entire string as one word. - Within each word, split on
letter_septo recover individual symbol patterns. - Look up every pattern in the codebook. If any pattern is absent, the message is undecodable — return
[]. - Otherwise, join the decoded letters into words, join the words with single spaces, and return that one sentence inside a list.
Mode 2 — Missing letter boundaries (letter_sep is empty)
When letter_sep is empty, words are still separated by word_sep, but there is no delimiter between letters inside a word. A single encoded word may be partitioned into valid patterns in multiple ways, producing multiple possible decoded words.
For each encoded word, find every way to segment it into a sequence of patterns that are all present in the codebook, such that the patterns concatenate exactly to that word. Combine the per-word sets of decodings into full sentences by taking the Cartesian product across all words (preserving word order) and joining with single spaces.
If any word has zero valid segmentations, the entire message is undecodable — return [].
Ordering rule: when exploring segmentations inside a word, try patterns in order of decreasing length; break ties alphabetically. This makes the output order deterministic.
Space joining rule: when building sentences from the product, a space is inserted between words only when the accumulated prefix is non-empty (so a leading empty-string word does not produce a leading space).
Duplicates: do not deduplicate. If two distinct segmentation paths produce the same letter sequence, that sequence appears multiple times in the output.
Return value
Always return a List[str]:
- Mode 1 returns a list containing exactly one sentence, or
[]on failure. - Mode 2 returns all valid sentences (possibly more than one), or
[]if none exist. - If
encodedis"", return[""]immediately (one valid decoding: the empty sentence).
Constraints
encodedconsists of the characters.,-, and any separator characters; it may be empty.letter_sepandword_separe strings; either or both may be empty.- The codebook contains between 1 and 26 entries; every key is a non-empty string of
.and-; every value is a single lowercase letter. - No codebook key contains a separator character.
- When
letter_sepis non-empty it is different fromword_sep. - The encoded message length is at most 200 characters (excluding separators).
- The function must return results in the deterministic order described above.
Examples
Example 1
Input: decode_symbol_message({'-.': 'n', '-': 't', '..': 'i', '.': 'e'}, '-. -/-.', ' ', '/')
Output: ['nt n']
Example 2
Input: decode_symbol_message({'-.': 'n', '-': 't', '..': 'i', '.': 'e'}, '-. -', '', '/')
Output: []
Example 3
Input: decode_symbol_message({'...': 's', '..': 'i', '.': 'e', '-': 't'}, '... ..', '', '/')
Output: []
Hints
Hint 1
In Mode 1 every boundary is marked, so two plain string splits plus dictionary lookups are enough — no search required. Focus first on getting that path right before thinking about Mode 2.
Hint 2
Mode 2 is the classic 'Word Break II' problem applied independently to each encoded word. Define a recursive function decode_from(i) that returns all letter strings decodable from position i to the end of the word, and memoize it on i so each suffix is solved only once.
Hint 3
After solving each word independently, the full set of sentences is the Cartesian product of the per-word result lists. Build it by iterating through the word results one at a time, extending each accumulated prefix. Remember to reset the memoization cache between words.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The function has two clearly distinct modes, determined solely by whether letter_sep is empty.
Mode 1 — Two splits and a lookup
When letter_sep is non-empty, every boundary is already marked. The decoding is completely deterministic:
- Split
encodedonword_septo get a list of encoded words. - For each word, split on
letter_septo get individual symbol patterns. - Look each pattern up in the codebook. If any is missing, the whole message is invalid — return
[]. - Join the letters inside each word, then join the words with spaces, and return that sentence in a one-element list.
This is purely mechanical — no search, no recursion.
Mode 2 — Memoized segmentation then Cartesian product
When letter_sep is empty, words are still separated by word_sep, so each word can be solved independently. The problem inside a single word is the classic "Word Break II": find every way to partition a string into dictionary keys.
Define decode_from(i) as the tuple of all letter strings that correctly decode word[i:] to the end:
- Base case:
decode_from(len(word)) = ("",)— there is exactly one way to decode nothing: the empty string. - Recursive case: for each pattern
psuch thatwordstarts withpat positioni, prependsymbol_to_letter[p]to every result ofdecode_from(i + len(p)).
Memoizing on i ensures each suffix position is solved at most once. Returning a tuple makes cached values safe to share across callers.
Patterns are tried in order of decreasing length, with ties broken alphabetically. This makes the output order fully deterministic.
After solving every word, the complete set of sentences is the Cartesian product of the per-word result lists, built left-to-right and joined with spaces. A space is only prepended when the accumulated prefix is non-empty, so a leading empty-string word (from a leading word_sep) does not create a leading space.
If any word produces zero decodings, the product is empty — return [].
Why it is correct
Soundness: every string that decode_from(0) yields comes from a chain of patterns, each matching at the exact current index. The chain terminates at len(word) (the only base case), so the concatenated patterns equal the word exactly.
Completeness: take any valid segmentation. Its first pattern matches at index 0, so the loop considers it. By induction on suffix length, the rest of that segmentation appears in the recursive result. Therefore every valid decoding is generated.
Word independence: because word_sep fixes word boundaries, the choice of decoding in one word never affects another. The full answer set is exactly the product of the per-word sets.
Edge cases
encoded == ""→[""]immediately, before any splitting.- Empty
word_sep→ the whole string is treated as one word. - Unknown pattern in Mode 1 →
[]. - No valid segmentation for any word in Mode 2 →
[]. - Empty word in Mode 2 (e.g. consecutive
word_sep) →decode_from(0)hits the base case immediately and yields("",), contributing an empty string to the product. - Duplicates are preserved, not removed.
- The
lru_cacheis created fresh inside the loop body for each word, so it never leaks state between words.
Complexity
Let L be the length of an encoded word, P the number of codebook entries, and m the maximum pattern length.
- Mode 1: O(n) time and space, where n is the total length of
encoded. - Mode 2, memoization work per word:
L + 1states ×Ppatterns × O(m) prefix check = O(L · P · m). - Mode 2, output size: if word k has c_k decodings, there are ∏ c_k total sentences. Building and storing them takes O(n · ∏ c_k) time and space. This output-sensitive bound is optimal when every sentence must be returned.
from functools import lru_cache
from typing import Dict, List
def decode_symbol_message(symbol_to_letter: Dict[str, str], encoded: str, letter_sep: str, word_sep: str) -> List[str]:
if encoded == "":
return [""]
words = encoded.split(word_sep) if word_sep else [encoded]
# Mode 1: letter boundaries are explicit — one decoding or none.
if letter_sep:
decoded_words = []
for word in words:
patterns = word.split(letter_sep)
if any(pattern not in symbol_to_letter for pattern in patterns):
return []
decoded_words.append("".join(symbol_to_letter[p] for p in patterns))
return [" ".join(decoded_words)]
# Mode 2: enumerate all segmentations per word (Word Break II style).
results_by_word = []
# Try longer patterns first; break ties alphabetically for deterministic order.
patterns = sorted(symbol_to_letter, key=lambda p: (-len(p), p))
for word in words:
@lru_cache(maxsize=None)
def decode_from(i):
if i == len(word):
return ("",)
results = []
for pattern in patterns:
if word.startswith(pattern, i):
for suffix in decode_from(i + len(pattern)):
results.append(symbol_to_letter[pattern] + suffix)
return tuple(results)
results_by_word.append(decode_from(0))
if any(not results for results in results_by_word):
return []
# Cartesian product across words, preserving left-to-right order.
sentences = [""]
for decoded_words in results_by_word:
sentences = [
prefix + (" " if prefix else "") + w
for prefix in sentences
for w in decoded_words
]
return sentences