Monday, July 15, 2024
HomeLanguagesJavascriptJavaScript Program to Find Shortest Distance Between Two Words in an Array...

JavaScript Program to Find Shortest Distance Between Two Words in an Array of Words

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 words

Table of Content

Approach 1: Brute Force

One 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));


Output

1

Approach 2: Optimal Approach

Another 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));


Output

1

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments