The Shortest Word Distance interview question gives you an array of strings and two target words word1 and word2. Find the minimum distance (difference in indices) between any occurrence of word1 and any occurrence of word2 in the array. This is a simple linear scan problem — find the nearest pair of occurrences across both words.
Apple, Microsoft, Amazon, LinkedIn, and Anduril ask this problem because it tests the classic "track the last seen position of each element" pattern. It validates that candidates can maintain running positions and compute pairwise distances in a single pass, rather than naively finding all positions and comparing all pairs in O(n^2). This directly models "nearest neighbor" queries in recommendation systems and text search engines.
The pattern is single-pass scan with position tracking. Scan the array while tracking the most recently seen index of word1 (idx1) and word2 (idx2). When word1 is found, update idx1 and compute |idx1 - idx2| if idx2 is valid. When word2 is found, update idx2 and compute |idx1 - idx2| if idx1 is valid. Track the running minimum distance. This is O(n) time and O(1) space.
words = ["hello","world","hello","go","world"], word1 = "hello", word2 = "world".
Scan:
Answer: 1.
idx1 and idx2 to -1 or infinity — attempting to compute distance before both have been seen causes incorrect results.abs(idx1 - idx2) but forgetting to check both are valid (non-negative) before computing.For the Shortest Word Distance coding problem, the array string two-pointer interview pattern is the simple O(n) approach. The single-scan solution is the ideal answer — maintain two most-recent indices and update the minimum on each word encounter. LinkedIn interviewers ask this as a warmup before the harder variants (Shortest Word Distance II with repeated queries, Shortest Word Distance III where word1 and word2 can be the same). Know that solving this cleanly in O(n) prepares you for all three variants — the position-tracking pattern is the common thread across all of them.