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

Number: 3768

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a string s consisting of digits, repeatedly perform the following operation until the string has exactly two digits: for every pair of consecutive digits, compute the sum modulo 10, and form a new string with these results in order. Return true if the final two digits are identical; otherwise, return false.


Key Insights

  • The transformation reduces the string length by 1 on each iteration.
  • Continue applying the operation until only two digits remain.
  • The operation involves calculating (digit1 + digit2) mod 10 for every consecutive digit pair.
  • Simulation of the process is straightforward given the constraints.

Space and Time Complexity

Time Complexity: O(n²) in the worst-case where n is the length of the string, due to repeatedly processing nearly the entire string as its length decreases. Space Complexity: O(n) for storing the intermediate string results.


Solution

We simulate the process of reducing the string by computing each pair’s sum modulo 10 until the string contains exactly two digits. The main data structure used is a string (or list) to hold digits, which is updated on each iteration by generating a new sequence from the previous one. The solution leverages a simple loop (or while loop) that repeatedly builds the next state based on the current digits. The approach is direct and utilizes basic arithmetic and string manipulation without requiring any advanced data structures.


Code Solutions

# Function to check if digits are equal after operations
def checkEqualDigits(s: str) -> bool:
    # Continue the operation until exactly 2 digits remain in the string
    while len(s) > 2:
        new_string = ""
        # Process each pair of consecutive digits
        for i in range(len(s) - 1):
            # Compute the sum of the pair modulo 10 and append to new_string
            computed_digit = (int(s[i]) + int(s[i+1])) % 10
            new_string += str(computed_digit)
        s = new_string  # Update s with the new computed string
    # Check if the final two digits are the same
    return s[0] == s[1]

# Example usage:
print(checkEqualDigits("3902"))  # Output: True
print(checkEqualDigits("34789")) # Output: False
← Back to All Questions