LeetCode in Kotlin

2399. Check Distances Between Same Letters

Easy

You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.

Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, … , 'z' -> 25).

In a well-spaced string, the number of letters between the two occurrences of the ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.

Return true if s is a well-spaced string, otherwise return false.

Example 1:

Input: s = “abaccb”, distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

Output: true

Explanation:

Note that distance[3] = 5, but since ‘d’ does not appear in s, it can be ignored.

Return true because s is a well-spaced string.

Example 2:

Input: s = “aa”, distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

Output: false

Explanation:

Constraints:

Solution

class Solution {
    fun checkDistances(s: String, distance: IntArray): Boolean {
        val seenFirstIndexYet = BooleanArray(26)
        for (idxIntoS in 0 until s.length) {
            val c = s[idxIntoS]
            if (!seenFirstIndexYet[c.code - 'a'.code]) {
                seenFirstIndexYet[c.code - 'a'.code] = true
                distance[c.code - 'a'.code] += idxIntoS
            } else {
                // seenFirstIndexYet[c - 'a']
                distance[c.code - 'a'.code] -= idxIntoS
                if (distance[c.code - 'a'.code] != -1) {
                    // early return
                    return false
                }
            }
        }
        return true
    }
}