# C++ Program to find the Shortest Distance to a character

C++Server Side ProgrammingProgramming

Given a string 'a' and a character 'char', the task is to print the distance of 'char' from each character of the given string. The size of the distance array is same as the size of the string, since we have to find the distance of the character from each character of the given string.

For Example

Input-1:

a = “tutorialspoint”char = “o”

Output:

[ 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3]

Explanation: In the given string, the distance of the character from each character of the given string is [3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3].

Input-2:

a = “programmer”
char = “r”

Output:

[1, 0, 1, 2, 0, 1, 2, 3, 4, 0 ]

Explanation: In the given string, the distance of 'r' from each character of the given string is [1, 0, 1, 2, 0, 1, 2, 3, 4, 0 ].

## Approach to Solve this Problem

A Brute Force approach to solve this problem is to find the position of the given character in the string and store in the array. Now iterate over the whole string as well as position array to find the minimum distance of the character in the given string.

• Take a string and a character 'char' as the input.
• A function distanceTochar(string a, char ch) takes a string and a character as an input and prints the distance of the given character from each character in the given string.
• Iterate over the string 'a' and store the position of the given character into the vector.
• Now iterate over the string and position array and calculate the distance of the character in the string.
• Print the position array.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
void shortestToChar(string a, char C) {
vector < int > pos, dist;
for (int i = 0; i < a.size(); i++) {
if (a[i] == C)
pos.push_back(i);
}
for (int i = 0; i < a.size(); i++) {
int mn = INT_MAX;
for (int j = 0; j < pos.size(); j++) {
mn = min(mn, abs(pos[j] - i));
}
dist.push_back(mn);
}
for (auto i: dist) {
cout << i << " ";
}
}
int main() {
string a = "tutorialspoint";
char ch {
'o'
};
shortestToChar(a, ch);
}

Running the above code will generate the output as,

## Output

3 2 1 0 1 2 3 3 2 1 0 1 2 3

The character 'o' in the string “tutorialspoint” is present at the index 3 and index 10. Thus, if we calculate its nearest distance from the characters before and after it, we will get the distances as [3 2 1 0 1 2 3 3 2 1 0 1 2 3].