Calculate Digit Sum of a String - Problem

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:

  • 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.
  • 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.
  • 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.

Input & Output

Example 1 — Basic Case
$ Input: s = "11111222223", k = 3
Output: "135"
💡 Note: Round 1: "111"|"112"|"222"|"23" → "3"|"4"|"6"|"5" → "3465". Round 2: "346"|"5" → "13"|"5" → "135". Length 3 ≤ k=3, so return "135".
Example 2 — Single Round
$ Input: s = "00000000", k = 3
Output: "000"
💡 Note: Round 1: "000"|"000"|"00" → "0"|"0"|"0" → "000". Length 3 ≤ k=3, so return "000".
Example 3 — No Processing Needed
$ Input: s = "123", k = 4
Output: "123"
💡 Note: Length 3 ≤ k=4, so no rounds needed. Return original string "123".

Constraints

  • 1 ≤ s.length ≤ 100
  • 1 ≤ k ≤ 100
  • s consists of only digits

Visualization

Tap to expand
Calculate Digit Sum: Complete ProcessInput:s = "11111222223", k = 3Round 1:11111222223↓ Sum digits in each group"3465"Round 2:3465↓ Sum: 13 + 5"135"Length 3 ≤ k=3 ✓
Understanding the Visualization
1
Input
String s and group size k
2
Process
Iteratively group and sum digits
3
Output
Final string when length ≤ k
Key Takeaway
🎯 Key Insight: Keep grouping digits by size k and summing until the result is short enough
Asked in
Amazon 15 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen