How to find the shortest distance to a character in a given string using C#?

Finding the shortest distance to a character in a string requires calculating the minimum distance from each position to the nearest occurrence of the target character. This can be efficiently solved using a two-pass approach that scans the string from left to right and then from right to left.

The algorithm maintains two arrays to track distances from both directions, then combines them to find the minimum distance at each position.

Syntax

Following is the method signature for finding shortest distances −

public int[] ShortestDistanceToCharacter(string s, char c)

Parameters

  • s − The input string to search within

  • c − The target character to find distances to

Return Value

Returns an integer array where each element represents the shortest distance from that position to the nearest occurrence of the target character.

How It Works

The algorithm uses a two-pass approach:

  1. Left-to-right pass − Calculate distances from the left direction

  2. Right-to-left pass − Calculate distances from the right direction

  3. Combine results − Take the minimum distance from both arrays

Two-Pass Distance Calculation String: "lovecode" l o v e c o d e Left Pass: ? ? ? 0 1 2 3 0 Right Pass: 3 2 1 0 1 2 1 0 Result: 3 2 1 0 1 2 1 0 Left to Right Right to Left

Example

using System;
using System.Linq;

public class Arrays {
    public int[] ShortestDistanceToCharacter(string s, char c) {
        int stringLength = s.Length;
        int[] leftDis = new int[stringLength];
        int[] rightDis = new int[stringLength];
        
        // Initialize arrays
        leftDis = Enumerable.Range(0, stringLength).Select(n => int.MaxValue).ToArray();
        rightDis = Enumerable.Range(0, stringLength).Select(n => int.MaxValue).ToArray();
        
        // Left to right pass
        int count = int.MaxValue;
        for (int i = 0; i < stringLength; i++) {
            if (s[i] == c) {
                count = 0;
                rightDis[i] = count;
            }
            else {
                if (count != int.MaxValue) {
                    count++;
                    rightDis[i] = count;
                }
            }
        }
        
        // Right to left pass
        count = int.MaxValue;
        for (int i = stringLength - 1; i >= 0; i--) {
            if (s[i] == c) {
                count = 0;
                leftDis[i] = count;
            }
            else {
                if (count != int.MaxValue) {
                    count++;
                    leftDis[i] = count;
                }
            }
        }
        
        // Combine results
        int[] result = new int[stringLength];
        for (int i = 0; i < stringLength; i++) {
            result[i] = Math.Min(leftDis[i], rightDis[i]);
        }
        
        return result;
    }
}

class Program {
    static void Main(string[] args) {
        Arrays arrayProcessor = new Arrays();
        string inputString = "lovecode";
        char targetChar = 'e';
        
        var distances = arrayProcessor.ShortestDistanceToCharacter(inputString, targetChar);
        
        Console.WriteLine("String: " + inputString);
        Console.WriteLine("Target character: " + targetChar);
        Console.WriteLine("Distances: [" + string.Join(", ", distances) + "]");
    }
}

The output of the above code is −

String: lovecode
Target character: e
Distances: [3, 2, 1, 0, 1, 2, 1, 0]

Optimized Single-Pass Approach

Example

using System;

public class OptimizedArrays {
    public int[] ShortestDistanceToCharacter(string s, char c) {
        int n = s.Length;
        int[] result = new int[n];
        int lastCharPosition = -n;
        
        // Forward pass
        for (int i = 0; i < n; i++) {
            if (s[i] == c) lastCharPosition = i;
            result[i] = i - lastCharPosition;
        }
        
        // Backward pass
        for (int i = n - 1; i >= 0; i--) {
            if (s[i] == c) lastCharPosition = i;
            result[i] = Math.Min(result[i], lastCharPosition - i);
        }
        
        return result;
    }
}

class Program {
    static void Main(string[] args) {
        OptimizedArrays processor = new OptimizedArrays();
        string testString = "programming";
        char target = 'r';
        
        var distances = processor.ShortestDistanceToCharacter(testString, target);
        
        Console.WriteLine("String: " + testString);
        Console.WriteLine("Target: " + target);
        Console.WriteLine("Result: [" + string.Join(", ", distances) + "]");
    }
}

The output of the above code is −

String: programming
Target: r
Result: [1, 0, 1, 2, 0, 1, 2, 3, 4, 5, 6]

Time and Space Complexity

Approach Time Complexity Space Complexity
Two-Array Approach O(n) O(n) - uses two additional arrays
Optimized Single-Pass O(n) O(1) - only result array needed

Conclusion

Finding the shortest distance to a character can be solved efficiently using a two-pass algorithm that scans from both directions. The optimized approach reduces space complexity while maintaining the same time complexity, making it ideal for memory-constrained applications.

Updated on: 2026-03-17T07:04:36+05:30

457 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements