Talentd
FleetCode
Make and follow sheets.Sign in

Sum of Digits of String After Convert solution and explanation

EasySimulationString5 min read74.9% acceptanceUpdated 9 Apr 2026
1945. Sum of Digits of String After Convert | math | strings | Leetcode Daily ChallengeShashCode · 13:14 · 3K viewsWatch on YouTube
9 more videos on this problem
  1. 1945. Sum of Digits of String After Convert | math | strings | Leetcode Daily ChallengeShashCode · 13:14 · 3K views
  2. 1945. Sum of Digits of String After Convert (Leetcode Easy)Programming Live with Larry · 3:40 · 1K views
  3. LeetCode 1945 - Sum of Digits of String After Convert: A Microsoft JourneyThe Lofi Dev · 6:48 · 745 views
  4. Leetcode | 1945. Sum of Digits of String After Convert | Easy | Java SolutionDeveloper Docs · 6:05 · 465 views
  5. Sum of Digits of String After Convert (LeetCode 1945) (Array, Maths)CodeWithARB · 12:47 · 403 views
  6. 1945. Sum of Digits of String After Convert || Java || Leetcode || HindiCoding Sphere · 8:16 · 270 views
  7. Sum of Digits of String After Convert | LeetCode 1945 | For Beginners Easy ApproachCodeInBits · 8:37 · 211 views
  8. LeetCode 1945 - Sum of Digits of String After Convert - JavaAlpha-Code · 12:23 · 184 views
  9. LeetCode #1945: Sum of Digits of String After Convert | LeetCode DailyAnish · 5:14 · 90 views
  10. Sum of Digits of String After Convert - Leetcode 1945 - JavaCode With K5KC · 8:00 · 70 views

The 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.

For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations:

  1. Convert: "zbax" ➝ "(26)(2)(1)(24)" ➝ "262124" ➝ 262124
  2. Transform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17
  3. 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 <= 100
  • 1 <= k <= 10
  • s consists of lowercase English letters.

Approach overview

Problem Overview: You receive a lowercase string s and an integer k. Each character is converted to its alphabet position (a = 1, b = 2, … z = 26) and concatenated into a numeric string. Then you repeat the digit-sum operation k times. The goal is to return the final integer after these transformations.

Approach 1: Map and Sum Technique (O(n + k * d) time, O(n) space)

This approach directly simulates the process described in the problem. First iterate through the string and convert each character using value = c - 'a' + 1. Append these numbers to build the transformed numeric string. After that, perform the digit-sum operation k times by iterating through the digits and computing their total. The main work comes from scanning the original string once and then processing the digit string repeatedly. This approach is straightforward and mirrors the problem statement, making it easy to implement when practicing string manipulation and simulation.

Approach 2: Direct Digit Sum Accumulation (O(n + k) time, O(1) space)

The key observation: you do not need to build the intermediate numeric string. When converting characters to alphabet positions, immediately split multi-digit values and add their digits to a running sum. For example, z = 26 contributes 2 + 6. This gives the result of the first transformation directly as a digit sum. After that, repeat the digit-sum operation k - 1 times on the resulting number until all iterations are completed. Since only a few digits are processed after the first step, the remaining operations are very small. This optimized simulation avoids storing large strings and keeps space constant while still using simple iteration.

Recommended for interviews: Direct Digit Sum Accumulation is the approach most interviewers expect. It shows you spotted the optimization that eliminates the intermediate string and reduces memory usage. Implementing the basic Map and Sum simulation first demonstrates understanding of the transformation, but the optimized approach proves stronger reasoning with digit manipulation and efficient string processing.

Approach 1: Map and Sum Technique

This approach involves converting each character to its corresponding position in the alphabet and forming a numeric string. We then sum the digits of this number 'k' times to get the resulting integer.

def digit_sum(num):
    return sum(int(digit) for digit in num)

def sum_of_digits_after_convert(s, k):
    num = ''.join(str(ord(c) - ord('a') + 1) for c in s)
    for _ in range(k):
        num = str(digit_sum(num))
    return int(num)

print(sum_of_digits_after_convert('zbax', 2))
public class Solution {

    private static int digitSum(String num) {
        int sum = 0;
        for (char ch : num.toCharArray())
            sum += ch - '0';
        return sum;
    }
    
    public static int sumOfDigitsAfterConvert(String s, int k) {
        StringBuilder num = new StringBuilder();
        for (char c : s.toCharArray())
            num.append(c - 'a' + 1);

        String result = num.toString();
        while (k-- > 0) {
            int sum = digitSum(result);
            result = String.valueOf(sum);
        }

        return Integer.parseInt(result);
    }

    public static void main(String[] args) {
      System.out.println(sumOfDigitsAfterConvert("zbax", 2));
    }
}
#include <iostream>
#include <string>
using namespace std;

int digitSum(string num) {
    int sum = 0;
    for(char ch : num) 
        sum += ch - '0';
    return sum;
}

int sumOfDigitsAfterConvert(string s, int k) {
    string num = "";
    for (char c : s) 
        num += to_string(c - 'a' + 1);

    int result = 0;
    while (k--) {
        result = digitSum(num);
        num = to_string(result);
    }

    return result;
}

int main() {
    cout << sumOfDigitsAfterConvert("zbax", 2) << endl;
    return 0;
}
function digitSum(num) {
    return Array.from(num).reduce((acc, digit) => acc + parseInt(digit, 10), 0);
}

function sumOfDigitsAfterConvert(s, k) {
    let num = Array.from(s).map(c => c.charCodeAt(0) - 'a'.charCodeAt(0) + 1).join('');

    while (k-- > 0) {
        num = digitSum(num).toString();
    }

    return parseInt(num, 10);
}

console.log(sumOfDigitsAfterConvert('zbax', 2));
#include <stdio.h>
#include <string.h>

int digitSum(char *num) {
    int sum = 0;
    while (*num) { 
        sum += *num - '0';
        num++;
    }
    return sum;
}

int sumOfDigitsAfterConvert(char *s, int k) {
    char num[300] = "";
    char buffer[3];
    for (int i = 0; s[i] != '\0'; i++) {
        int val = s[i] - 'a' + 1;
        sprintf(buffer, "%d", val);
        strcat(num, buffer);
    }

    int result = 0;
    while (k--) {
        result = digitSum(num);
        sprintf(num, "%d", result);
    }

    return result;
}

int main() {
    printf("%d\n", sumOfDigitsAfterConvert("zbax", 2));
    return 0;
}
using System;
using System.Linq;

public class Solution {
    static int DigitSum(string num) {
        return num.Sum(ch => ch - '0');
    }
    public static int SumOfDigitsAfterConvert(string s, int k) {
        string num = string.Concat(s.Select(c => (c - 'a' + 1).ToString()));

        while (k-- > 0) {
            int sum = DigitSum(num);
            num = sum.ToString();
        }

        return int.Parse(num);
    }

    public static void Main() {
        Console.WriteLine(SumOfDigitsAfterConvert("zbax", 2));
    }
}

Python provides simple handling of strings and numbers. The string conversion is achieved using list comprehensions, and the repeated digit sum calculation is handled using a loop and the digit_sum function.

Complexity

Time Complexity: O(N + kM).
Space Complexity: O(M).

Try this approach in the editor

Approach 2: Direct Digit Sum Accumulation

This approach directly calculates the digit sum during the conversion of the string to a number by aggregating the sum of each digit representation, reducing the need for intermediate large integer string handling.

def sum_of_digits_after_convert(s, k):
    sum_digits = sum(int(digit) for c in s for digit in str(ord(c) - ord('a') + 1))
    for _ in range(1, k):
        sum_digits = sum(int(d) for d in str(sum_digits))
    return sum_digits

print(sum_of_digits_after_convert('zbax', 2))
public class Solution {
    public static int sumOfDigitsAfterConvert(String s, int k) {
        int sum = 0;
        for (char c : s.toCharArray()) {
            int val = c - 'a' + 1;
            while (val > 0) {
                sum += val % 10;
                val /= 10;
            }
        }

        while (--k > 0) {
            int newSum = 0;
            while (sum > 0) {
                newSum += sum % 10;
                sum /= 10;
            }
            sum = newSum;
        }

        return sum;
    }

    public static void main(String[] args) {
      System.out.println(sumOfDigitsAfterConvert("zbax", 2));
    }
}
#include <iostream>
#include <string>
using namespace std;

int sumOfDigitsAfterConvert(string s, int k) {
    int sum = 0;
    for (char c : s) {
        int val = c - 'a' + 1;
        while (val) {
            sum += val % 10;
            val /= 10;
        }
    }

    for (int i = 1; i < k; i++) {
        int newSum = 0;
        while (sum) {
            newSum += sum % 10;
            sum /= 10;
        }
        sum = newSum;
    }

    return sum;
}

int main() {
    cout << sumOfDigitsAfterConvert("zbax", 2) << endl;
    return 0;
}
function sumOfDigitsAfterConvert(s, k) {
    let sum = 0;
    for (let c of s) {
        let val = c.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
        while (val > 0) {
            sum += val % 10;
            val = Math.floor(val / 10);
        }
    }

    while (--k > 0) {
        let newSum = 0;
        while (sum > 0) {
            newSum += sum % 10;
            sum = Math.floor(sum / 10);
        }
        sum = newSum;
    }

    return sum;
}

console.log(sumOfDigitsAfterConvert('zbax', 2));
#include <stdio.h>
int sumOfDigitsAfterConvert(char *s, int k) {
    int sum = 0;
    for (int i = 0; s[i] != '\0'; i++) {
        int val = s[i] - 'a' + 1;
        while (val) {
            sum += val % 10;
            val /= 10;
        }
    }

    while (--k > 0) {
        int newSum = 0;
        while (sum) {
            newSum += sum % 10;
            sum /= 10;
        }
        sum = newSum;
    }

    return sum;
}

int main() {
    printf("%d\n", sumOfDigitsAfterConvert("zbax", 2));
    return 0;
}
using System;

public class Solution {
    public static int SumOfDigitsAfterConvert(string s, int k) {
        int sum = 0;
        foreach (var c in s) {
            int val = c - 'a' + 1;
            while (val > 0) {
                sum += val % 10;
                val /= 10;
            }
        }

        while (--k > 0) {
            int newSum = 0;
            while (sum > 0) {
                newSum += sum % 10;
                sum /= 10;
            }
            sum = newSum;
        }
        return sum;
    }

    public static void Main() {
        Console.WriteLine(SumOfDigitsAfterConvert("zbax", 2));
    }
}

Python's flexible handling allows compact code for direct digit sum manipulation, using nested loops to achieve immediate conversion and summation of digits.

Complexity

Time Complexity: O(N + k*logM).
Space Complexity: O(1).

Try this approach in the editor

Approach 3: Simulation

We can simulate the process described in the problem.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string s.

function getLucky(s: string, k: number): number {
    let ans = '';
    for (const c of s) {
        ans += c.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
    }
    for (let i = 0; i < k; i++) {
        let t = 0;
        for (const v of ans) {
            t += Number(v);
        }
        ans = `${t}`;
    }
    return Number(ans);
}
func getLucky(s string, k int) int {
	var t strings.Builder
	for _, c := range s {
		t.WriteString(strconv.Itoa(int(c - 'a' + 1)))
	}
	s = t.String()
	for k > 0 {
		k--
		t := 0
		for _, c := range s {
			t += int(c - '0')
		}
		s = strconv.Itoa(t)
	}
	ans, _ := strconv.Atoi(s)
	return ans
}
impl Solution {
    pub fn get_lucky(s: String, k: i32) -> i32 {
        let mut ans = String::new();
        for c in s.as_bytes() {
            ans.push_str(&(c - b'a' + 1).to_string());
        }
        for _ in 0..k {
            let mut t = 0;
            for c in ans.as_bytes() {
                t += (c - b'0') as i32;
            }
            ans = t.to_string();
        }
        ans.parse().unwrap()
    }
}
class Solution {
    /**
     * @param String $s
     * @param Integer $k
     * @return Integer
     */
    function getLucky($s, $k) {
        $rs = '';
        for ($i = 0; $i < strlen($s); $i++) {
            $num = ord($s[$i]) - 96;
            $rs = $rs . strval($num);
        }
        while ($k != 0) {
            $sum = 0;
            for ($j = 0; $j < strlen($rs); $j++) {
                $sum += intval($rs[$j]);
            }
            $rs = strval($sum);
            $k--;
        }
        return intval($rs);
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Map and Sum Technique

Time Complexity: O(N + kM).
Space Complexity: O(M).

Direct Digit Sum Accumulation

Time Complexity: O(N + k*logM).
Space Complexity: O(1).

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Map and Sum TechniqueO(n + k * d)O(n)When implementing the problem exactly as described or when learning basic string-to-number transformations.
Direct Digit Sum AccumulationO(n + k)O(1)Best for interviews and production code where avoiding extra string storage improves efficiency.

Frequently asked questions

Is Sum of Digits of String After Convert easy or hard?

Sum of Digits of String After Convert is classified as an Easy problem on LeetCode with a high acceptance rate of around 75%. It mainly tests string traversal, digit manipulation, and simple simulation logic rather than advanced data structures or algorithms.

Sum of Digits of String After Convert Python/Java solution

The solution in Python or Java typically iterates through the string, converts characters using ASCII arithmetic (c - 'a' + 1), and accumulates digit sums. After computing the initial sum, a loop runs k − 1 times to repeatedly sum the digits of the current number.

How to solve Sum of Digits of String After Convert in O(n)?

Convert each character to its alphabet position and immediately add the digits of that number to a running total. This effectively performs the first transformation without building a string. Then repeat the digit-sum operation on the resulting number for the remaining k − 1 iterations.

What is the best approach for Sum of Digits of String After Convert?

Direct Digit Sum Accumulation is the best approach. Instead of building the full numeric string after converting characters, you immediately add the digits of each character’s alphabet value. This reduces memory usage and keeps the complexity at O(n + k) time with O(1) space.

Is Sum of Digits of String After Convert asked at Google/Amazon/Meta?

This problem is categorized as an easy string and simulation problem on LeetCode and is commonly used in early interview rounds or coding assessments. Companies like Amazon and other tech firms often include similar string transformation or digit manipulation questions to test basic algorithmic thinking.

What data structure is used in Sum of Digits of String After Convert?

No complex data structure is required. The problem mainly uses string traversal and integer arithmetic. The optimized solution relies on simple digit processing and a running sum variable, making it a simulation-style problem.

What is the time complexity of Sum of Digits of String After Convert?

The optimal solution runs in O(n + k) time, where n is the length of the input string and k is the number of digit-sum transformations. The string is processed once for character conversion, and each remaining transformation operates on a small integer with only a few digits.

Comments

Now write it yourselfClose this page and solve Sum of Digits of String After Convert in the editor, without looking.
Practise Sum of Digits of String After Convert