leetcodedaybyday - Beats 100% with C++ and Beats 100% with Python3
IntuitionThe problem involves repeatedly compressing a string by summing groups of k consecutive characters. The goal is to reduce the string until its length i
# Intuition
The problem involves repeatedly compressing a string by summing groups of `k` consecutive characters. The goal is to reduce the string until its length is less than or equal to `k`. This iterative process of summing digits helps in understanding and implementing a loop-based solution.

# Approach
1. **Digit Sum Helper**:
   - Define a helper function to calculate the sum of digits for a given substring. In Python, this can be done using `sum(int(char) for char in substring)`.

2. **Iterative Compression**:
   - While the string's length exceeds `k`, process the string:
     - Divide the string into groups of `k` characters.
     - For each group, compute the sum of its digits and convert the result back to a string.
     - Concatenate these results to form the new compressed string.
   - Repeat the process until the string length is less than or equal to `k`.

3. **Output**:
   - Return the final compressed string.

# Complexity
- **Time Complexity**:
  - Each iteration processes the string by summing digits, which takes \(O(n)\), where \(n\) is the length of the current string.
  - In the worst case, the length of the string is halved in each iteration, leading to \(O(n \log(n))\).

- **Space Complexity**:
  - In Python, temporary strings and substrings take \(O(n)\) space in total. For C++, string manipulations also require similar temporary space, resulting in \(O(n)\).
---

# Code
```cpp []
class Solution {
public:
int sum(string& s){
    int n = s.size();
    int ans = 0;
    for (int i = 0; i < n; i++){
        int dig = s[i] - '0';
        ans += dig;
    }
    return ans;
}
    string digitSum(string s, int k) {
        while (s.size() > k){
            string ans = "";
            int n = s.size();
            for (int i = 0; i < n; i += k){
                string str = s.substr(i, min(k, n - i));
                int res = sum(str);
                ans += to_string(res);
            }
            s = ans;
        }
        return s;
    }
};
```

```python3 []
class Solution:
    def digitSum(self, s: str, k: int) -> str:
        def digit(substring: str) -> int:
            return sum(int(char) for char in substring)
        while len(s) > k:
            ans = ""
            for i in range(0, len(s), k):
                substring = s[i : i + k]
                res = digit(substring)
                ans += str(res)
            s = ans
        return s


```

['C++', 'Python3']