Find where a sentence occurs in a document, with wildcards
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Cognition's coding screen, last asked Oct 2024. It tests strings, pattern matching and wildcards.
Given a document and a query sentence, return every position in the document where the sentence occurs. The query may contain * wildcards, so a plain substring search is not enough. Settle with the interviewer what a wildcard may stand for before you code; start with the version below, where text is compared word by word and each * stands for exactly one word.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
find_occurrences(document: str, query: str) -> list[int]— splits both on whitespace and returns, in increasing order, the word index indocumentwhere each match starts. A query word matches a document word when they are equal or the query word is*. Overlapping matches all count.
Example
document = "the cat sat on the mat and the cat sat on the hat"
find_occurrences(document, "the cat sat") -> [0, 7]
find_occurrences(document, "on the *") -> [3, 10] # * matches "mat", then "hat"
find_occurrences(document, "* cat sat on") -> [0, 7]
find_occurrences(document, "sat on the dog") -> []
Constraints
- Positions are word indices, starting at 0.
- An empty query or a query longer than the document returns
[].
Clarifying questions
- Does
*stand for exactly one word, any run of words (including none), or characters inside a word? - Are positions word indices or character offsets?
- Should matching ignore case and punctuation?
- Do overlapping matches count?
- Is the document searched once, or many times with different queries?
What a strong answer covers
- Tokenizing once, then a sliding comparison: O(n · m) for
ndocument words andmquery words, which is fine for one query. - For long queries with few wildcards: split the query on
*into fixed chunks and find each chunk with KMP or a hash of word ids, then check that the chunks line up at the right offsets. - If
*may cover any number of words: a greedy left-to-right match of the chunks or a DP over (query word, document word), and what "position" means when one start has several matches. - Edge cases: a query of only
*s, repeated words, a match at the very end. - Tests that cover each wildcard rule you agreed on.
Follow-ups
- Make
*match zero or more words. - Answer many queries over the same document: build an index from word to positions and start from the rarest fixed word.
- Return the matched text, not only its start.
Where it's asked
- Cognition · Coding screen · Last asked Oct 2024Live coding
What it tests
strings · pattern matching · wildcards
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
