Skip to content

Commit 88bacb0

Browse files
authored
Merge pull request #3902 from sivaprasath2004/sivaprasath-closes-issue-3890
[Feature]: Add 245. Shortest Word Distance III solution
2 parents 28ac03a + c577cc4 commit 88bacb0

File tree

1 file changed

+358
-0
lines changed

1 file changed

+358
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,358 @@
1+
---
2+
id: shortest-distance-between-words-III
3+
title: Shortest Distance Between Words -III
4+
sidebar_label: 0245-Shortest Distance Between Words - III
5+
tags: [Hash Map, Two Pointers]
6+
description: Solution to finding the shortest distance between two words in an array of strings.
7+
---
8+
9+
## Problem Statement
10+
11+
- 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.
12+
13+
- Note: that `word1` and `word2` may be the same. It is guaranteed that they represent two individual words in the list.
14+
15+
#### Example 1:
16+
```bash
17+
Input: wordsDict = [“practice”, “makes”, “perfect”, “coding”, “makes”], word1 = “makes”, word2 = “coding”
18+
Output: 1
19+
```
20+
21+
#### Example 2:
22+
23+
```bash
24+
Input: wordsDict = [“practice”, “makes”, “perfect”, “coding”, “makes”], word1 = “makes”, word2 = “makes”
25+
Output: 3
26+
```
27+
28+
### Solution
29+
30+
#### Approach
31+
32+
1. **Initialization**:
33+
- Initialize two variables to store the most recent positions of `word1` and `word2`.
34+
- Initialize a variable to store the minimum distance, set it to a large value initially.
35+
36+
2. **Single Pass through the List**:
37+
- Iterate through the list, and for each word:
38+
- If the word is `word1`, update the most recent position of `word1`.
39+
- If the word is `word2`, update the most recent position of `word2`.
40+
- If both words are the same, ensure you handle the same word case properly.
41+
- Calculate the distance between the most recent positions of `word1` and `word2` and update the minimum distance if the calculated distance is smaller.
42+
43+
3. **Output**:
44+
- After iterating through the list, the minimum distance variable will hold the shortest distance between the two words.
45+
46+
47+
#### Codes in Different Languages
48+
49+
<Tabs>
50+
<TabItem value="javascript" label="JavaScript" default>
51+
<SolutionAuthor name="@sivaprasath"/>
52+
```javascript
53+
function shortestDistance(wordsDict, word1, word2) {
54+
let pos1 = -1;
55+
let pos2 = -1;
56+
let minDistance = Infinity;
57+
58+
for (let i = 0; i < wordsDict.length; i++) {
59+
if (wordsDict[i] === word1) {
60+
pos1 = i;
61+
if (word1 === word2) {
62+
pos2 = pos1;
63+
}
64+
if (pos2 !== -1) {
65+
minDistance = Math.min(minDistance, Math.abs(pos1 - pos2));
66+
}
67+
} else if (wordsDict[i] === word2) {
68+
pos2 = i;
69+
if (pos1 !== -1) {
70+
minDistance = Math.min(minDistance, Math.abs(pos1 - pos2));
71+
}
72+
}
73+
}
74+
75+
return minDistance;
76+
}
77+
78+
// Example usage:
79+
const wordsDict1 = ["practice", "makes", "perfect", "coding", "makes"];
80+
const word1 = "makes";
81+
const word2 = "coding";
82+
console.log(shortestDistance(wordsDict1, word1, word2)); // Output: 1
83+
84+
const wordsDict2 = ["practice", "makes", "perfect", "coding", "makes"];
85+
const word1Same = "makes";
86+
const word2Same = "makes";
87+
console.log(shortestDistance(wordsDict2, word1Same, word2Same)); // Output: 3
88+
```
89+
</TabItem>
90+
<TabItem value="typescript" label="TypeScript">
91+
92+
93+
```typescript
94+
function shortestDistance(wordsDict: string[], word1: string, word2: string): number {
95+
let pos1: number = -1;
96+
let pos2: number = -1;
97+
let minDistance: number = Infinity;
98+
99+
for (let i = 0; i < wordsDict.length; i++) {
100+
if (wordsDict[i] === word1) {
101+
pos1 = i;
102+
if (word1 === word2) {
103+
pos2 = pos1;
104+
}
105+
if (pos2 !== -1) {
106+
minDistance = Math.min(minDistance, Math.abs(pos1 - pos2));
107+
}
108+
} else if (wordsDict[i] === word2) {
109+
pos2 = i;
110+
if (pos1 !== -1) {
111+
minDistance = Math.min(minDistance, Math.abs(pos1 - pos2));
112+
}
113+
}
114+
}
115+
116+
return minDistance;
117+
}
118+
119+
// Example usage:
120+
const wordsDict1: string[] = ["practice", "makes", "perfect", "coding", "makes"];
121+
const word1: string = "makes";
122+
const word2: string = "coding";
123+
console.log(shortestDistance(wordsDict1, word1, word2)); // Output: 1
124+
125+
const wordsDict2: string[] = ["practice", "makes", "perfect", "coding", "makes"];
126+
const word1Same: string = "makes";
127+
const word2Same: string = "makes";
128+
console.log(shortestDistance(wordsDict2, word1Same, word2Same)); // Output: 3
129+
```
130+
</TabItem>
131+
<TabItem value="java" label="Java">
132+
<SolutionAuthor name="@sivaprasath"/>
133+
```java
134+
public class ShortestWordDistance {
135+
public int shortestDistance(String[] wordsDict, String word1, String word2) {
136+
int pos1 = -1;
137+
int pos2 = -1;
138+
int minDistance = Integer.MAX_VALUE;
139+
140+
for (int i = 0; i < wordsDict.length; i++) {
141+
if (wordsDict[i].equals(word1)) {
142+
pos1 = i;
143+
if (word1.equals(word2)) {
144+
pos2 = pos1;
145+
}
146+
if (pos2 != -1) {
147+
minDistance = Math.min(minDistance, Math.abs(pos1 - pos2));
148+
}
149+
} else if (wordsDict[i].equals(word2)) {
150+
pos2 = i;
151+
if (pos1 != -1) {
152+
minDistance = Math.min(minDistance, Math.abs(pos1 - pos2));
153+
}
154+
}
155+
}
156+
157+
return minDistance;
158+
}
159+
160+
public static void main(String[] args) {
161+
ShortestWordDistance solution = new ShortestWordDistance();
162+
163+
String[] wordsDict1 = {"practice", "makes", "perfect", "coding", "makes"};
164+
String word1 = "makes";
165+
String word2 = "coding";
166+
System.out.println(solution.shortestDistance(wordsDict1, word1, word2)); // Output: 1
167+
168+
String[] wordsDict2 = {"practice", "makes", "perfect", "coding", "makes"};
169+
String word1Same = "makes";
170+
String word2Same = "makes";
171+
System.out.println(solution.shortestDistance(wordsDict2, word1Same, word2Same)); // Output: 3
172+
}
173+
}
174+
```
175+
</TabItem>
176+
<TabItem value="python" label="Python" >
177+
<SolutionAuthor name="@sivaprasath"/>
178+
```python
179+
def shortestDistance(wordsDict, word1, word2):
180+
pos1, pos2 = -1, -1
181+
min_distance = float('inf')
182+
183+
for i, word in enumerate(wordsDict):
184+
if word == word1:
185+
pos1 = i
186+
if word1 == word2:
187+
pos2 = pos1
188+
if pos2 != -1:
189+
min_distance = min(min_distance, abs(pos1 - pos2))
190+
191+
elif word == word2:
192+
pos2 = i
193+
if pos1 != -1:
194+
min_distance = min(min_distance, abs(pos1 - pos2))
195+
196+
return min_distance
197+
wordsDict = ["practice", "makes", "perfect", "coding", "makes"]
198+
word1 = "makes"
199+
word2 = "coding"
200+
print(shortestDistance(wordsDict, word1, word2)) # Output: 1
201+
202+
wordsDict = ["practice", "makes", "perfect", "coding", "makes"]
203+
word1 = "makes"
204+
word2 = "makes"
205+
print(shortestDistance(wordsDict, word1, word2)) # Output: 3
206+
```
207+
</TabItem>
208+
<TabItem value="cpp" label="C++">
209+
<SolutionAuthor name="@sivaprasath"/>
210+
```cpp
211+
#include <iostream>
212+
#include <vector>
213+
#include <string>
214+
#include <climits>
215+
#include <algorithm>
216+
217+
using namespace std;
218+
219+
class Solution {
220+
public:
221+
int shortestDistance(vector<string>& wordsDict, string word1, string word2) {
222+
int pos1 = -1;
223+
int pos2 = -1;
224+
int minDistance = INT_MAX;
225+
226+
for (int i = 0; i < wordsDict.size(); ++i) {
227+
if (wordsDict[i] == word1) {
228+
pos1 = i;
229+
if (word1 == word2) {
230+
pos2 = pos1;
231+
}
232+
if (pos2 != -1) {
233+
minDistance = min(minDistance, abs(pos1 - pos2));
234+
}
235+
} else if (wordsDict[i] == word2) {
236+
pos2 = i;
237+
if (pos1 != -1) {
238+
minDistance = min(minDistance, abs(pos1 - pos2));
239+
}
240+
}
241+
}
242+
243+
return minDistance;
244+
}
245+
};
246+
247+
int main() {
248+
Solution solution;
249+
250+
vector<string> wordsDict1 = {"practice", "makes", "perfect", "coding", "makes"};
251+
string word1 = "makes";
252+
string word2 = "coding";
253+
cout << solution.shortestDistance(wordsDict1, word1, word2) << endl; // Output: 1
254+
255+
vector<string> wordsDict2 = {"practice", "makes", "perfect", "coding", "makes"};
256+
string word1Same = "makes";
257+
string word2Same = "makes";
258+
cout << solution.shortestDistance(wordsDict2, word1Same, word2Same) << endl; // Output: 3
259+
260+
return 0;
261+
}
262+
```
263+
</TabItem>
264+
</Tabs>
265+
266+
### Explanation:
267+
<Tabs>
268+
<TabItem value="javascript" label="JavaScript" default>
269+
270+
- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `minDistance` is set to `Infinity` to ensure any found distance will be smaller.
271+
- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions.
272+
- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `minDistance` if the new distance is smaller.
273+
- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word.
274+
275+
</TabItem>
276+
<TabItem value="typescript" labe="TypeScript">
277+
278+
- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `minDistance` is set to `Infinity` to ensure any found distance will be smaller.
279+
- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions.
280+
- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `minDistance` if the new distance is smaller.
281+
- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word.
282+
</TabItem>
283+
<TabItem value="java" label="Java">
284+
- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `minDistance` is set to `Integer.MAX_VALUE` to ensure any found distance will be smaller.
285+
- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions.
286+
- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `minDistance` if the new distance is smaller.
287+
- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word.
288+
289+
</TabItem>
290+
<TabItem value="python" label="Python">
291+
- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `min_distance` is set to infinity to ensure any found distance will be smaller.
292+
- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions.
293+
- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `min_distance` if the new distance is smaller.
294+
- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word.
295+
</TabItem>
296+
<TabItem value="cpp" label="C++">
297+
298+
- **Initialization**: `pos1` and `pos2` are initialized to `-1` to indicate that the positions of `word1` and `word2` have not been found yet. `minDistance` is set to `INT_MAX` to ensure any found distance will be smaller.
299+
- **Single Pass**: We iterate through the list, and for each occurrence of `word1` or `word2`, we update the respective positions.
300+
- **Distance Calculation**: If both positions have been updated at least once, we calculate the distance and update `minDistance` if the new distance is smaller.
301+
- **Handling Same Words**: If `word1` is the same as `word2`, we set `pos2` to `pos1` whenever `word1` is found to ensure we calculate the distance correctly between different occurrences of the same word.
302+
</TabItem>
303+
</Tabs>
304+
305+
306+
307+
### Complexity
308+
<Tabs>
309+
<TabItem value="javascript" labe="JavaScript">
310+
311+
- **O(n)**: The solution involves a single pass through the list `wordsDict`, where `n` is the length of the list. During this pass, each element is checked and possibly used to update positions and compute distances, which are all O(1) operations.
312+
313+
- **O(1)**: The solution uses a constant amount of extra space, regardless of the input size. It only maintains a few integer variables (`pos1`, `pos2`, `minDistance`) to store indices and distances. There are no data structures whose size grows with the input.
314+
315+
</TabItem>
316+
<TabItem value="typescript" label="TypeScript">
317+
318+
- **Time Complexity**: `O(n)`
319+
- We iterate through the array `wordsDict` once, where `n` is the length of the array. Each element is processed in constant time.
320+
321+
- **Space Complexity**: `O(1)`
322+
- We use a constant amount of extra space for variables `pos1`, `pos2`, and `minDistance`. No additional data structures are used that grow with the size of the input.
323+
</TabItem>
324+
<TabItem value="java" label="Java">
325+
326+
- **Time Complexity**: `O(n)`
327+
- We iterate through the array `wordsDict` once, where `n` is the length of the array. Each element is processed in constant time.
328+
329+
- **Space Complexity**: `O(1)`
330+
- We use a constant amount of extra space for variables `pos1`, `pos2`, and `minDistance`. No additional data structures are used that grow with the size of the input.
331+
</TabItem>
332+
<TabItem value="python" label="Python">
333+
- **O(n)**: The solution involves a single pass through the list `wordsDict`, where `n` is the length of the list. In this pass, each element is checked and possibly used to update positions and compute distances, which are all O(1) operations.
334+
335+
- **O(1)**: The solution uses a constant amount of extra space, regardless of the input size. It only maintains a few integer variables (`pos1`, `pos2`, `min_distance`) to store indices and distances. There are no data structures whose size grows with the input.
336+
</TabItem>
337+
<TabItem value="cpp" label="c++">
338+
339+
- **Time Complexity**: `O(n)`
340+
- We iterate through the array `wordsDict` once, where `n` is the length of the array. Each element is processed in constant time.
341+
342+
- **Space Complexity**: `O(1)`
343+
- We use a constant amount of extra space for variables `pos1`, `pos2`, and `minDistance`. No additional data structures are used that grow with the size of the input.
344+
</TabItem>
345+
</Tabs>
346+
347+
348+
## References
349+
350+
- **LeetCode Problem:** [Shortest Word Distance-III](https://leetcode.com/problems/shortest-word-distance-iii/)
351+
352+
<h2>Author:</h2>
353+
354+
<div style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: '10px'}}>
355+
{['sivaprasath2004'].map(username => (
356+
<Author key={username} username={username} />
357+
))}
358+
</div>

0 commit comments

Comments
 (0)