
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 ]
Advertisements