[LeetCode] Lexicographically Largest String After Pair Transformations

4036. Lexicographically Largest String After Pair Transformations

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
string helper(int x) {
char ch = 'a';
string res = "";
while(x) {
if(ch == 'z') return string(x, 'z') + res;
if(x & 1) {
res = ch + res;
}
x /= 2;
ch++;
}
return res;
}
public:
vector<string> largestString(vector<int>& nums) {
vector<string> res;
for(auto& n : nums) res.push_back(helper(n));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/03/PS/LeetCode/lexicographically-largest-string-after-pair-transformations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.