LeetCode in Kotlin

2451. Odd String Difference

Easy

You are given an array of equal-length strings words. Assume that the length of each string is n.

Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25.

All the strings in words have the same difference integer array, except one. You should find that string.

Return the string in words that has different difference integer array.

Example 1:

Input: words = [“adc”,”wzy”,”abc”]

Output: “abc”

Explanation:

The odd array out is [1, 1], so we return the corresponding string, “abc”.

Example 2:

Input: words = [“aaa”,”bob”,”ccc”,”ddd”]

Output: “bob”

Explanation: All the integer arrays are [0, 0] except for “bob”, which corresponds to [13, -13].

Constraints:

Solution

class Solution {
    fun oddString(words: Array<String>): String {
        val n = words[0].length - 1
        val x = IntArray(n)
        var s = 1
        var y = 0
        var index = 1
        for (i in 0 until n) {
            x[i] = words[0][i + 1].code - words[0][i].code
        }
        var i = 1
        while (y * s == 0 || s + y < 3) {
            var b = true
            for (j in 0 until n) {
                if (x[j] != words[i][j + 1].code - words[i][j].code) {
                    b = false
                    break
                }
            }
            if (b) {
                s++
            } else {
                y++
                index = i
            }
            i++
        }
        return if (s == 1) words[0] else words[index]
    }
}