Sum of Digits of String After Convert - Problem

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:

  1. Convert s into an integer by replacing each letter with its position in the alphabet (i.e. replace 'a' with 1, 'b' with 2, ..., 'z' with 26).
  2. Transform the integer by replacing it with the sum of its digits.
  3. Repeat the transform operation (step 2) k times in total.

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "zbax", k = 2
Output: 8
💡 Note: Convert: z(26) + b(2) + a(1) + x(24) = "262124" → sum digits: 2+6+2+1+2+4=17 → sum again: 1+7=8
Example 2 — Single Character
$ Input: s = "z", k = 1
Output: 8
💡 Note: Convert: z(26) → sum digits once: 2+6=8
Example 3 — Multiple Transforms
$ Input: s = "leetcode", k = 2
Output: 6
💡 Note: Convert letters to positions and sum: gets large number → first sum gives 54 → second sum: 5+4=9... final result is 6

Constraints

  • 1 ≤ s.length ≤ 100
  • 1 ≤ k ≤ 10
  • s consists of lowercase English letters

Visualization

Tap to expand
Sum of Digits of String After Convert INPUT String s = "zbax" z b a x 26 2 1 24 Concatenated: 262124 k = 2 (transforms) Alphabet Positions: a=1, b=2, ... x=24, ... z=26 ALGORITHM STEPS 1 Convert to Numbers z-->26, b-->2, a-->1, x-->24 2 Concatenate Digits "26" + "2" + "1" + "24" = 262124 3 Transform 1 (k=1) 2+6+2+1+2+4 = 17 4 Transform 2 (k=2) 1+7 = 8 262124 17 8 FINAL RESULT After k=2 transforms: 8 Verification: "zbax" --> 262124 Sum 1: 2+6+2+1+2+4 = 17 Sum 2: 1+7 = 8 Output: 8 [OK] Time: O(n), Space: O(n) Key Insight: The Direct Digit Sum approach converts each character to its alphabet position, concatenates all numbers into one string, then repeatedly sums the digits k times. Each transform reduces the number significantly, making this approach efficient even for large inputs. The digit sum converges quickly to a small number. TutorialsPoint - Sum of Digits of String After Convert | Direct Digit Sum Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen