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 of a String INPUT String s = "11111222223" 1 1 1 1 1 2 2 2 2 2 3 Groups (k=3): 111 112 222 23 Parameters: s = "11111222223" k = 3 Length: 11 chars 11 > k, so process ALGORITHM STEPS 1 Round 1: Split into groups "111" "112" "222" "23" 2 Sum each group 3 + 4 + 6 + 5 = "3465" 1+1+1=3 1+1+2=4 2+2+2=6 2+3=5 3 Round 2: len(4) > k(3) "346" "5" --> 13 + 5 3+4+6=13 5 = "135" 4 Check: len(3) <= k(3) Stop! Return result Condition: len(s) <= k len("135") = 3 <= 3 [OK] Time: O(n) | Space: O(n) FINAL RESULT After 2 rounds: Round 1: "11111222223" --> "3465" Round 2: "3465" --> "135" len("135") = 3 [OK] OUTPUT "135" Verification: 1+3+5 = 9 Original: 1+1+1+1+1+2+2+2+2+2+3 = 18 Key Insight: Use StringBuilder for efficient string manipulation. Each round reduces the string length significantly since digit sums compress information. The algorithm terminates when length <= k. With k=3, at most O(log n) rounds are needed as each round reduces length by factor of ~k. TutorialsPoint - Calculate Digit Sum of a String | Optimized String Building Approach
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