Skip to content

Commit

Permalink
js-concepts: minDistance voz
Browse files Browse the repository at this point in the history
  • Loading branch information
baochau.dinh committed Mar 27, 2022
1 parent e8f040d commit 0f397af
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions distance.js
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'));

0 comments on commit 0f397af

Please sign in to comment.