Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Shortest Distance to a Character

XPChallenge Points: 10
levelLevel: Easy

You are given a string s and a character ch that occurs at least once in s.
For each index i in the string, calculate the shortest distance between i and any occurrence of ch in s.

The distance between two indices i and j is defined as abs(i - j) (the absolute difference).

Return an array of integers answer, where answer[i] is the distance from index i to the closest occurrence of ch.

Example 1:

Input: s = "datascience", c = "e"

Output: [7, 6, 5, 4, 3, 2, 1, 0, 1, 1, 0]

Example 2:

Input: s = "aeroplane", c= "a"

Output: [0, 1, 2, 3, 2, 1, 0, 1, 2]

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result