First say how you read it, because the question leaves three things open: what a word is, what "distance" counts, and what "indices" means. A sound reading: split the text into words, number them, and return every pair of positions [i, j] where word i is the first query word, word j is the second, and |i - j| <= k. The direct solution compares every occurrence of one word with every occurrence of the other. The better one collects each word's positions (already sorted) and slides a window over the second list, so each list is walked once. If the interviewer wants character offsets, or the text is a stream, keep only the occurrences seen in the last k words and pair each new occurrence with those.
Given a text and a query of two words plus an integer k, return the indices in the text where the distance between the two words is ≤ k.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
The words come from one regular expression on the lower-cased text, so The and the are the same word and punctuation is dropped. Two loops check each occurrence of the first word against each occurrence of the second. When both query words are the same, a pair is reported once, earlier position first. This is O(n²) in the number of words, which is fine to say out loud and then improve.
// Reading of the question: split the text into words, number them 0, 1, 2…, and return every// pair [i, j] where word i is the first query word, word j is the second, and they are at most// k words apart. Case is ignored.function nearPairs(text, first, second, k) {const words = text.toLowerCase().match(/[a-z0-9']+/g) ?? [];const a = first.toLowerCase();const b = second.toLowerCase();const pairs = [];for (let i = 0; i < words.length; i++) {if (words[i] !== a) continue;for (let j = 0; j < words.length; j++) {if (words[j] !== b || i === j) continue;// The same word twice: report each pair once, earlier position first.if (a === b && i > j) continue;if (Math.abs(i - j) <= k) pairs.push([i, j]);}}return pairs;}
passes 7 checks run on every build, against the native method where there is one
- both orders around one word
- exactly k apart counts, one more does not
- neighbours with k = 1, nothing with k = 0
- the same word twice: each pair once, earlier first
- case and punctuation are ignored, in the text and in both query words
- a missing word, an empty text, a negative k
- agrees with the definition on a long text
One pass records where each query word occurs. For a position i of the first word, the only useful positions of the second word are in [i - k, i + k]. Because both lists are sorted, the window's left edge lo only ever moves right as i grows. The cost is the number of words, plus the number of pairs returned. The output is identical to the first stage, which the last check proves against the definition.
// Collect the positions of each word once (both lists come out sorted). Then, for each position// of the first word, only the second word's positions inside [i - k, i + k] can match. `lo` never// moves backwards, so the lists are walked once, plus the matches themselves.function nearPairs(text, first, second, k) {const words = text.toLowerCase().match(/[a-z0-9']+/g) ?? [];const a = first.toLowerCase();const b = second.toLowerCase();const as = [];const bs = [];words.forEach((word, i) => {if (word === a) as.push(i);if (word === b) bs.push(i);});const pairs = [];let lo = 0;for (const i of as) {while (lo < bs.length && bs[lo] < i - k) lo++;for (let at = lo; at < bs.length && bs[at] <= i + k; at++) {const j = bs[at];if (a === b ? i < j : true) pairs.push([i, j]);}}return pairs;}
passes 7 checks run on every build, against the native method where there is one
- both orders around one word
- exactly k apart counts, one more does not
- neighbours with k = 1, nothing with k = 0
- the same word twice: each pair once, earlier first
- case and punctuation are ignored, in the text and in both query words
- a missing word, an empty text, a negative k
- agrees with the definition on a long text
matchAll gives each word together with its offset in the text (m.index), so the result can point into the original string. Instead of full position lists, two short queues hold the occurrences from the last k words; anything older can never match again and is dropped. The pattern uses Unicode property escapes (\p{L}, \p{N}), so café is one word. Results come out in the order the pairs are completed.
// "Indices in the text" can also mean character offsets, and the text can be too long to hold a// list of every word. One pass: remember only the occurrences seen in the last k words, and pair// each new occurrence with the remembered ones of the other word.function nearMatches(text, first, second, k) {const a = first.toLowerCase();const b = second.toLowerCase();const recentA = []; // { n: word number, at: character offset }const recentB = [];const out = [];let n = 0;for (const m of text.matchAll(/[\p{L}\p{N}']+/gu)) {const word = m[0].toLowerCase();while (recentA.length && n - recentA[0].n > k) recentA.shift();while (recentB.length && n - recentB[0].n > k) recentB.shift();if (word === b) for (const f of recentA) out.push({ first: f.at, second: m.index, distance: n - f.n });if (word === a && a !== b) for (const s of recentB) out.push({ first: m.index, second: s.at, distance: n - s.n });if (word === a) recentA.push({ n, at: m.index });if (word === b) recentB.push({ n, at: m.index });n++;}return out;}
passes 7 checks run on every build, against the native method where there is one
- character offsets of both words, and how far apart
- every offset points at its word
- exactly k apart counts, one more does not
- the same word twice: each pair once, earlier first
- letters outside a to z are words too
- it remembers only the last k words
- a missing word and an empty text
Proximity search
Search engines call this a proximity or "near" query: documents rank higher when the query words are close together. A positional index stores, for each word, the sorted positions it occurs at, which is exactly the two lists of the second stage.
Highlighting matches in a page
To highlight a found phrase you need character offsets into the original text, not word numbers. matchAll returns each match with its index.
Words in any language
[a-z] misses accented and non-Latin letters. \p{L} with the u flag matches a letter in any script; for real word boundaries in languages without spaces, use Intl.Segmenter.
Starting to code before asking whether distance is counted in words or characters.
Using
indexOfon the raw text, which findstheinsideother.Returning only the first pair when the words occur many times.
Reporting a word paired with itself, or the same pair twice, when both query words are equal.
Splitting on a single space, so punctuation sticks to words and
fox.never equalsfox.Restarting the inner scan from the beginning for every occurrence when the positions are already sorted.
What is the complexity of each version?
With n words, a and b occurrences and p pairs returned: the first is O(n²) as written (O(n + a·b) if you collect positions first). The second is O(n + a + b + p). The third is O(n + p) time and O(k) extra memory besides the output.
What if the order matters: the first word must come before the second?
Keep only pairs with i < j. In the streaming version that means pairing only when the second word arrives, with the remembered occurrences of the first.
How would you answer many queries on the same text?
Build the positional index once: a Map from each word to its sorted positions. Each query then skips the scan and goes straight to the window step.
How would you return only the closest pair?
Walk the two sorted lists with one pointer each, always advancing the pointer at the smaller position, and keep the smallest gap seen. That is O(a + b).
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter
- nlp.stanford.edu/IR-book/html/htmledition/positional-indexes-1.html