/* This class will be given a list of words (such as might be tokenized
- from a paragraph of job text), and will provide a method that takes two
- words and returns the shortest distance (in words) between those two
- words in the provided text.
- Example:
- JobDescDistanceFinder finder = new JobDescDistanceFinder(Arrays.asList("the", "java", "skill", "is", "important", "for", "java", "development"));
- assert(finder.distance("important", "the") == 4);
- assert(finder.distance("important", "java") == 2);
- assert(finder.distance("java", "doesntExist") == -1);
*/
public class JobDescDistanceFinder {
public JobDescDistanceFinder(List<String> words) {
// implementation here
}
public int distance(String wordOne, String wordTwo) {
// implementation here
}
}My Solution was
n is no of words
k = no of maximum occurance of an word (input wordOne and wordtwo).
TC :- O(n) + k*log(k)
Expection was
O(n) + O(k);
import java.util.*;
public class JobDescDistanceFinder {
private Map<String, List<Integer>> store = new HashMap<>();
public JobDescDistanceFinder(List<String> words) {
for(int i=0; i<words.size(); i++) {
List<Integer> list = store.getOrDefault(words.get(i), new ArrayList<>());
list.add(i);
store.put(words.get(i), list);
}
}
public int distance(String wordOne, String wordTwo) {
if(!store.containsKey(wordOne) || !store.containsKey(wordTwo) || wordOne == null || wordTwo == null) {
return -1;
}
if(wordOne.equals(wordTwo)) return 0;
List<Integer> list1 = store.get(wordOne);
List<Integer> list2 = store.get(wordTwo);
int min = Integer.MAX_VALUE;
for(Integer idx : list1) {
min = Math.min(min, Math.abs(idx - binSearch(list2, idx)));
}
return min;
}
private int binSearch(List<Integer> lst, int val) {
int i = 0;
int j = lst.size()-1;
int mid;
while(i<=j) {
mid = i + (j-i)/2;
if(lst.get(mid) == val) {
return mid;
}
if(lst.get(mid)< val) {
i = mid+1;
}
if(lst.get(mid) > val) {
j = mid-1;
}
}
return mid;
}
}Comments (4)


