EasyArrayStringUpdated Sep 2026

243. Shortest Word Distance

Asked at Snowflake

Difficulty

Easy

Time

O(n)

Space

O(1)

Pattern

Array

Companies

1

Problem

You are given a list of words wordsDict and two different words, word1 and word2. Both words are guaranteed to appear somewhere in the list.

Return the shortest distance between an occurrence of word1 and an occurrence of word2. The distance is the absolute difference of their positions (indices) in the list. In other words, find the pair of positions — one holding word1, one holding word2 — that are closest together, and report how far apart they are.

Note that a word may appear many times, so you must consider every occurrence. The two words are always different, so you never compare a position with itself.

Find the closest pair of positions

wordsDictdistance 3practicemakesperfectcodingmakes01234"practice" sits at index 0 and "coding" at index 3, so the gapis 3.
We want the smallest gap between a "coding" position and a "practice" position in the list.

Constraints

  • ●2 <= wordsDict.length <= 3 * 10^4
  • ●1 <= wordsDict[i].length <= 10
  • ●wordsDict[i] consists of lowercase English letters.
  • ●word1 and word2 are in wordsDict.
  • ●word1 != word2

Examples

Example 1
InputwordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
Output3
Why"practice" is at index 0 and "coding" is at index 3. That is the only pair, so the distance is |3 - 0| = 3.
Example 2
InputwordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output1
Why"makes" appears at index 1 and index 4, while "coding" is at index 3. The closest pair is index 4 and index 3, giving |4 - 3| = 1.

Asked At

1 companies
CompanyDifficulty
SnowflakeEasyView all Snowflake questions →

How to Think About It

1

Brute force: collect all indices of word1 and all indices of word2, then compare every pair. That is O(a * b) in the worst case.

2

Key insight: when you reach an occurrence of one word, the only occurrence of the other word that can give the best distance "so far" is the most recent one. So remember just the last index of each.

3

Scan once. When you see word1, update i1; when you see word2, update i2. Whenever both are set, update best = min(best, abs(i1 - i2)).

4

Walkthrough for ["practice","makes","perfect","coding","makes"], "coding", "practice": index 0 sets practice=0; index 3 sets coding=3 -> distance 3. Answer 3.

5

Edge cases: the words are guaranteed to be different and both present. The follow-ups are the interesting part — many queries (Shortest Word Distance II) and word1 == word2 (III).

Optimal Approach

Step 1: i1 = i2 = -1, best = infinity.
Step 2: For each index i:
If words[i] == word1: i1 = i.
If words[i] == word2: i2 = i.
If both i1 and i2 are set: best = min(best, abs(i1 - i2)).
Step 3: Return best.

Time: O(n) comparisons (each is O(L) for word length). Space: O(1).

One pass, remember last seen index

wordsDictpracticemakesperfectcodingmakes01234i1=0Step 1 — index 0 is "practice", so i1 = 0. i2 is stillunknown.wordsDictbest = 3practicemakesperfectcodingmakes01234i2=3Step 2 — index 3 is "coding", so i2 = 3. Now both are set:best = |3 - 0| = 3.when both i1 and i2 are set:best = min(best, abs(i1 - i2))answer = 3
Keep the most recent index of each word; whenever both are known, check the gap.
ComplexityTime O(n)Space O(1)We scan the list once, and each comparison costs O(L) for the word length; only two index variables and one best value are stored.

What Trips People Up in Real Interviews

1

Storing every index and comparing all pairs. It is correct but quadratic — the "last seen" trick is what the interviewer is waiting for.

2

Only computing the distance when you see word2. You must update after either word, because the closest pair can end on either one.

3

Not asking about follow-ups. Mention that for many queries you would preprocess index lists (Shortest Word Distance II).

4

Initializing best to 0 instead of a large value.

Solution Code

O(n) time
def shortestDistance(wordsDict, word1, word2):
    i1 = i2 = -1
    best = len(wordsDict)
    for i, w in enumerate(wordsDict):
        if w == word1:
            i1 = i
        elif w == word2:
            i2 = i
        if i1 != -1 and i2 != -1:
            best = min(best, abs(i1 - i2))
    return best

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Shortest Word Distance problem?

Shortest Word Distance gives you a list of words and two different words that both appear in it, and asks for the smallest distance between an occurrence of the first and an occurrence of the second. It rewards a clean one-pass scan instead of comparing every pair of positions.

How do you solve Shortest Word Distance?

The optimal approach runs in O(n) time and O(1) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Shortest Word Distance?

Shortest Word Distance is asked at Snowflake. It is a easy difficulty problem.

What are common mistakes on Shortest Word Distance?
  • Storing every index and comparing all pairs. It is correct but quadratic — the "last seen" trick is what the interviewer is waiting for.
  • Only computing the distance when you see `word2`. You must update after either word, because the closest pair can end on either one.
  • Not asking about follow-ups. Mention that for many queries you would preprocess index lists (Shortest Word Distance II).
  • Initializing `best` to 0 instead of a large value.