LinkedIn 1st Round [Rejected]

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-11-06Added By Anonymous
Source: Link

/* 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);

*/

1 2public class JobDescDistanceFinder { 3 4 public JobDescDistanceFinder(List<String> words) { 5 // implementation here 6 } 7 public int distance(String wordOne, String wordTwo) { 8 // implementation here 9 } 10}

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);


1 2import java.util.*; 3 4public class JobDescDistanceFinder { 5 6 private Map<String, List<Integer>> store = new HashMap<>(); 7 public JobDescDistanceFinder(List<String> words) { 8 for(int i=0; i<words.size(); i++) { 9 List<Integer> list = store.getOrDefault(words.get(i), new ArrayList<>()); 10 list.add(i); 11 store.put(words.get(i), list); 12 } 13 } 14 public int distance(String wordOne, String wordTwo) { 15 if(!store.containsKey(wordOne) || !store.containsKey(wordTwo) || wordOne == null || wordTwo == null) { 16 return -1; 17 } 18 19 if(wordOne.equals(wordTwo)) return 0; 20 21 List<Integer> list1 = store.get(wordOne); 22 List<Integer> list2 = store.get(wordTwo); 23 24 int min = Integer.MAX_VALUE; 25 for(Integer idx : list1) { 26 min = Math.min(min, Math.abs(idx - binSearch(list2, idx))); 27 } 28 29 return min; 30 31 } 32 33 private int binSearch(List<Integer> lst, int val) { 34 int i = 0; 35 int j = lst.size()-1; 36 int mid; 37 while(i<=j) { 38 mid = i + (j-i)/2; 39 if(lst.get(mid) == val) { 40 return mid; 41 } 42 if(lst.get(mid)< val) { 43 i = mid+1; 44 } 45 if(lst.get(mid) > val) { 46 j = mid-1; 47 } 48 49 } 50 return mid; 51 } 52}


Comments