Intuition
Do exactly what the problem says: keep collapsing the string into digit-sums of each size-k group until it is short enough to stop.
Explanation
Idea
There is no shortcut here. The answer is defined by a process, so we simulate that process directly. Each round chops the string into blocks of k characters, replaces every block by the string of its digit sum, joins the blocks back together, and repeats until the string is no longer than k.
Walk-through with s = "11111222223", k = 3
Round 1. Length is 11, which is greater than 3, so we do a round. Split into groups of 3 (the last group may be shorter):
"111"→ 1 + 1 + 1 = 3 →"3""112"→ 1 + 1 + 2 = 4 →"4""222"→ 2 + 2 + 2 = 6 →"6""23"→ 2 + 3 = 5 →"5"
Concatenate the pieces: "3" + "4" + "6" + "5" = "3465".
Round 2. Length is 4, still greater than 3, so we do another round. Split "3465" into groups of 3:
"346"→ 3 + 4 + 6 = 13 →"13""5"→ 5 →"5"
Concatenate: "13" + "5" = "135".
Stop. Length is now 3, which is not greater than k = 3, so we return "135".
Why a while loop
We can't predict how many rounds we need, only the stopping condition (len(s) <= k), so a while len(s) > k loop is the natural fit. Each round strictly shrinks or keeps the length small, so it always terminates.
Complexity
- Time: O(n) overall. The first round reads all n characters; every later round works on a string that is a small fraction of the previous length, so the total work is bounded by a geometric series in n.
- Space: O(n) for the rebuilt string in each round.
Implementation
class Solution {
public String digitSum(String s, int k) {
while (s.length() > k) {
StringBuilder next = new StringBuilder();
for (int i = 0; i < s.length(); i += k) {
int total = 0;
int end = Math.min(i + k, s.length());
for (int j = i; j < end; j++) {
total += s.charAt(j) - '0';
}
next.append(total);
}
s = next.toString();
}
return s;
}
}