Skip to content
BytePatterns

Nearest Two Words

EasySearching#single-pass#linear-scan~15m

Problem

A search tool ranks a document higher when two query words appear close together. Given a list of words and two different words a and b that each appear at least once, return the smallest distance between a position holding a and a position holding b. The distance between positions i and j is the absolute value of i minus j.

Examples

Input:  words = ["cat", "dog", "fox", "cat", "owl", "dog"], a = "cat", b = "dog"
Output: 1
Why:    the cat at 0 and the dog at 1 are neighbours
Input:  words = ["red", "sky", "sky", "sky", "blue"], a = "blue", b = "red"
Output: 4
Why:    each word appears once, at opposite ends
Input:  words = ["up", "down"], a = "up", b = "down"
Output: 1
Why:    edge case, the shortest list that can hold both words

Hints

0 / 3

Stuck on the idea rather than the code? Linear Search covers it.