244. Shortest Word Distance II
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
This problem asks us to design a data structure that, after being initialized with a list of words, can efficiently answer queries for the shortest distance between two given words. Since the shortest method can be called many times, it's beneficial to do some pre-processing in the constructor to optimize these queries.
Solution
Shortest Word Distance II in Python
import collections
import math
from typing import List
class WordDistance:
def __init__(self, wordsDict: List[str]):
# Use defaultdict to simplify appending to lists for new words.
# This map stores each word and a list of its indices.
self.locations = collections.defaultdict(list)
# Pre-process the input list to populate the locations map.
for i, word in enumerate(wordsDict):
self.locations[word].append(i)
def shortest(self, word1: str, word2: str) -> int:
# Retrieve the sorted lists of indices for the two words.
indices1 = self.locations[word1]
indices2 = self.locations[word2]
min_dist = math.inf
p1, p2 = 0, 0
# Use a two-pointer approach to find the minimum distance.
while p1 < len(indices1) and p2 < len(indices2):
idx1 = indices1[p1]
idx2 = indices2[p2]
# Update the minimum distance found so far.
min_dist = min(min_dist, abs(idx1 - idx2))
# Advance the pointer that points to the smaller index to find a
# potentially smaller difference.
if idx1 < idx2:
p1 += 1
else:
p2 += 1
return int(min_dist)
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)
Shortest Word Distance II in Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class WordDistance {
// A map to store each word and the list of indices where it appears.
private Map<String, List<Integer>> locations;
public WordDistance(String[] wordsDict) {
this.locations = new HashMap<>();
// Pre-process the input array to populate the locations map.
for (int i = 0; i < wordsDict.length; i++) {
// The key is the word, and the value is a list of its indices.
// computeIfAbsent ensures the list is created if it's the first time we see the word.
this.locations.computeIfAbsent(wordsDict[i], k -> new ArrayList<>()).add(i);
}
}
public int shortest(String word1, String word2) {
// Retrieve the sorted lists of indices for the two words.
List<Integer> indices1 = locations.get(word1);
List<Integer> indices2 = locations.get(word2);
int min_dist = Integer.MAX_VALUE;
int p1 = 0, p2 = 0;
// Use a two-pointer approach to find the minimum distance.
while (p1 < indices1.size() && p2 < indices2.size()) {
int idx1 = indices1.get(p1);
int idx2 = indices2.get(p2);
// Update the minimum distance found so far.
min_dist = Math.min(min_dist, Math.abs(idx1 - idx2));
// Advance the pointer that points to the smaller index to find a
// potentially smaller difference.
if (idx1 < idx2) {
p1++;
} else {
p2++;
}
}
return min_dist;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(wordsDict);
* int param_1 = obj.shortest(word1,word2);
*/
Shortest Word Distance II in C++
#include <vector>
#include <string>
#include <unordered_map>
#include <climits>
#include <cmath>
class WordDistance {
private:
// A hash map to store each word and the list of indices where it appears.
std::unordered_map<std::string, std::vector<int>> locations;
public:
WordDistance(std::vector<std::string>& wordsDict) {
// Pre-process the input array to populate the locations map.
for (int i = 0; i < wordsDict.size(); ++i) {
// The key is the word, and the value is a list of its indices.
locations[wordsDict[i]].push_back(i);
}
}
int shortest(std::string word1, std::string word2) {
// Retrieve the sorted lists of indices for the two words.
std::vector<int>& indices1 = locations[word1];
std::vector<int>& indices2 = locations[word2];
int min_dist = INT_MAX;
int p1 = 0, p2 = 0;
// Use a two-pointer approach to find the minimum distance.
while (p1 < indices1.size() && p2 < indices2.size()) {
int idx1 = indices1[p1];
int idx2 = indices2[p2];
// Update the minimum distance found so far.
min_dist = std::min(min_dist, std::abs(idx1 - idx2));
// Advance the pointer that points to the smaller index to find a
// potentially smaller difference.
if (idx1 < idx2) {
p1++;
} else {
p2++;
}
}
return min_dist;
}
};
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance* obj = new WordDistance(wordsDict);
* int param_1 = obj->shortest(word1,word2);
*/
Shortest Word Distance II in TypeScript
class WordDistance {
// A map to store each word and the list of indices where it appears.
private locations: Map<string, number[]>;
constructor(wordsDict: string[]) {
this.locations = new Map<string, number[]>();
// Pre-process the input array to populate the locations map.
for (let i = 0; i < wordsDict.length; i++) {
const word = wordsDict[i];
// If the word is not yet in the map, initialize its list.
if (!this.locations.has(word)) {
this.locations.set(word, []);
}
// The '!' non-null assertion is safe because we just ensured the key exists.
this.locations.get(word)!.push(i);
}
}
shortest(word1: string, word2: string): number {
// Retrieve the sorted lists of indices for the two words.
// The '!' non-null assertion is safe due to problem constraints.
const indices1 = this.locations.get(word1)!;
const indices2 = this.locations.get(word2)!;
let min_dist = Number.MAX_SAFE_INTEGER;
let p1 = 0;
let p2 = 0;
// Use a two-pointer approach to find the minimum distance.
while (p1 < indices1.length && p2 < indices2.length) {
const idx1 = indices1[p1];
const idx2 = indices2[p2];
// Update the minimum distance found so far.
min_dist = Math.min(min_dist, Math.abs(idx1 - idx2));
// Advance the pointer that points to the smaller index to find a
// potentially smaller difference.
if (idx1 < idx2) {
p1++;
} else {
p2++;
}
}
return min_dist;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* var obj = new WordDistance(wordsDict)
* var param_1 = obj.shortest(word1,word2)
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.