Skip to content

Commit 0f397af

Browse files
author
baochau.dinh
committed
js-concepts: minDistance voz
1 parent e8f040d commit 0f397af

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

distance.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* A problem collected from Voz =))
3+
*
4+
* Given an array of strings, write a function return the minimum distance between a and b in array
5+
*/
6+
7+
function solution(list = [], a = '', b = '') {
8+
if (list.length === 0) return -1;
9+
if (a.length === 0 || b.length === 0) return -1;
10+
11+
let firstIdx = -1, secondIdx = -1;
12+
let minDist = list.length;
13+
14+
for (let i = 0; i < list.length; ++i) {
15+
if (list[i] === a) {
16+
firstIdx = i
17+
minDist = Math.min(Math.abs(firstIdx - secondIdx), minDist);
18+
} else if (list[i] === b) {
19+
secondIdx = i
20+
minDist = Math.min(Math.abs(firstIdx - secondIdx), minDist);
21+
}
22+
}
23+
24+
return minDist;
25+
}
26+
27+
console.log(solution(["cat", "dog", "bird", "fish", "cat","duck","chicken","dog"], 'dog', 'duck'));

0 commit comments

Comments
 (0)