{x}
blog image

Calculate Digit Sum of a String

You are given a string s consisting of digits and an integer k.

A round can be completed if the length of s is greater than k. In one round, do the following:

  1. Divide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k.
  2. Replace each group of s with a string representing the sum of all its digits. For example, "346" is replaced with "13" because 3 + 4 + 6 = 13.
  3. Merge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1.

Return s after all rounds have been completed.

 

Example 1:

Input: s = "11111222223", k = 3
Output: "135"
Explanation: 
- For the first round, we divide s into groups of size 3: "111", "112", "222", and "23".
  ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. 
  So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round.
- For the second round, we divide s into "346" and "5".
  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. 
  So, s becomes "13" + "5" = "135" after second round. 
Now, s.length <= k, so we return "135" as the answer.

Example 2:

Input: s = "00000000", k = 3
Output: "000"
Explanation: 
We divide s into "000", "000", and "00".
Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. 
s becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000".

 

Constraints:

  • 1 <= s.length <= 100
  • 2 <= k <= 100
  • s consists of digits only.

Solution Explanation

The problem asks to repeatedly calculate the digit sum of groups of size k in a string until the string's length is no longer greater than k. The solution involves iteratively applying a digit-summing operation until the termination condition is met.

Algorithm

  1. Base Case: If the length of the input string s is less than or equal to k, the string itself is returned.

  2. Iteration: If the length of s is greater than k, the following steps are performed repeatedly until the base case is reached:

    • Grouping: The string s is divided into groups of size k. The last group might be shorter than k if the length of s is not a multiple of k.
    • Digit Sum Calculation: For each group, the sum of its digits is calculated.
    • String Construction: The calculated digit sums (converted to strings) are concatenated to form a new string.
    • Update: The new string replaces the original s, and the process repeats from step 2.

Code Explanation (Python)

class Solution:
    def digitSum(self, s: str, k: int) -> str:
        while len(s) > k:
            t = []
            n = len(s)
            for i in range(0, n, k):
                x = 0
                for j in range(i, min(i + k, n)):
                    x += int(s[j])
                t.append(str(x))
            s = "".join(t)
        return s
  • The while loop continues as long as the length of s exceeds k.
  • Inside the loop:
    • t is an empty list to store the digit sums of each group.
    • The outer for loop iterates through s in steps of k, creating groups. min(i + k, n) handles the last group's potential shorter length.
    • The inner for loop calculates the sum (x) of digits in each group.
    • str(x) converts the sum to a string, which is appended to t.
    • "".join(t) concatenates the strings in t to create the new s.

Time and Space Complexity

  • Time Complexity: O(n*logk(n)), where n is the length of the input string. In each iteration, the string's length is reduced by a factor of approximately k. The loop will iterate approximately logk(n) times. The inner loops take O(n) time in total across all iterations.

  • Space Complexity: O(n) in the worst case. This is because the intermediate strings generated during the iterations could potentially be of length n in the worst case. In practice, the space usage will likely be less than O(n) because the string length reduces with each iteration.

The solutions in other languages (Java, C++, Go, TypeScript) follow a similar algorithmic approach, differing mainly in syntax and data structure usage. Their time and space complexities remain the same as the Python solution.