DDSA
Advertisement

821. Shortest Distance to a Character

Time: O(n)
Space: O(n)

Approach

Two-pass L→R then R→L; each position stores distance to the nearest target character; final answer takes the minimum.

821.cs
C#
// Approach: Two-pass L→R then R→L; each position stores distance to the nearest target character; final answer takes the minimum.
// Time: O(n) Space: O(n)

public class Solution
{
    public int[] ShortestToChar(string s, char c)
    {
        int n = s.Length;
        int[] ans = new int[n];
        int prev = -n;

        for (int i = 0; i < n; ++i)
        {
            if (s[i] == c)
                prev = i;
            ans[i] = i - prev;
        }

        for (int i = prev - 1; i >= 0; --i)
        {
            if (s[i] == c)
                prev = i;
            ans[i] = Math.Min(ans[i], prev - i);
        }

        return ans;
    }
}
Advertisement
Was this solution helpful?