From 0f397af3a9c89542036a12255d0f60a954f92f94 Mon Sep 17 00:00:00 2001 From: "baochau.dinh" Date: Sun, 27 Mar 2022 14:19:47 +0700 Subject: [PATCH] js-concepts: minDistance voz --- distance.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 distance.js diff --git a/distance.js b/distance.js new file mode 100644 index 0000000..22c5b24 --- /dev/null +++ b/distance.js @@ -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')); \ No newline at end of file