-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
baochau.dinh
committed
Mar 27, 2022
1 parent
e8f040d
commit 0f397af
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
/** | ||
* A problem collected from Voz =)) | ||
* | ||
* Given an array of strings, write a function return the minimum distance between a and b in array | ||
*/ | ||
|
||
function solution(list = [], a = '', b = '') { | ||
if (list.length === 0) return -1; | ||
if (a.length === 0 || b.length === 0) return -1; | ||
|
||
let firstIdx = -1, secondIdx = -1; | ||
let minDist = list.length; | ||
|
||
for (let i = 0; i < list.length; ++i) { | ||
if (list[i] === a) { | ||
firstIdx = i | ||
minDist = Math.min(Math.abs(firstIdx - secondIdx), minDist); | ||
} else if (list[i] === b) { | ||
secondIdx = i | ||
minDist = Math.min(Math.abs(firstIdx - secondIdx), minDist); | ||
} | ||
} | ||
|
||
return minDist; | ||
} | ||
|
||
console.log(solution(["cat", "dog", "bird", "fish", "cat","duck","chicken","dog"], 'dog', 'duck')); |