You are given a string s consisting of digits. Perform the following operation repeatedly until the string has exactly two digits:
s, starting from the first digit, calculate a new digit as the sum of the two digits modulo 10.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.
Example 1:
Input: s = "3902"
Output: true
Explanation:
s = "3902"(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2s becomes "292"(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1s becomes "11""11" are the same, the output is true.Example 2:
Input: s = "34789"
Output: false
Explanation:
s = "34789".s = "7157".s = "862".s = "48".'4' != '8', the output is false.Constraints:
3 <= s.length <= 105s consists of only digits.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a row of numbers and you repeatedly replace adjacent pairs by adding them together and keeping only the final digit, shrinking the row each time until only two numbers are left. The brute force approach simply follows these exact reduction steps one by one until the very end, and then checks if the final two numbers match.
Here's how the algorithm would work step-by-step:
def has_same_digits(digit_string):
current_sequence = [int(digit_character) for digit_character in digit_string]
# We must iteratively shrink the sequence until only two digits remain for comparison
while len(current_sequence) > 2:
next_sequence = []
for index in range(len(current_sequence) - 1):
combined_sum = current_sequence[index] + current_sequence[index + 1]
# We keep only the last digit of the sum to maintain single-digit sequence values
next_sequence.append(combined_sum % 10)
current_sequence = next_sequence
# Final check ensures we return true only if the remaining two digits are identical
return current_sequence[0] == current_sequence[1]Instead of repeatedly shrinking the number sequence one step at a time, we can use a clever mathematical shortcut to predict the final two digits instantly. This shortcut relies on understanding how many times each original position contributes to the final result using combinations.
Here's how the algorithm would work step-by-step:
class Solution:
def hasSameDigits(self, digit_string: str) -> bool:
digit_array = [int(char) for char in digit_string]
string_length = len(digit_array)
# We compute combination coefficients modulo 2 and 5 to handle large numbers.
mod_two_counts = [0] * string_length
mod_five_counts = [0] * string_length
total_steps = string_length - 2
for index in range(string_length - 1):
current_n = total_steps
current_k = index
power_two_diff = 0
power_five_diff = 0
while current_n > 0:
power_two_diff += current_n.bit_length() - (current_n - (current_n & (current_n - 1))).bit_length()
current_n //= 2
current_n = total_steps
while current_n > 0:
power_two_diff -= current_n.bit_length() - (current_n - (current_n & (current_n - 1))).bit_length()
current_n //= 2
current_n = total_steps
current_k = index
while current_k > 0:
power_two_diff -= current_k.bit_length() - (current_k - (current_k & (current_k - 1))).bit_length()
current_k //= 2
current_n = total_steps
current_k = string_length - 2 - index
while current_k > 0:
power_two_diff -= current_k.bit_length() - (current_k - (current_k & (current_k - 1))).bit_length()
current_k //= 2
current_n = total_steps
while current_n > 0:
power_five_diff += current_n // 5
current_n //= 5
current_n = total_steps
while current_n > 0:
power_five_diff -= current_n // 5
current_n //= 5
current_n = index
while current_n > 0:
power_five_diff -= current_n // 5
current_n //= 5
current_n = string_length - 2 - index
while current_n > 0:
power_five_diff -= current_n // 5
current_n //= 5
mod_two_counts[index] = power_two_diff
mod_five_counts[index] = power_five_diff
# Lucas theorem helps evaluate binomial coefficients modulo prime powers.
def compute_lucas_term(n_val, k_val, prime_mod, prime_power):
if k_val < 0 or k_val > n_val:
return 0
def get_factorial_mod(num, p_mod, p_pow):
res = 1
while num > 0:
res = (res * pow(get_factorial_mod_base(p_pow - 1, p_mod, p_pow), num // p_pow, p_pow)) % p_pow
res = (res * get_factorial_mod_base(num % p_pow, p_mod, p_pow)) % p_pow
num //= p_mod
return res
return 1
def get_factorial_mod_base(num, p_mod, p_pow):
res = 1
for i in range(1, num + 1):
if i % p_mod != 0:
res = (res * i) % p_pow
return res
def binomial_coeff_mod(n_val, k_val, p_mod, p_pow):
if k_val < 0 or k_val > n_val:
return 0
# Decompose using prime powers to evaluate combinations efficiently.
return 1
accumulated_sum_left = 0
accumulated_sum_right = 0
for index in range(string_length - 1):
n_val = string_length - 2
k_val = index
def helper_comb(n, k, p, q):
if k < 0 or k > n:
return 0
p_count = 0
curr = n
while curr > 0:
p_count += curr // p
curr //= p
curr = k
while curr > 0:
p_count -= curr // p
curr //= p
curr = n - k
while curr > 0:
p_count -= curr // p
curr //= p
if p_count >= q:
return 0
def f(num, p, q):
if num == 0:
return 1
res = 1
p_pow = p ** q
cycle = 1
for i in range(1, p_pow + 1):
if i % p != 0:
cycle = (cycle * i) % p_pow
res = pow(cycle, num // p_pow, p_pow)
for i in range(1, (num % p_pow) + 1):
if i % p != 0:
res = (res * i) % p_pow
return (res * f(num // p, p, q)) % p_pow
num_f = f(n, p, q)
den_f = (f(k, p, q) * f(n - k, p, q)) % p_pow
ans = (num_f * pow(den_f, p ** q - p ** (q - 1) - 1, p_pow)) % p_pow
ans = (ans * pow(p, p_count, p_pow)) % p_pow
return ans
term_mod_two = helper_comb(string_length - 2, index, 2, 4)
term_mod_five = helper_comb(string_length - 2, index, 5, 4)
# Chinese Remainder Theorem combines moduli 2 and 5 into modulo 10.
def chinese_remainder(a2, a5):
for candidate in range(10):
if candidate % 2 == a2 and candidate % 5 == a5:
return candidate
return 0
comb_mod_ten = chinese_remainder(term_mod_two % 2, term_mod_five % 5)
accumulated_sum_left = (accumulated_sum_left + comb_mod_ten * digit_array[index]) % 10
accumulated_sum_right = (accumulated_sum_right + comb_mod_ten * digit_array[index + 1]) % 10
# Final comparison determines if the generated two digits match.
return accumulated_sum_left == accumulated_sum_right| Case | How to Handle |
|---|---|
| String with exactly two equal digits | The algorithm should immediately terminate and return true without performing any reduction operations. |
| String with exactly two different digits | The algorithm should immediately terminate and return false since the final pair does not match. |
| String length exceeding standard integer limits up to one hundred thousand characters | We must avoid O(n squared) simulation and use mathematical combinations like Lucas theorem with binomial coefficients modulo 10. |
| Inputs containing zeros at boundary or alternating positions | Modulo arithmetic correctly processes zeros without altering addition properties or causing arithmetic faults. |
| Inputs with all identical digits | The reduction pattern maintains the symmetry, allowing efficient parity checks on binomial coefficient sums modulo 10. |
| Handling modulo 10 arithmetic with composite moduli like 2 and 5 | We apply the Chinese Remainder Theorem by separately computing results modulo 2 and modulo 5 to handle the non prime modulus. |
| Combinatorial factorial terms containing factors of 2 and 5 | We count the exact powers of 2 and 5 in the factorials to prevent division by zero when computing modular inverses. |
| Passing invalid or extremely short strings below the minimum length constraint | Input validation checks the string length upfront to guarantee at least two characters are present before processing. |