Skip to content

Commit 41fc045

Browse files
committed
README + 243
1 parent a4ea456 commit 41fc045

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
Time spent : 10 min(See hint)
2+
3+
GIVEN: a list of words and two words word1 and word2
4+
5+
RETURNS: the shortest distance between two words in the list
6+
7+
EXAMPLES:
8+
9+
```
10+
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
11+
12+
Given word1 = “coding”, word2 = “practice”, return 3.
13+
Given word1 = "makes", word2 = "coding", return 1.
14+
```
15+
16+
17+
18+
Keeping two indices where we store the most recent locations of word1 and word2.
19+
20+
Each time we find a new occurance of one of the words, we do not need to search the entire array for the other word.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public int shortestDistance(String[] words, String word1, String word2) {
3+
int minDistance = words.length;
4+
int index1 = -1;
5+
int index2 = -1;
6+
int currentDistance = 0;
7+
for (int i = 0; i < words.length; i++) {
8+
if (words[i].equals(word1)) {
9+
index1 = i;
10+
}
11+
else if (words[i].equals(word2)) {
12+
index2 = i;
13+
}
14+
if (index1 != -1 && index2 != -1) {
15+
currentDistance = Math.abs(index2 - index1);
16+
minDistance = Math.min(minDistance, currentDistance);
17+
}
18+
}
19+
return minDistance;
20+
}
21+
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@
138138
| 134 | 238 | [Product of Array Except Self][238] | Java | Medium | 2017.11.8 | Array | |
139139
| 135 | 5 | [Longest Palindromic Substring][5] | Java | Medium | 2017.11.11 | String | |
140140
| 136 | 580 | [Count Student Number in Departments][580] | SQL | Medium | 2017.11.11 | Database | 2018.1.2 |
141-
| 137 | 243 | [Shortest Word Distance][243] | Java | Easy | 2017.11.12 | Array | |
141+
| 137 | 243 | [Shortest Word Distance][243] | Java | Easy | 2017.11.12 | Array | 2018.1.2 |
142142
| 138 | 661 | [Image Smoother][661] | Java | Easy | 2017.11.12 | Array | |
143143
| 139 | 586 | [Customer Placing the Largest Number of Orders][586] | SQL | Easy | 2017.11.12 | Database | |
144144
| 140 | 595 | [Big Countries][595] | SQL | Easy | 2017.11.12 | Database | |

0 commit comments

Comments
 (0)