source: https://leetcode.com/problems/shortest-word-distance-iii/description/
Shortest Word Distance III
Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list.
Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.
Example 1:
Input: wordsDict = [“practice”, “makes”, “perfect”, “coding”, “makes”], word1 = “makes”, word2 = “coding”
Output: 1
Example 2:
Input: wordsDict = [“practice”, “makes”, “perfect”, “coding”, “makes”], word1 = “makes”, word2 = “makes”
Output: 3
Constraints:
- 1 <= wordsDict.length <= 105
- 1 <= wordsDict[i].length <= 10
- wordsDict[i] consists of lowercase English letters.
word1 and word2 are in wordsDict.
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
class Solution { public int shortestWordDistance(String[] wordsDict, String word1, String word2) { int[] a1 = new int[wordsDict.length]; int[] a2 = new int[wordsDict.length]; Arrays.fill(a1, -1); //O(n) Arrays.fill(a2, -1); //O(n) int p = 0; int q = 0; for(int i=0;i<wordsDict.length;i++){ //O(n) if(wordsDict[i].equals(word1)){ a1[p++] = i; } if(wordsDict[i].equals(word2)){ a2[q++] = i; } } //word1 is equal to word2 if(word1.equals(word2)){ return equal(a1, p); } //word1 and word2 are different return notEqual(a1, a2, p, q); } private int notEqual(int[] a1, int[] a2, int p, int q){ int i=0; int j=0; int min = Integer.MAX_VALUE; while(i<p && j<q){ //(min(O(p), O(q))) if(a1[i] < a2[j]){ min = Math.min(min, a2[j] - a1[i]); i++; } else{ min = Math.min(min, a1[i] - a2[j]); j++; } } return min; } private int equal(int[] a, int len){ //O(p) int min = Integer.MAX_VALUE; int i = 1; while(i<len){ min = Math.min(min, a[i] - a[i-1]); i++; } return min; } } |
Let’s say, wordsDict contains n elements
Time Complexity
O(n)
Space Complexity
O(2n) -> O(n)