LeetCode in Kotlin

4036. Lexicographically Largest String After Pair Transformations

Medium

You are given an integer array nums.

For each integer x in nums, start with a string consisting of exactly x lowercase 'a' characters.

You may perform the following operation any number of times (including zero):

For example, "aa" can be replaced with "b", and "bb" can be replaced with "c". The pair "zz" cannot be replaced.

For each x, determine the lexicographically largest string that can be obtained.

Return an array of strings where the ith string is the answer for nums[i].

A string a is lexicographically larger than a string b if, at the first position where they differ, a contains a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters are equal, the longer string is lexicographically larger.

Example 1:

Input: nums = [2,5,7]

Output: [“b”,”ca”,”cba”]

Explanation:

Example 2:

Input: nums = [3,9,1]

Output: [“ba”,”da”,”a”]

Explanation:

Constraints:

Solution

class Solution {
    fun largestString(nums: IntArray): Array<String> {
        val n = nums.size
        val ans = Array<String>(n) { "" }
        for (i in 0..<n) {
            val num = nums[i]
            var mask = num and 33554431
            val zCount = num ushr 25
            val arr = CharArray(Integer.bitCount(mask) + zCount)
            for (j in 0..<zCount) {
                arr[j] = 'z'
            }
            var index = arr.size - 1
            var c = 'a'
            while (mask > 0) {
                if ((mask and 1) == 1) {
                    arr[index--] = c
                }
                c++
                mask = mask ushr 1
            }
            ans[i] = String(arr)
        }
        return ans
    }
}