Shortest Distance to a Character

Here’s another tricky easy LC problem.

class Solution {
    fun shortestToChar(S: String, C: Char): IntArray {
        var tempIndex = Integer.MAX_VALUE
        return S.mapIndexed { index, i ->
                val nearest = S.indexOf(C, index)
                if(i == C) {
                    tempIndex = index
                    0
                }else {
                    val d1 = Math.abs(index - nearest)
                    val d2 = Math.abs(index - tempIndex)
                    Math.min(d1, d2)
                }
        }.toIntArray()
        
    }
}
Runtime: 192 ms, faster than 23.08% of Kotlin online submissions for Shortest Distance to a Character.
Memory Usage: 36.2 MB, less than 100.00% of Kotlin online submissions for Shortest Distance to a Character.

The idea here is to find the nearest C from the current index using indexOf and remembering the last location of C. indexOf will search the right section and the last location will take care of the left section. The remaining code is just comparing the distance of each index with respect to their left and right occurences of C.

comments powered by Disqus