Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1945. Sum of Digits of String After Convert - Leetcode Solution

Code Implementation

class Solution:
    def getLucky(self, s: str, k: int) -> int:
        # Step 1: Convert each character to its alphabet position and concatenate
        num_str = ''.join(str(ord(c) - ord('a') + 1) for c in s)
        # Step 2: Repeat k times: sum the digits
        for _ in range(k):
            num_str = str(sum(int(d) for d in num_str))
        return int(num_str)
      
class Solution {
public:
    int getLucky(string s, int k) {
        string num_str = "";
        for (char c : s) {
            num_str += to_string(c - 'a' + 1);
        }
        for (int i = 0; i < k; ++i) {
            int sum = 0;
            for (char d : num_str) {
                sum += d - '0';
            }
            num_str = to_string(sum);
        }
        return stoi(num_str);
    }
};
      
class Solution {
    public int getLucky(String s, int k) {
        StringBuilder numStr = new StringBuilder();
        for (char c : s.toCharArray()) {
            numStr.append((int)(c - 'a' + 1));
        }
        String str = numStr.toString();
        for (int i = 0; i < k; i++) {
            int sum = 0;
            for (char d : str.toCharArray()) {
                sum += d - '0';
            }
            str = Integer.toString(sum);
        }
        return Integer.parseInt(str);
    }
}
      
var getLucky = function(s, k) {
    let numStr = '';
    for (let i = 0; i < s.length; i++) {
        numStr += (s.charCodeAt(i) - 'a'.charCodeAt(0) + 1).toString();
    }
    for (let i = 0; i < k; i++) {
        let sum = 0;
        for (let d of numStr) {
            sum += Number(d);
        }
        numStr = sum.toString();
    }
    return Number(numStr);
};
      

Problem Description

Given a string s consisting of lowercase English letters and an integer k, your task is to perform the following operations:

  • First, replace every letter in s with its position in the alphabet (i.e., 'a' becomes 1, 'b' becomes 2, ..., 'z' becomes 26). Concatenate these numbers to form a new string of digits.
  • Then, k times, replace the string with the sum of its digits (treating the string as a sequence of digits, not as numbers separated by spaces).
  • Return the resulting integer after performing these operations.

For example, with s = "zbax" and k = 2:

  • 'z' → 26, 'b' → 2, 'a' → 1, 'x' → 24, so the concatenated string is "262124".
  • First transformation: 2+6+2+1+2+4 = 17 ("17").
  • Second transformation: 1+7 = 8 ("8").
The answer is 8.

Thought Process

To solve this problem, we need to break it into two main parts: character-to-number conversion and repeated digit summing. The first step is straightforward—map each character to its corresponding alphabet position and concatenate the results. The second step is to sum the digits of the resulting number k times.

At first glance, you might think of handling each letter separately or using arrays to store the positions, but since the problem asks for digit sums, it's more efficient to work with string representations of numbers. This avoids issues with large numbers and makes digit summing easy.

Brute-force would involve converting, then summing the digits in a loop, but it's already efficient since the number shrinks quickly. There's no need for advanced optimization; just careful implementation.

Solution Approach

  • Step 1: Convert Characters to Alphabet Positions
    • For each character c in s, compute ord(c) - ord('a') + 1 (or equivalent in other languages).
    • Concatenate these numbers as strings, not as numbers. For example, "abc" becomes "123", not [1,2,3].
  • Step 2: Sum Digits k Times
    • For k iterations, sum all digits in the current string.
    • After each sum, convert the result back to a string for the next iteration.
    • Repeat until k transformations are complete.
  • Step 3: Return Result
    • After k digit sums, the string will be a small number. Return it as an integer.

This approach is simple and leverages string operations for easy digit access. No extra data structures are needed.

Example Walkthrough

Let's walk through an example with s = "abc" and k = 2:

  1. Convert to Alphabet Positions:
    • 'a' → 1
    • 'b' → 2
    • 'c' → 3
    Concatenate: "1" + "2" + "3" = "123"
  2. First Transformation (Sum Digits):
    • 1 + 2 + 3 = 6
    Now, string is "6"
  3. Second Transformation (Sum Digits):
    • 6 (only one digit)
    The string remains "6"
  4. Return: 6

This matches the expected output.

Time and Space Complexity

  • Brute-force Approach:
    • Convert each character: O(n) where n = length of s.
    • Sum digits: Each time, at most O(m) where m is the number of digits (initially up to 2n, since 'z' is 26).
    • Repeat for k times: O(k * m), but m shrinks quickly after each iteration.
    • Total: O(n + k * m), but since m becomes small after the first sum, this is effectively O(n).
  • Space Complexity:
    • Storing the digit string: up to 2n characters (if all letters are 'z').
    • No extra significant space is used.
    • Total: O(n) space.

Summary

The solution is a straightforward application of string and digit manipulation. By converting each letter to its alphabet position and concatenating, then summing digits k times, we can efficiently solve the problem. The key insight is to treat the number as a string for easy digit access, and recognize that the digit sum process quickly reduces the size of the number, keeping the algorithm efficient and simple.