Check If Digits Are Equal in String After Operations II Problem
Description
LeetCode Problem 3463.
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
swith 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:
- Initially, s = "3902"
- First operation:
- (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 = 2
- s becomes "292"
- Second operation:
- (s[0] + s[1]) % 10 = (2 + 9) % 10 = 1
- (s[1] + s[2]) % 10 = (9 + 2) % 10 = 1
- s becomes "11"
- Since the digits in "11" are the same, the output is true.
Example 2:
Input: s = "34789"
Output: false
Explanation:
- Initially, s = "34789".
- After the first operation, s = "7157".
- After the second operation, s = "862".
- After the third operation, s = "48".
- Since '4' != '8', the output is false.
Constraints:
3 <= s.length <= 10^5sconsists of only digits.
Solution
Approach: Binomial Coefficients Modulo 10
Repeatedly replacing a string by the sums of its adjacent digits (mod 10) is Pascal's triangle. After n - 2 rounds the two remaining digits are
- left = sum of
C(n-2, i) * s[i]fori = 0..n-2, - right = sum of
C(n-2, i) * s[i+1]fori = 0..n-2,
all modulo 10. With n up to 10^5 we cannot simulate the rounds, so we compute each coefficient directly.
Since 10 is not prime, compute C(m, i) modulo 2 and modulo 5 separately and combine them. Modulo 2, C(m, i) is odd exactly when i & m == i (Lucas' theorem in base 2). Modulo 5, apply Lucas' theorem in base 5 using a small table of C(a, b) for a, b < 5. The result a (mod 2) and b (mod 5) combine to (5a + 6b) mod 10. Finally compare the two sums modulo 10.
Complexity: O(n log n) time, O(1) extra space.
class Solution:
def hasSameDigits(self, s: str) -> bool:
m = len(s) - 2
c5 = [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 1, 4, 1]]
def comb(i: int) -> int:
a = 1 if (i & m) == i else 0
b, x, y = 1, m, i
while y > 0:
b = b * c5[x % 5][y % 5] % 5
x //= 5
y //= 5
return (5 * a + 6 * b) % 10
left = right = 0
for i in range(m + 1):
c = comb(i)
left += c * int(s[i])
right += c * int(s[i + 1])
return left % 10 == right % 10