Sum of Digits of String After Convert
EasyPrompt
You are given a string s consisting of lowercase English letters, and an integer k. Your task is to convert the string into an integer by a special process, and then transform it by summing its digits repeatedly k times. More specifically, perform the following steps:
- Convert
sinto an integer by replacing each letter with its position in the alphabet (i.e. replace'a'with1,'b'with2, ...,'z'with26). - Transform the integer by replacing it with the sum of its digits.
- Repeat the transform operation (step 2)
ktimes in total.
For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:
- Convert:
"zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124 - Transform #1:
262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17 - Transform #2:
17 ➝ 1 + 7 ➝ 8
Return the resulting integer after performing the operations described above.
Example 1:
Input: s = "iiii", k = 1
Output: 36
Explanation:
The operations are as follows:
- Convert: "iiii" ➝ "(9)(9)(9)(9)" ➝ "9999" ➝ 9999
- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36
Thus the resulting integer is 36.
Example 2:
Input: s = "leetcode", k = 2
Output: 6
Explanation:
The operations are as follows:
- Convert: "leetcode" ➝ "(12)(5)(5)(20)(3)(15)(4)(5)" ➝ "12552031545" ➝ 12552031545
- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
- Transform #2: 33 ➝ 3 + 3 ➝ 6
Thus the resulting integer is 6.
Example 3:
Input: s = "zbax", k = 2
Output: 8
Constraints:
1 <= s.length <= 1001 <= k <= 10sconsists of lowercase English letters.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach directly simulates the process described in the problem statement. It first converts the input string s into a new, potentially very long, string of digits. Then, it iteratively calculates the sum of digits of this string k times, updating the string at each step.
Algorithm
- Create a
StringBuilderto store the numeric representation of the strings. - Iterate through
s, converting each characterctoc - 'a' + 1and appending it to theStringBuilder. - Convert the
StringBuilderto a stringnumStr. - Loop
ktimes:- Calculate the sum of digits of
numStr. - Update
numStrwith the string representation of the sum.
- Calculate the sum of digits of
- Return the final sum as an integer.
Walkthrough
The core idea is to use string manipulation to handle the large number generated in the 'convert' step.
The algorithm proceeds as follows:
- Initialize a
StringBuilderto construct the number string. - Iterate through each character of the input string
s. For each characterc, find its corresponding alphabetical position (e.g.,'a' -> 1,'b' -> 2). Append this numeric value to theStringBuilder. - After processing all characters, you will have a string, let's call it
numStr, representing the converted number. - Start a loop to perform the transformation
ktimes. - In each iteration of the loop, calculate the sum of the digits of the current
numStr. - To do this, initialize a
sumvariable to 0. Iterate through the characters ofnumStr, convert each character to its integer value, and add it tosum. - After summing the digits, update
numStrto be the string representation of the calculatedsum. - After
kiterations, the finalnumStrholds the string representation of the answer. Convert it to an integer and return.
Here is the Java implementation for this approach:
class Solution { public int getLucky(String s, int k) { StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { sb.append(c - 'a' + 1); } String numStr = sb.toString(); long sum = 0; // Perform the transformation k times for (int i = 0; i < k; i++) { sum = 0; for (char digitChar : numStr.toCharArray()) { sum += digitChar - '0'; } numStr = String.valueOf(sum); } return (int) sum; }}Complexity
Time
O(N + k * L), where N is the length of the input string `s` and L is the length of the number string. The initial conversion is O(N). The first transformation operates on a string of length up to 2N. Subsequent transformations are on much smaller numbers. The complexity is dominated by the initial conversion and the first transformation, making it effectively O(N), but with higher constant factors due to string operations.
Space
O(N), as a `StringBuilder` and string of length up to 2N are created to store the number after the initial conversion.
Trade-offs
Pros
- The logic is straightforward and directly follows the problem description, making it easy to understand and implement.
Cons
- This approach is inefficient because it involves creating a potentially large intermediate string.
- Repeated conversions between strings and numbers inside the loop add performance overhead.
This approach avoids the creation of a large intermediate string by leveraging a mathematical property: the sum of digits of a concatenated number is equal to the sum of the sums of digits of its constituent parts. For example, the sum of digits of 1234 is the same as the sum of digits of 12 plus the sum of digits of 34. This allows us to compute the result of the first transformation directly without building the string.
Algorithm
- Initialize an integer
sum = 0. - Iterate through the input string
s. For each characterc:- Calculate its value
val = c - 'a' + 1. - Add the sum of digits of
valto the totalsum.
- Calculate its value
- This completes the first transformation.
- Loop
k-1more times:- Replace
sumwith the sum of its own digits.
- Replace
- Return the final
sum.
Walkthrough
Instead of building a large string like '12552031545' and then summing its digits, we can calculate the sum of digits for each character's value as we iterate through the input string.
The algorithm is as follows:
- Initialize an integer
sumto 0. This variable will hold the result of the first transformation. - Iterate through each character
cof the input strings. - For each character, calculate its value
val = c - 'a' + 1. - Calculate the sum of the digits of
valand add it to the totalsum. Sincevalis between 1 and 26, this is a simple operation (e.g.,val / 10 + val % 10). - After the loop,
sumcontains the result of one transformation. - Now, perform the remaining
k-1transformations. Loop fromi = 1tok-1. - In each iteration, calculate the sum of digits of the current
sumand updatesumwith this new value. - After the loops complete,
sumholds the final result.
Here is the Java implementation for this optimized approach:
class Solution { public int getLucky(String s, int k) { int sum = 0; // Calculate the sum for the first transformation directly for (char c : s.toCharArray()) { int val = c - 'a' + 1; sum += (val / 10) + (val % 10); } // Perform the remaining k-1 transformations for (int i = 1; i < k; i++) { int nextSum = 0; while (sum > 0) { nextSum += sum % 10; sum /= 10; } sum = nextSum; } return sum; }}Complexity
Time
O(N), where N is the length of the input string `s`. The initial pass over the string takes O(N) time. The subsequent `k-1` transformations operate on a number that shrinks very quickly, so this part takes negligible time compared to the initial pass.
Space
O(1), as we only use a few integer variables for the calculation, requiring constant extra space regardless of the input size.
Trade-offs
Pros
- Highly efficient in both time and space.
- Avoids costly string creation and manipulation, leading to better performance.
Cons
- The logic is slightly less direct than the brute-force approach, as it relies on observing a property of digit sums.
Solutions
Solution
class Solution {public int getLucky(String s, int k) { StringBuilder sb = new StringBuilder(); for (char c : s.toCharArray()) { sb.append(c - 'a' + 1); } s = sb.toString(); while (k-- > 0) { int t = 0; for (char c : s.toCharArray()) { t += c - '0'; } s = String.valueOf(t); } return Integer.parseInt(s); }}class Solution {public: int getLucky(string s, int k) { string t; for (char c : s) t += to_string(c - 'a' + 1); s = t; while (k--) { int t = 0; for (char c : s) t += c - '0'; s = to_string(t); } return stoi(s); }};class Solution: def getLucky(self, s: str, k: int) -> int: s = '' . join(str(ord(c) - ord('a') + 1) for c in s) for _ in range(k): t = sum(int(c) for c in s) s = str(t) return int(s)Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.