Corresponding shortest distance in string in JavaScript

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.

Problem Example

For example, if the input to the function is:

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

The expected output should be:

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

Algorithm Explanation

The solution uses a two-pass approach:

  • First pass (left to right): Calculate distance from the nearest character to the left
  • Second pass (right to left): Update distances considering characters to the right

Implementation

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));
    };
    
    // First pass: left to right
    for (let i = 0; i < str.length; i++) {
        handleIndex(i);
    }
    
    // Reset for second pass
    prev = Infinity;
    
    // Second pass: right to left
    for (let i = str.length - 1; i >= 0; i--) {
        handleIndex(i);
    }
    
    return res;
};

console.log(shortestDistance(str, char));
[ 0, 1, 2, 1, 0, 1, 2, 3, 4, 5 ]

Step-by-Step Breakdown

Let's trace through the example with string "somestring" and character "s":

// String: s o m e s t r i n g
// Index:  0 1 2 3 4 5 6 7 8 9
// 's' positions: 0, 4

// After first pass (left to right):
// Distance from left 's': [0, 1, 2, 3, 0, 1, 2, 3, 4, 5]

// After second pass (right to left):
// Final distances: [0, 1, 2, 1, 0, 1, 2, 3, 4, 5]

const example = 'somestring';
const target = 's';
const result = shortestDistance(example, target);

console.log('String:', example);
console.log('Target:', target);
console.log('Distances:', result);
String: somestring
Target: s
Distances: [ 0, 1, 2, 1, 0, 1, 2, 3, 4, 5 ]

Alternative Single Pass Solution

Here's a more intuitive approach that first finds all positions of the target character:

const shortestDistanceAlt = (str, char) => {
    // Find all positions of the target character
    const positions = [];
    for (let i = 0; i < str.length; i++) {
        if (str[i] === char) {
            positions.push(i);
        }
    }
    
    // Calculate minimum distance for each position
    const result = [];
    for (let i = 0; i < str.length; i++) {
        let minDistance = Infinity;
        for (const pos of positions) {
            minDistance = Math.min(minDistance, Math.abs(i - pos));
        }
        result.push(minDistance);
    }
    
    return result;
};

console.log(shortestDistanceAlt('somestring', 's'));
console.log(shortestDistanceAlt('hello', 'l'));
[ 0, 1, 2, 1, 0, 1, 2, 3, 4, 5 ]
[ 2, 1, 0, 0, 1 ]

Time Complexity

  • Two-pass solution: O(n) time, O(n) space
  • Alternative solution: O(n × k) where k is the number of target characters

Conclusion

The two-pass approach efficiently calculates the shortest distance to any occurrence of a target character. The algorithm ensures optimal performance by scanning the string only twice, making it suitable for large inputs.

Updated on: 2026-03-15T23:19:00+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements