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

Check If Digits Are Equal in String After Operations II

Difficulty: Hard


Problem Description

You are given a string s consisting of digits. Perform the following operation repeatedly until the string has exactly two digits:

  • For each pair of consecutive digits in s, starting from the first digit, calculate a new digit as the sum of the two digits modulo 10.
  • Replace s with the sequence of newly calculated digits, maintaining the order in which they are computed.

Return true if the final two digits in s are the same; otherwise, return false.


Key Insights

  • The operations reduce the length of the string by 1 with each iteration.
  • The new digits are derived from the modulo operation, which means we only care about the last digit of the sum of two digits.
  • The process will continue until the string is reduced to exactly two digits, allowing a final comparison.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input string s. Each operation processes all current digits once, and the total number of operations is proportional to the initial length of s.

Space Complexity: O(1), as we are reusing the input string for transformations and not using additional space proportional to the input size.


Solution

To solve this problem, we will iteratively transform the string by calculating the sum of each pair of consecutive digits modulo 10. We will continue this process until only two digits remain in the string. Finally, we will compare these two digits to determine if they are equal.

  1. Start with the input string s.
  2. While the length of s is greater than 2:
    • Create a new string that will hold the results of the current transformation.
    • Iterate through the string and calculate the new digits based on the sum of each pair of consecutive digits modulo 10.
  3. After reducing s to two digits, compare these two digits.
  4. Return true if they are equal, otherwise return false.

Code Solutions

def checkEqualDigits(s: str) -> bool:
    while len(s) > 2:
        new_s = []
        for i in range(len(s) - 1):
            new_digit = (int(s[i]) + int(s[i + 1])) % 10
            new_s.append(str(new_digit))
        s = ''.join(new_s)
    return s[0] == s[1]
← Back to All Questions