JavaScript Program to Find Shortest Distance Between Two Words in an Array of Words Last Updated : 22 Sep, 2023 Comments Improve Suggest changes 4 Likes Like Report Given an array of words and two target words, the task is to find the shortest distance (minimum number of words) between the two target words in the array. The distance is calculated by counting the number of words between the two target words, excluding the target words themselves. Approaches to find the shortest distance between two wordsTable of ContentBrute ForceOptimal ApproachApproach 1: Brute ForceOne straightforward approach is to iterate through the array and keep track of the indices of the two target words. Then, compute the minimum distance between the indices. Example: This example shows the use of the above-explained approach. JavaScript function shortestDistance(words, word1, word2) { let minDistance = Number.MAX_SAFE_INTEGER; let index1 = -1; let index2 = -1; let i = 0; while (i < words.length) { if (words[i] === word1) { index1 = i; minDistance = index2 !== -1 ? Math.min( minDistance, Math.abs(index1 - index2) ) : minDistance; } else if (words[i] === word2) { index2 = i; minDistance = index1 !== -1 ? Math.min( minDistance, Math.abs(index1 - index2) ) : minDistance; } i++; } return minDistance; } const wordsArray = ["apple", "banana", "orange", "apple", "kiwi", "cherry" ]; const word1 = "apple"; const word2 = "banana"; console.log(shortestDistance(wordsArray, word1, word2)); Output1 Approach 2: Optimal ApproachAnother efficient approach is to keep track of the last indices where each word appeared while traversing the array. Then, calculate the distance and update the minimum distance whenever one of the words is found. Example: This example shows the use of the above-explained approach. JavaScript function shortestDistance(words, word1, word2) { let minDistance = Number.MAX_SAFE_INTEGER; let index1 = -1; let index2 = -1; let i = 0; while (i < words.length) { if (words[i] === word1) { index1 = i; } else if (words[i] === word2) { index2 = i; } if (index1 !== -1 && index2 !== -1) { minDistance = Math.min( minDistance, Math.abs(index1 - index2) ); } i++; } return minDistance; } // Example usage: const wordsArray = [ "apple", "banana", "orange", "apple", "kiwi", "banana" ]; const word1 = "apple"; const word2 = "banana"; console.log(shortestDistance(wordsArray, word1, word2)); Output1 Create Quiz Comment S sahoopratyushkumar3 Follow 4 Improve S sahoopratyushkumar3 Follow 4 Improve Article Tags : JavaScript Web Technologies javascript-array JavaScript-DSA JavaScript-Program +1 More Explore JavaScript BasicsIntroduction to JavaScript4 min readVariables and Datatypes in JavaScript6 min readJavaScript Operators5 min readControl Statements in JavaScript4 min readArray & StringJavaScript Arrays7 min readJavaScript Array Methods7 min readJavaScript Strings5 min readJavaScript String Methods9 min readFunction & ObjectFunctions in JavaScript5 min readJavaScript Function Expression3 min readFunction Overloading in JavaScript4 min readObjects in JavaScript4 min readJavaScript Object Constructors4 min readOOPObject Oriented Programming in JavaScript3 min readClasses and Objects in JavaScript4 min readWhat Are Access Modifiers In JavaScript ?5 min readJavaScript Constructor Method7 min readAsynchronous JavaScriptAsynchronous JavaScript2 min readJavaScript Callbacks4 min readJavaScript Promise4 min readEvent Loop in JavaScript4 min readAsync and Await in JavaScript2 min readException HandlingJavascript Error and Exceptional Handling6 min readJavaScript Errors Throw and Try to Catch2 min readHow to create custom errors in JavaScript ?2 min readJavaScript TypeError - Invalid Array.prototype.sort argument1 min readDOMHTML DOM (Document Object Model)8 min readHow to select DOM Elements in JavaScript ?3 min readJavaScript Custom Events4 min readJavaScript addEventListener() with Examples9 min readAdvanced TopicsClosure in JavaScript4 min readJavaScript Hoisting6 min readScope of Variables in JavaScript3 min readJavaScript Higher Order Functions7 min readDebugging in JavaScript4 min read Like