O(n) java using hashmap


  • 0
    V
    public class WordDistance {
        Map<String, List<Integer>> wordToPositionMap = new HashMap<>();
        public WordDistance(String[] words) {
            for (int i = 0; i < words.length; i++) {
                if (!wordToPositionMap.containsKey(words[i])) {
                    wordToPositionMap.put(words[i], new ArrayList<Integer>());
                }
                wordToPositionMap.get(words[i]).add(i);
            }
        }
        
        public int shortest(String word1, String word2) {
            List<Integer> l1 = wordToPositionMap.get(word1);
            List<Integer> l2 = wordToPositionMap.get(word2);
            
            int i = 0, j = 0, minDist = Integer.MAX_VALUE;
            while (i < l1.size() && j < l2.size()) {
                minDist = Math.min(minDist, Math.abs(l1.get(i) - l2.get(j)));
                if (l1.get(i) < l2.get(j)) i++;
                else j++;
            }
            
            return minDist;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.