Lost a solid 10 minutes convinced there was some logic bug in my approach.
Tokenize the sentence into words while tracking each word's original position, then scan for occurrences of the first query word and check if the second word appears within the next K words. Collect and return the positions of the first word that satisfy the proximity condition.
Pro tip: Clarify upfront whether 'within K words after it' means strictly after (excluding the first word) and whether positions are 0-indexed or 1-indexed, and mention handling punctuation and case sensitivity—this shows attention to edge cases and real-world data quality.
Confirm definitions: what counts as a word (punctuation handling), whether matching is case-sensitive, whether K counts words strictly after the first word, and whether positions are 0- or 1-indexed. Also ask about overlapping matches and empty inputs.
Split the sentence into words while preserving original positions (e.g., store each word with its index). Normalize case if needed and decide how to treat punctuation.
Iterate through the tokenized words and record every index where the first query word appears. These are the only positions that can potentially satisfy the condition.
For each candidate position, examine the next K words (or up to the end of the sentence) and check if the second query word occurs. If yes, add the candidate position to the result list.
Return the list of valid positions. Analyze time complexity: O(N) to tokenize plus O(M*K) for checks, where M is the number of first-word occurrences; mention potential optimizations like precomputing second-word positions.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.