Corresponding shortest distance in string in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of English lowercase alphabets, str, as the first argument and a single character, char, which exists in the string str, as the second argument.

Our function should prepare and return an array which, for each character in string str, contains its distance from the nearest character in the string specified by char.

For example, if the input to the function is

Input

const str = 'somestring';
const char = 's';

Output

const output = [0, 1, 2, 1, 0, 1, 2, 3, 4, 5]

Example

Following is the code −

 Live Demo

const str = 'somestring';
const char = 's';
const shortestDistance = (str = '', char = '') => {
   const res = new Array(str.length).fill(Infinity)
   let prev = Infinity
   const handleIndex = (i) => {
      if (str[i] === char) {
         prev = i
      }
      res[i] = Math.min(res[i], Math.abs(i - prev), )
   }
   for (let i = 0; i < str.length; i++) {
      handleIndex(i)
   }
   prev = Infinity
   for (let i = str.length - 1; i >= 0; i--) {
      handleIndex(i)
   }
   return res
}
console.log(shortestDistance(str, char));

Output

[ 0, 1, 2, 1, 0, 1, 2, 3, 4, 5 ]

Updated on: 24-Apr-2021

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements