245. Shortest Word Distance III
mediumAsked at LinkedInSame as Shortest Word Distance but word1 might equal word2 — meaning you need the closest pair of occurrences of the same word. LinkedIn asks this as the culminating follow-up to the series, testing whether you spot the asymmetric case before writing code.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in LinkedIn loops.
- Glassdoor (2026-Q1)— LinkedIn onsite reports list III as a frequent third question after I and II are warmed up.
- Blind (2025-12)— LinkedIn writeups specifically highlight the same-word case as the differentiator — many candidates miss it.
Problem
Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list. Note that word1 and word2 may be the same and they represent two individual words in the list.
Constraints
1 <= wordsDict.length <= 3 * 10^4wordsDict[i] consists of lowercase English letters.word1 and word2 are in wordsDict.
Examples
Example 1
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"1Example 2
wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"3Explanation: The two 'makes' occurrences are at indices 1 and 4.
Approaches
1. Single-pass with case-branch on word1 === word2 (optimal)
If word1 === word2, track the previous index of that word; the distance is current - prev. If word1 !== word2, fall back to the original two-tracker approach.
- Time
- O(n)
- Space
- O(1)
function shortestWordDistance(wordsDict, word1, word2) {
let best = Infinity;
if (word1 === word2) {
let prev = -1;
for (let i = 0; i < wordsDict.length; i++) {
if (wordsDict[i] === word1) {
if (prev !== -1) best = Math.min(best, i - prev);
prev = i;
}
}
return best;
}
let i1 = -1, i2 = -1;
for (let i = 0; i < wordsDict.length; i++) {
if (wordsDict[i] === word1) i1 = i;
else if (wordsDict[i] === word2) i2 = i;
if (i1 !== -1 && i2 !== -1) best = Math.min(best, Math.abs(i1 - i2));
}
return best;
}Tradeoff: Clean — two short branches. The same-word case can't reuse i1/i2 trackers because each new occurrence updates the same variable; need a prev/current pair.
2. Unified single-pass with i1 = previous-of-i1 swap
Use one tracker per word. If they're the same word, before assigning i1 = i, push the old i1 to i2. This effectively lets one variable serve both roles.
- Time
- O(n)
- Space
- O(1)
function shortestWordDistanceUnified(wordsDict, word1, word2) {
const same = word1 === word2;
let i1 = -1, i2 = -1, best = Infinity;
for (let i = 0; i < wordsDict.length; i++) {
if (wordsDict[i] === word1) {
if (same) { i2 = i1; i1 = i; }
else i1 = i;
} else if (wordsDict[i] === word2) {
i2 = i;
}
if (i1 !== -1 && i2 !== -1 && i1 !== i2) best = Math.min(best, Math.abs(i1 - i2));
}
return best;
}Tradeoff: Same O(n) but compresses to one loop. The `i1 !== i2` guard is necessary to skip the case where both trackers point to the same index in the non-same-word fork.
LinkedIn-specific tips
LinkedIn interviewers want you to spot the same-word case BEFORE writing code. Say: 'Wait — word1 might equal word2, so I can't just track 'last index of each' in two variables; I need to track the previous and current occurrence of the same word.' That observation is the entire signal. The two-branch version is easier to write under pressure; the unified version scores higher on style.
Common mistakes
- Missing the case where word1 === word2 entirely — runs the I solution and returns 0 (because i1 === i2 always).
- In the same-word branch, comparing the current index against itself — must use the previous occurrence.
- In the unified version, forgetting the `i1 !== i2` guard — returns 0 when both trackers point to the same position.
Follow-up questions
An interviewer at LinkedIn may pivot to one of these next:
- What if you needed the k-shortest distances? (Maintain a min-heap of candidate pairs.)
- What if the word list could be updated online? (Same trackers; just rerun on update.)
- Could you do this with regex? (No — distances need positional reasoning.)
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why can't you just call the II solution with word1 === word2?
The II solution's two-pointer merge walk on two identical sorted lists would always find distance 0 (matching index against itself). You need to skip the self-match — either by the case-branch in the optimal solution or by careful pointer arithmetic.
Is the unified version really better?
Stylistically yes — one loop, clear branch. But under interview pressure the two-branch version is easier to debug. Either is acceptable; pick the one you can write correctly the first time.
Free learning resources
Curated free links for this problem.
Practice these live with InterviewChamp.AI
Drill Shortest Word Distance III and other LinkedIn interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →