↓Skip to main content
  1. LeetCode/

LeetCode 244: Shortest Word Distance II

·2 mins· ·
LeetCode Medium Two-Pointers Design Hash-Table String Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-02-02

  • Submissions: Accepted (first try)

Approach
#

There are many queries, so at construction record every position of each word in a hash map. Building it in one pass over the array means each list is already sorted.

A query for word1, word2 becomes: given sorted lists a and b, find the minimum |a[i] - b[j]|. With two pointers:

  • Compare a[i] and b[j] and update the answer.
  • Advance the smaller one: it only gets farther from the later elements of the other list.

My Attempts
#

My accepted version compared the two position lists with a nested loop, O(|a| · |b|) per query, which is slow when a word appears many times and there are many queries. Two pointers make each query O(|a| + |b|).

Solution
#

class WordDistance:
    def __init__(self, wordsDict: List[str]):
        self.pos = defaultdict(list)
        for i, word in enumerate(wordsDict):
            self.pos[word].append(i)               # appended in order, so sorted

    def shortest(self, word1: str, word2: str) -> int:
        a, b = self.pos[word1], self.pos[word2]
        i = j = 0
        best = float("inf")
        while i < len(a) and j < len(b):
            best = min(best, abs(a[i] - b[j]))
            if a[i] < b[j]:
                i += 1                             # a[i] only gets farther from the rest of b
            else:
                j += 1
        return best

Complexity
#

Construction O(n), each query O(|a| + |b|), space O(n).

Mistakes to Avoid
#

  • Rescanning the whole array per query: it ignores that there are many queries.
  • Comparing every pair of positions with a nested loop: O(|a| · |b|).

Interview Explanation
#

At construction I record each word’s positions in a hash map; since they are appended in order, each list is sorted. For a query I run two pointers over the two lists, update the minimum difference, and advance the pointer with the smaller value, because it only gets farther from the rest of the other list. Each query is O(|a| + |b|).

Related

LeetCode 809: Expressive Words
·3 mins
LeetCode Medium Two-Pointers String Array
LeetCode 809 note: two pointers compare runs of equal characters; when the lengths differ, the run in s must be at least 3 and no shorter than the word’s run, and both strings must end together
LeetCode 923: 3Sum With Multiplicity
·4 mins
LeetCode Medium Two-Pointers Sorting Hash-Table Counting Array
LeetCode 923 note: sort, fix the first number, and find the other two with converging pointers; equal end values are counted with a combination, different ones by multiplying each end’s duplicate count
LeetCode 208: Implement Trie (Prefix Tree)
·2 mins
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 note: each node is a children dict plus an is_end flag; insert, search and startsWith all walk down character by character
LeetCode 981: Time Based Key-Value Store
·2 mins
LeetCode Medium Hash-Table String Binary-Search Design
LeetCode 981 note: store a (timestamp, value) list per key, with timestamps increasing; get binary searches the last timestamp <= the query
LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group
LeetCode 2337: Move Pieces to Obtain a String
·2 mins
LeetCode Medium Two-Pointers String
LeetCode 2337 note: after skipping blanks the piece order must match; L only moves left and R only moves right, so each L’s start index must be >= its target index and each R’s must be <=