LeetCode - Shortest Word Distance II
Problem description
Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.
Example:
1
2
3
4
5
6
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
- You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Analysis
The basic idea is to use a hashmap save all the index of each word.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class WordDistance {
HashMap<String, List<Integer>> indexes;
public WordDistance(String[] words) {
indexes = new HashMap<>();
for (int i = 0; i < words.length; i++){
if (!indexes.containsKey(words[i])){
List<Integer> list = new ArrayList<>();
indexes.put(words[i], list);
}
List<Integer> list = indexes.get(words[i]);
list.add(i);
}
}
public int shortest(String word1, String word2) {
int min = Integer.MAX_VALUE;
for (int i:indexes.get(word1)){
for (int j:indexes.get(word2)){
min = Math.min(min, Math.abs(i-j));
}
}
return min;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(words);
* int param_1 = obj.shortest(word1,word2);
*/
And we can use two pointers to reduce TC in the shortest function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public int shortest(String word1, String word2) {
ArrayList<Integer> loc1, loc2;
// Location lists for both the words
// the indices will be in SORTED order by default
loc1 = this.locations.get(word1);
loc2 = this.locations.get(word2);
int l1 = 0, l2 = 0, minDiff = Integer.MAX_VALUE;
while (l1 < loc1.size() && l2 < loc2.size()) {
minDiff = Math.min(minDiff, Math.abs(loc1.get(l1) - loc2.get(l2)));
if (loc1.get(l1) < loc2.get(l2)) {
l1++;
} else {
l2++;
}
}
return minDiff;
}
What to improve
- for sorted array, use two pointer to reduce TC