Lexicographically Largest String After Pair Transformations Problem
Description
LeetCode Problem 4036.
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):
- Choose two adjacent equal letters and replace them with the next letter in the alphabet.
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 i^th 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:
- nums[0] = 2: "aa" → "b".
- nums[1] = 5: "aaaaa" → "baaa" → "bba" → "ca".
- nums[2] = 7: "aaaaaaa" → "baaaaa" → "bbaaa" → "bbba" → "cba".
- Therefore, ans = ["b", "ca", "cba"].
Example 2:
Input: nums = [3,9,1]
Output: ["ba","da","a"]
Explanation:
- nums[0] = 3: "aaa" → "ba".
- nums[1] = 9: "aaaaaaaaa" → "baaaaaaa" → "bbaaaaa" → "bbbaaa" → "bbbba" → "cbba" → "cca" → "da".
- nums[2] = 1: No transformation can be applied, so the result is "a".
- Therefore, ans = ["ba", "da", "a"].
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^8
Solution
Approach: Greedy on the binary representation
Merging two equal adjacent letters turns 2 copies of a letter into one of the next letter, so the letter 'a' + j is worth 2^j copies of 'a'. The strings reachable from x letters 'a' are therefore the ones whose letter values add up to x.
For the lexicographically largest string, use the biggest letters first. Go through j from 25 ('z', worth 2^25) down to 0, append t = x >> j copies of the letter 'a' + j, and keep only the low j bits of x. For j < 25 we have t at most 1, so the string is the binary representation of x written as letters from high to low, and only 'z' can repeat; since "zz" cannot be merged, the result is valid and no larger string exists.
Complexity: time O(n log M), space O(log M) besides the output, where n = nums.length and M is the largest value.
class Solution:
def largestString(self, nums: List[int]) -> List[str]:
ans = []
for x in nums:
s = []
for j in range(25, -1, -1):
t = x >> j
s.append(chr(ord('a') + j) * t)
x &= (1 << j) - 1
ans.append(''.join(s))
return ans