IRAMIACADEMY Picture it. Then code it.
Problem 2243Easy

Calculate Digit Sum of a String

String · Simulation

Running group sum

solution.py
class Solution:
    def digitSum(self, s, k):
        while len(s) > k:
            next_s = ""
            group_sum = 0
            for i, ch in enumerate(s):
                group_sum += int(ch)
                if (i + 1) % k == 0 or i == len(s) - 1:
                    next_s += str(group_sum)  # may add 2+ digits
                    group_sum = 0  # next group starts fresh
            s = next_s
        return s
Time O(n · R)Space O(n)

The code from the episode, ready for LeetCode's Python 3 editor: paste it in and submit.

The idea

A letterpress turns digit sums into fresh blocks, then gathers them into new batches across the old joins. Follow the print job to see why each round needs fresh grouping and when the machine stops.

Check our socials
Another way: Literal simulation
solution.py
class Solution:
    def digitSum(self, s, k):
        while len(s) > k:
            # Step 1: cut s into k-char groups.
            groups = []
            for start in range(0, len(s), k):
                groups.append(s[start:start + k])
            # Step 2: sum each group's digits.
            sums = []
            for group in groups:
                total = 0
                for ch in group:
                    total += int(ch)
                sums.append(str(total))
            # Step 3: glue the sums together.
            s = "".join(sums)
        return s
Time O(n · R)Space O(n)