Extract Stock Symbols from a Text Snippet
StringsAuto-graded · 18 test casesLast updated
Tests whole-word, case-insensitive multi-token matching with trie-based scanning and deduplication ordered by a reference list.
Problem
You are given a text snippet and a reference list that maps entity names to short symbol codes. Your task is to scan the text for any entity names that appear as complete, consecutive word sequences, then return the corresponding symbols.
Definitions
- Token: a maximal contiguous run of alphanumeric characters (
[a-zA-Z0-9]). Every non-alphanumeric character (spaces, punctuation, symbols) acts as a separator and is otherwise ignored. - Match: an entity name matches the text if and only if its tokens appear as a contiguous subsequence of the text's tokens, in the same order, with no gaps. Matching is case-insensitive.
Rules
- Tokenize both the text and every entity name using the definition above, then lowercase all tokens before comparing.
- A name with multiple words must appear as consecutive tokens in the text. A partial token is never a match — for example, the name
"App"does not match the token"apple". - Return only unique symbols. If the same symbol is reachable through several different names, include it only once.
- The output order follows the reference list, not the order of appearance in the text. Specifically, iterate through the reference list from top to bottom and emit each symbol the first time it qualifies.
Constraints
1 <= len(text) <= 10^51 <= len(reference) <= 10^4- Each entity name contains between 1 and 10 words, each word consisting of alphanumeric characters only.
textcontains only standard printable ASCII characters.- Symbols are non-empty strings of uppercase alphanumeric characters.
Examples
Example 1
Input: find_mentioned_tickers('Apple, along with Microsoft Corp., announced a partnership with OpenAI.', [['Apple', 'AAPL'], ['Amazon', 'AMZN'], ['Microsoft Corp', 'MSFT'], ['OpenAI', 'OPAI'], ['Microsoft', 'MSFT']])
Output: ['AAPL', 'MSFT', 'OPAI']
Example 2
Input: find_mentioned_tickers('Meta Platforms and meta are investing heavily in AI.', [['Meta Platforms', 'META'], ['Meta', 'META']])
Output: ['META']
Hints
Hint 1
Tokenize the text once with a regex that extracts maximal alphanumeric runs, then lowercase every token. Apply the same normalization to each entity name so both sides are comparable on equal footing.
Hint 2
Build a word-level trie from all entity names. At each terminal node store the normalized word tuple that identifies that name. Then slide a pointer across the text tokens: from each starting position, walk the trie as far as consecutive tokens allow, recording every terminal node you pass through.
Hint 3
Detection (which names appear) and output ordering (which symbols to emit) are independent concerns. After scanning, collect matched name tuples in a set, then make a single pass over the reference list to emit symbols in order, skipping duplicates with a seen set.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
High-level idea
Split the problem into two independent steps:
- Detect which entity names actually appear in the text.
- Emit symbols in the order dictated by the reference list, skipping duplicates.
Keeping these steps separate makes each part simpler and avoids tangling matching logic with ordering logic.
Step 1 — Normalize
Extract tokens from both the text and every entity name using the regex [A-Za-z0-9]+, then lowercase everything. After this step, "Microsoft Corp." and "microsoft corp" produce the identical tuple ("microsoft", "corp"), and punctuation has vanished from both sides.
Step 2 — Build a word-level trie
Insert each normalized name tuple into a trie whose edges are words, not characters. When all words of a name have been inserted, store the tuple itself at a sentinel key "$" on the terminal node. This serves as both the end-of-name marker and the lookup key used later.
The trie does two things efficiently:
- It lets the scanner prune dead paths immediately: if the current headline token is not an edge from the current node, no name starting here can match, so the inner loop breaks.
- It handles prefix relationships naturally. Both
"Bank"and"Bank of America"are discovered in a single walk from the same start position because the walk passes through both terminal nodes.
Step 3 — Scan the text
For every starting index start in text_tokens, walk the trie by consuming consecutive tokens. Stop early if a token is not an edge. Every time the walk reaches a node that has "$", add the stored tuple to a matched set. The maximum walk length is bounded by the longest entity name (at most 10 words), so the inner loop is O(10) = O(1) per start position.
Step 4 — Emit in reference order
Iterate over the reference list from top to bottom. For each entry, check whether its normalized tuple is in matched. If yes, and if the symbol has not been emitted yet, append the symbol to the result and add it to a seen_symbols set.
Why it is correct
- Whole-word matching. Tokens are maximal alphanumeric runs, so
"apple"is never equal to"app", and the trie edge for"app"simply will not be taken when the text token is"apple". - Consecutive, ordered words. A trie path starting at
startcorresponds exactly to the contiguous slicetext_tokens[start:start+k]. Reaching"$"afterksteps proves that slice equals the entity name's word sequence in order. - Case insensitivity. Both sides are lowercased before any comparison.
- Deduplication and ordering.
matchedstores name tuples, not symbols.seen_symbolsensures that a symbol reachable through multiple names is emitted only at its earliest position in the reference list.
Complexity
Let H = text length, n = number of text tokens, M = number of reference entries, W = total words across all names, K = maximum words in any name (≤ 10).
| Cost | |
|---|---|
| Tokenizing text | O(H) |
| Building trie | O(W) |
| Scanning text | O(n · K) — effectively O(n) since K ≤ 10 |
| Emitting results | O(M) |
Overall time: O(H + W + n·K)
Space: O(H + W) for tokens and trie
The naive alternative — for every entity name, check every possible starting position in the text — costs O(n · W), which reaches ~10¹⁰ in the worst case. The trie avoids this by sharing common prefixes and pruning mismatches immediately.
Edge cases
- Punctuation in the text (e.g.,
"Corp.") — the period is a delimiter;"corp"becomes an ordinary token adjacent to whatever follows. - Entity name appears multiple times — the
matchedset absorbs duplicates. - Same symbol, different names —
seen_symbolsprevents double-emission. - Text with no alphanumeric content (e.g.,
"!!!") —text_tokensis empty, the scan loop does not execute, and the result is[].
Reference solution
import re
from typing import List
def find_mentioned_tickers(text: str, reference: List[List[str]]) -> List[str]:
token_re = re.compile(r"[A-Za-z0-9]+")
# Tokenize the input text once.
text_tokens = [t.lower() for t in token_re.findall(text)]
# Build a word-level trie; "$" marks the end of a complete entity name.
root = {}
normalized_names = []
max_words = 0
for entity_name, _ in reference:
words = tuple(t.lower() for t in token_re.findall(entity_name))
normalized_names.append(words)
if not words:
continue
max_words = max(max_words, len(words))
node = root
for word in words:
node = node.setdefault(word, {})
node["$"] = words # store the key so we can look it up later
# Slide over every starting position in the text and walk the trie.
matched = set()
n = len(text_tokens)
for start in range(n):
node = root
end_limit = min(n, start + max_words)
for end in range(start, end_limit):
word = text_tokens[end]
if word not in node:
break
node = node[word]
if "$" in node:
matched.add(node["$"])
# Emit unique symbols in reference-list order.
result = []
seen_symbols = set()
for words, (_, symbol) in zip(normalized_names, reference):
if words in matched and symbol not in seen_symbols:
seen_symbols.add(symbol)
result.append(symbol)
return result