Tell me a Leetwode question about generating harry potter stories. For a NLP research role
Assistant
User
Dont make up a question. This is a original Leetcode question that I was asked in an interview but can't remenbrt it
Assistant
Sure thing—let’s try piecing it back together together. Since it sounds like a real LeetCode-style/daily-coding problem that you were asked, I want to help you track it down or reconstruct it faithfully.
Could you share any of the following details you remember? Even partial hints could help:
Do you recall the title (or part of the title), even vaguely—like “Harry something,” or “spell generation,” etc.?
Was it labeled as an algorithm problem (e.g., dynamic programming, backtracking, BFS, graph, string generation), or more NLP-focused?
Any details about the input format? Was it strings, token lists, some tree/graph, constraints like “must include X,” “exactly K occurrences,” etc.?
Did it mention Harry Potter specifically, or was it more general (“story generation” but your interviewer used HP as a theme)?
Do you remember the expected output structure (e.g., return a string, list of strings, integer count, etc.)?
Here’s a LeetCode-style problem you can use. It’s framed to test both algorithms and NLP instincts, but it’s fully auto-gradeable and deterministic.
Constrained Story Generation (Harry-Potter Themed)
Problem
You’re given a tiny trigram language model (LM) over a wizarding-themed vocabulary and must generate a short story that maximizes LM log-likelihood while satisfying hard lexical constraints.
Implement constrained beam search that returns the most probable token sequence under these constraints.
Constraints (all hard)
Length: 50–80 tokens (inclusive), not counting and including a single at the end.
Must contain all tokens in a required set R (order free).
Must not contain any token from a forbidden set F.
Must mention exactly K “spell” tokens (from a provided list S) anywhere in the story.
The first non- token must be one of the allowed starters A.
The story must be a single sequence ending with . No may appear before the last position.
Among all sequences that satisfy (1)–(6), output the one with maximum total log-probability under the trigram LM.
Notes
• Tokens are lowercase strings like harry, wand, lumos, punctuation tokens (, .) are separate tokens, and is the end token.
• The LM is deterministic and provided as log-probs: logp[next | prev2, prev1]. Missing trigrams mean log-probability -inf (disallowed).
• “Spell” tokens are explicitly listed; don’t guess.
Input
All inputs are JSON files (paths passed to your program via CLI args) with the following schema:
You can assume vocab.json and constraints.json always contain consistent tokens; lm.json may exclude some trigrams (treat as -inf).
Output
Print a single line: the best sequence of tokens space-separated, ending in . Do not print .
Example (shortened for display; real output must meet the length constraint):
php-templateCopyEditharry lifts the wand , lumos glows under the dark hall . ...
Function Signature
Implement the following (language-agnostic description):
goCopyEditstring generate_story(
LM lm, // function: (prev2_id, prev1_id) -> dict[next_id -> logp]
List[int] A_ids, // allowed starters
Set[int] R_ids, // required tokens (must all appear ≥1)
Set[int] F_ids, // forbidden tokens (must not appear)
Set[int] S_ids, // spell tokens universe
int K, // exactly K spell tokens must appear in total
int min_len, int max_len
)
Return the best valid story as token string (tokens separated by spaces) or an empty string if impossible.
Required Approach: Constrained Beam Search
Use beam search with the following state per hypothesis:
seq (list of token ids)
score (sum of log-probs so far)
req_left (bitmask or set of required tokens not yet seen)
spell_count (int, total spell tokens seen)
ended (bool; only true if last token is )
prev2, prev1 (last two token ids for trigram)
Pruning & Feasibility
A hypothesis is infeasible and must be pruned if:
Contains any token in F_ids.
spell_count > K.
The best-case remaining length cannot satisfy requirements:
If already at length L (excluding ), then L > max_len is infeasible.
If ended and L < min_len, infeasible.
If len + minimal_required_tokens_remaining > max_len, infeasible.
may only be appended if min_len ≤ current_len+1 ≤ max_len and req_left is empty and spell_count == K.
Keep the top B hypotheses per step by score (ties broken lexicographically by token id). Use B = 32 (fixed).
Stop when:
All beams are ended; or
Length exceeds max_len.
Pick the best ended hypothesis.
Examples
Example 1 (toy)
iniCopyEditA = ["harry","hermione","ron"]
R = ["harry","wand","castle"]
F = ["malfoy"]
S = ["lumos","nox","expelliarmus","patronus"]
K = 2
min_len = 8
max_len = 14
Suppose the LM only allows the following (not exhaustive):
harry -> wand (−0.2), castle (−0.7)
harry wand -> , (−0.1), lumos (−1.0)
wand , -> castle (−0.2)
, castle -> . (−0.3), lumos (−0.6)
castle lumos -> glows (−0.3)
lumos glows -> . (−0.2)
glows . -> (−0.1)
A valid output (meeting constraints and maximizing the toy LM) might be:
php-templateCopyEditharry wand , castle lumos glows .
(Length meets the toy min/max, includes harry,wand,castle, uses exactly one spell if K=1, no malfoy.)
Example 2 (impossible)
If K=3 while only two spell words are reachable in the LM, return an empty string.
Edge Cases to Handle
No feasible starter in A has any outgoing trigram path → return empty.
The LM forces an early before min_len → prune those paths.
Repetition loops: rely on beam limit; do not add repetition penalties.
Punctuation as separate tokens—don’t allow right after .
Complexity
Let V be vocab size, T max length, B=32:
Time: O(T · B · avg_branching) where branching is the number of non--inf next tokens from each (prev2,prev1).
Space: O(B · T) to store beams.
Hidden Tests (used by the judge)
Verifies all hard constraints.
Verifies only at the end.
Checks you achieved the best score among valid sequences by comparing to a DP baseline on small instances.
Stress tests where many trigrams are -inf.
Follow-ups (for discussion)
Add a coverage penalty over R to encourage early satisfaction.
Diverse beam search to produce N distinct stories.
Replace hard K with a Poisson prior and use score augmentation.
Plug in a classifier-guided logit bias (e.g., style or toxicity).
Switch to WFST decoding and express constraints as a composition with an FSA.
def feasible(item):
L = len(item.seq)
if any(t in F_ids for t in item.seq): return False
if item.spell_count > K: return False
if L > max_len: return False
if item.ended:
return (min_len <= L <= max_len and
not item.req_left and item.spell_count == K)
# optimistic feasibility check:
min_extra = len(item.req_left) + max(0, K - item.spell_count)
return (L + min_extra) <= max_len
for step in range(max_len):
new_beams = []
for b in beams:
if b.ended:
new_beams.append(b)
continue
# get candidates
next_logps = lm.get((b.prev2, b.prev1), {})
for nxt, lp in next_logps.items():
# enforce starter constraint at first token
if len(b.seq) == 0 and nxt not in A_ids:
continue
# handle EOS: only allow when all hard conditions can be met
if nxt == eos_id:
L = len(b.seq) + 1
if not (min_len <= L <= max_len and not b.req_left and b.spell_count == K):
continue
nb = BeamItem(b.seq+[nxt], b.prev1, nxt, b.score + lp, b.req_left, b.spell_count, True)
else:
req_left = set(b.req_left)
if nxt in req_left: req_left.remove(nxt)
spell_count = b.spell_count + (1 if nxt in S_ids else 0)
nb = BeamItem(b.seq+[nxt], b.prev1, nxt, b.score + lp, req_left, spell_count, False)
if feasible(nb):
new_beams.append(nb)
# prune to top B by (score, lexicographic tie-break)
new_beams.sort(key=lambda x: (x.score, x.seq), reverse=True)
beams = new_beams[:B]
if all(b.ended for b in beams): break
# pick best ended
ended = [b for b in beams if b.ended]
if not ended: return ""
best = max(ended, key=lambda x: x.score)
return " ".join(id_to_token[t] for t in best.seq)
What this tests
Search/optimization under hard constraints
Careful state design
Pruning & feasibility reasoning
Handling of language modeling details (n-gram context, , tokenization)
Edge cases and determinism (research-y but interview-grade)
If you want, I can also provide a tiny concrete lm.json so you can run this end-to-end in your environment.
Was it about generating the story (constructing text) or checking whether a story could be generated or valid under some rules?
Any constraints or tricky parts—hard length limits, counting occurrences, excluding certain words, optimizing a probability or score?
Or maybe lexicographic ordering, counting subsequences, or path enumeration under constraints?
Even one clue—like “it had a constraint on including exactly one ‘Lumos’ and one ‘Expelliarmus’,” or “it was about maximizing some score while obeying a grammar constraint”—might be enough to narrow it down.
Let me know whatever fragment you recall. From there, I can search LeetCode, or at least reconstruct the exact problem statement you encountered.