The Shortest Word Distance III interview question extends Shortest Word Distance I with one key variation: word1 and word2 can be the same word. When they are the same, find the minimum distance between two different occurrences of the same word in the array. When they differ, the problem reduces to Shortest Word Distance I. This single edge case requires careful handling to avoid comparing a word with itself at the same index.
LinkedIn and Palantir Technologies ask this problem because it tests whether candidates handle the same-word edge case gracefully without significantly restructuring the core algorithm. The solution is a small but important modification of the two-index tracking approach: when word1 == word2, update the previous index before tracking the current one and compute distance between two consecutive occurrences.
The pattern is position tracking with same-word edge case. When word1 != word2: track idx1 and idx2 as the most recent positions of each word — identical to Shortest Word Distance I. When word1 == word2: use a single index prev. When the word is found at index i, compute i - prev if prev is valid, then update prev = i. The minimum across all such gaps is the answer.
words = ["a","b","c","b","a"], word1="b", word2="b" (same word).
Occurrences of "b": indices 1 and 3.
Distance between consecutive occurrences: |3 - 1| = 2.
words = ["a","b","a","b"], word1="a", word2="b" (different):
idx1 and idx2 for the same word results in comparing a word to itself at the same index (distance 0).idx1 == idx2 — they're the same index, not the same word appearing twice.prev variable handles it cleanly.prev to -1 or None — the first occurrence has no previous occurrence to compare with.For the Shortest Word Distance III coding problem, the array string interview pattern is a minimal extension of Shortest Word Distance I. The key modification: when word1 == word2, track only one previous index and measure consecutive occurrence gaps. LinkedIn and Palantir interviewers test this specific edge case — handle it cleanly with an if word1 == word2 branch at the start. Practice all three Shortest Word Distance variants together — they build progressively on the same position-tracking foundation and demonstrate mastery of the pattern when asked as a series.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Longest Common Prefix Between Adjacent Strings After Removals | Medium | Solve | |
| Remove Comments | Medium | Solve | |
| Shortest Word Distance | Easy | Solve | |
| Check If Two String Arrays are Equivalent | Easy | Solve | |
| Check if a String Is an Acronym of Words | Easy | Solve |