Magicsheet logo

Shortest Word Distance III

Medium
54.9%
Updated 6/1/2025

Shortest Word Distance III

What is this problem about?

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.

Why is this asked in interviews?

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.

Algorithmic pattern used

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.

Example explanation

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 for "a": 0, 2. idx2 for "b": 1, 3.
  • Minimum: |0-1|=1, |2-1|=1, |2-3|=1. Answer: 1.

Common mistakes candidates make

  • Not detecting the same-word case — using both idx1 and idx2 for the same word results in comparing a word to itself at the same index (distance 0).
  • Returning 0 as the distance when idx1 == idx2 — they're the same index, not the same word appearing twice.
  • Handling the same-word case by finding all positions and checking adjacent pairs — correct but unnecessary complexity; the running prev variable handles it cleanly.
  • Not initializing prev to -1 or None — the first occurrence has no previous occurrence to compare with.

Interview preparation tip

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.

Similar Questions