We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Calculate Digit Sum of a String

Number: 2361

Difficulty: Easy

Paid? No

Companies: Uber


Problem Description

Given a string s consisting of digits and an integer k, perform rounds of operations where in each round you:

  1. Divide s into consecutive groups of size k (with the last group possibly shorter).
  2. Replace each group by the string representation of the sum of its digits.
  3. Merge these sums to form a new s. Repeat the process until the length of s is less than or equal to k, then return s.

Key Insights

  • The process is a simulation: repeatedly transform the string until a termination condition is reached.
  • In each round, group the string using the given segment size k.
  • Calculate the digit sum for each group and convert it back to a string.
  • Continue until the string’s length does not exceed k, ensuring that the process converges.

Space and Time Complexity

Time Complexity: O(n * rounds) where n is the length of the string. Since each round reduces the string length significantly, the number of rounds is generally small. Space Complexity: O(n), as a new string is created in each round.


Solution

We solve the problem by simulating the transformation process:

  1. While the length of s is greater than k, iterate through the string in chunks of size k.
  2. For each chunk, compute the sum of its digits.
  3. Convert the numeric sum to a string and append it to form a new s.
  4. Once the termination condition is met (length of s <= k), return the result. The key data structure used is a plain string along with simple arithmetic operations for digit summation. This simple iterative approach efficiently solves the problem.

Code Solutions

# Python solution for Calculate Digit Sum of a String

def digitSum(s: str, k: int) -> str:
    # Continue rounds until the length of s is less than or equal to k
    while len(s) > k:
        new_s = ""  # This will store the resulting string after processing current round
        # Process the string in chunks of k characters
        for i in range(0, len(s), k):
            group = s[i:i+k]  # Extract a group of k digits (or fewer for the last group)
            # Calculate the sum of digits in the group
            group_sum = sum(int(ch) for ch in group)
            # Append the group sum (converted to string) to the new string
            new_s += str(group_sum)
        # Update s with the new string calculated from this round
        s = new_s
    return s

# Example usage:
# s = "11111222223", k = 3 should output "135"
print(digitSum("11111222223", 3))
← Back to All Questions