09 Sept 2026Go / Python / TypeScriptEasy

Shortest Distance to a Character

Return each string position's distance to the nearest occurrence of a target character.

Pass left-to-right to measure distance from the previous target, then right-to-left to improve distances using the next target.

complexity

O(n) time and O(n) output space.

solution files

  • Go shortest-distance-to-a-character/solution.go
  • Python shortest-distance-to-a-character/solution.py
  • TypeScript shortest-distance-to-a-character/solution.ts

Solution files

Goshortest-distance-to-a-character/solution.go
package main

func shortestToChar(s string, c byte) []int {
	distance := make([]int, len(s))
	previous := -len(s)
	for index := range s {
		if s[index] == c {
			previous = index
		}
		distance[index] = index - previous
	}
	previous = 2 * len(s)
	for index := len(s) - 1; index >= 0; index-- {
		if s[index] == c {
			previous = index
		}
		if previous-index < distance[index] {
			distance[index] = previous - index
		}
	}
	return distance
}
Pythonshortest-distance-to-a-character/solution.py
class Solution:
    def shortestToChar(self, s: str, c: str) -> list[int]:
        distance = [len(s)] * len(s)
        previous = -len(s)
        for index, character in enumerate(s):
            if character == c: previous = index
            distance[index] = index - previous
        previous = class="syntax-number">2 * len(s)
        for index in range(len(s) - class="syntax-number">1, -class="syntax-number">1, -class="syntax-number">1):
            if s[index] == c: previous = index
            distance[index] = min(distance[index], previous - index)
        return distance
TypeScriptshortest-distance-to-a-character/solution.ts
function shortestToChar(s: string, c: string): number[] {
  const distance = new Array<number>(s.length).fill(s.length);
  let previous = -s.length;
  for (let index = class="syntax-number">0; index < s.length; index += class="syntax-number">1) { if (s[index] === c) previous = index; distance[index] = index - previous; }
  previous = class="syntax-number">2 * s.length;
  for (let index = s.length - class="syntax-number">1; index >= class="syntax-number">0; index -= class="syntax-number">1) { if (s[index] === c) previous = index; distance[index] = Math.min(distance[index], previous - index); }
  return distance;
}