Shortest Distance to a Character(#821)

Category: Array, Two Pointer, String

๐Ÿงฉ Problem Statement

You're given a string `s` and a character `c` that is guaranteed to occur at least once in `s`. Your task is to return an array of integers โ€” where each element represents the shortest distance from the corresponding character in the string to the nearest occurrence of `c`. Distance is the absolute difference between indices.

๐Ÿ“š Examples

Input: s = "loveleetcode", c = "e"

Output: [3,2,1,0,1,0,0,1,2,2,1,0]

Explanation:

Input: s = "aaab", c = "b"

Output: [3,2,1,0]

Explanation:

๐Ÿง  Approach

### Key Idea

โ€ข First, collect all the indices where the character `c` appears and store them in an array `cIndexes`.

โ€ข Then traverse the string `s`, and for each character, compute the closest distance to any of the indices in `cIndexes`.

โ€ข Use a pointer `index` to keep track of the closest positions in `cIndexes`.

โ€ข If current index is before or at `cIndexes[index]`, use that.

โ€ข If it's after, check which of `cIndexes[index]` or `cIndexes[index + 1]` is closer and update accordingly.

This avoids brute force and leverages an efficient two-pointer technique.

๐Ÿ’ป Code

let cIndexes = [];

for (let i = 0; i < s.length; i++) {
  if (s[i] === c) {
    cIndexes.push(i);
  }
}

let distance = [];
let index = 0;

for (let i = 0; i < s.length; i++) {
  if (i <= cIndexes[index]) {
    let dist = Math.abs(i - cIndexes[index]);
    distance.push(dist);
  } else {
    if (index + 1 < cIndexes.length) {
      let dist1 = Math.abs(i - cIndexes[index]);
      let dist2 = Math.abs(i - cIndexes[index + 1]);
      if (dist2 < dist1) {
        index++;
        distance.push(dist2);
      } else {
        distance.push(dist1);
      }
    } else {
      let dist = Math.abs(i - cIndexes[index]);
      distance.push(dist);
    }
  }
}

return distance;

๐Ÿ“ˆ Complexity

Time: O(n) โ€” One pass to gather indices, one pass to calculate distances.

Space: O(n) โ€” To store both `cIndexes` and the `distance` result array.

๐ŸŽฌ Watch Explanation

๐Ÿ“Š Presentation (PPT)

๐Ÿ“ฅ Download PPT

๐Ÿ“Ž Resources