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 I

Difficulty: Easy


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 operation involves reducing the string by calculating new digits based on pairs of consecutive digits.
  • The reduction continues until the string length is exactly two.
  • To determine if the final two digits are the same, we can perform the operations iteratively.
  • The modulo operation ensures that the results are always single digits (0-9).

Space and Time Complexity

Time Complexity: O(n^2) - In the worst case, we may need to process n digits and generate n-1 new digits repeatedly until only two remain. Space Complexity: O(1) - We only use a few variables for computation, independent of the input size.


Solution

The solution involves simulating the process of reducing the string by repeatedly calculating new digits from pairs of consecutive digits. We can use a loop to continue this process until only two digits remain. The final step checks if these two digits are the same.


Code Solutions

def checkDigitsEqual(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