LeetCode in Kotlin

3106. Lexicographically Smallest String After Operations With Constraint

Medium

You are given a string s and an integer k.

Define a function distance(s1, s2) between two strings s1 and s2 of the same length n as:

For example, distance("ab", "cd") == 4, and distance("a", "z") == 1.

You can change any letter of s to any other lowercase English letter, any number of times.

Return a string denoting the lexicographically smallest string t you can get after some changes, such that distance(s, t) <= k.

Example 1:

Input: s = “zbbz”, k = 3

Output: “aaaz”

Explanation:

Change s to "aaaz". The distance between "zbbz" and "aaaz" is equal to k = 3.

Example 2:

Input: s = “xaxcd”, k = 4

Output: “aawcd”

Explanation:

The distance between “xaxcd” and “aawcd” is equal to k = 4.

Example 3:

Input: s = “lol”, k = 0

Output: “lol”

Explanation:

It’s impossible to change any character as k = 0.

Constraints:

Solution

import kotlin.math.abs
import kotlin.math.min

@Suppress("NAME_SHADOWING")
class Solution {
    fun getSmallestString(s: String, k: Int): String {
        var k = k
        val sArray = s.toCharArray()
        for (i in sArray.indices) {
            val distToA = cyclicDistance(sArray[i], 'a')
            if (distToA <= k) {
                sArray[i] = 'a'
                k -= distToA
            } else if (k > 0) {
                sArray[i] = (sArray[i].code - k).toChar()
                k = 0
            }
        }
        return String(sArray)
    }

    private fun cyclicDistance(ch1: Char, ch2: Char): Int {
        val dist = abs(ch1.code - ch2.code)
        return min(dist, (26 - dist))
    }
}