Given a string S and a character X where , for some . The task is to return an array of distances representing the shortest distance from the character X to every other character in the string.
Input: S = “geeksforgeeks”, X = ‘e’
Output: [1, 0, 0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2]
for S = ‘g’ nearest ‘e’ is at distance = 1 i.e. S = ‘e’.
similarly, for S = ‘e’, distance = 0.
for S = ‘o’, distance = 3 since we have S = ‘e’, and so on.
Input: S = “helloworld”, X = ‘o’
Output: [4, 3, 2, 1, 0, 1, 0, 1, 2, 3]
Approach: For each character at index i in S, let us try to find the distance to the next character X going left to right, and from right to left. The answer will be the minimum of these two values.
- When going from left to right, we remember the index of the last character X we’ve seen. Then the answer is i – prev.
- When going from right to left, the answer is prev – i.
- We take the minimum of these two answers to create our final distance array.
- Finally, print the array.
Below is the implementation of above approach:
[0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4]
- Count of character pairs at same distance as in English alphabets
- Replace every character of string by character whose ASCII value is K times more than it
- Find the count of M character words which have at least one character repeated
- Count substrings that starts with character X and ends with character Y
- Find a string such that every character is lexicographically greater than its immediate next character
- Longest Common Prefix using Character by Character Matching
- Map every character of one string to another such that all occurrences are mapped to the same character
- Replace every character of a string by a different character
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Shortest distance between a point and a circle
- Shortest distance from the centre of a circle to a chord
- Shortest distance between a Line and a Point in a 3-D plane
- Find the shortest distance between any pair of two different good nodes
- K'th Non-repeating Character
- Check if all occurrences of a character appear together
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.