

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 ]
- Related Questions & Answers
- Shortest distance between objects in JavaScript
- Shortest Word Distance II in C++
- Shortest Word Distance III in C++
- Shortest Distance to Target Color in C++
- Shortest Distance from All Buildings in C++
- Finding shortest word in a string in JavaScript
- Find the shortest string in an array - JavaScript
- Finding hamming distance in a string in JavaScript
- How to find the shortest distance to a character in a given string using C#?
- Distance to nearest vowel in a string - JavaScript
- Find Shortest distance from a guard in a Bankin Python
- C++ code to get shortest distance from circular stations
- Get the longest and shortest string in an array JavaScript
- Program to find distance of shortest bridge between islands in Python
- Program to Find the Shortest Distance Between Two Points in C++
Advertisements