← Questions

Find where a sentence occurs in a document, with wildcards

0
CognitionCodingLast asked Oct 2024

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 in document where 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 n document words and m query 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

What it tests

strings · pattern matching · wildcards

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding