Count No-Zero Pairs That Sum to N Problem
Description
LeetCode Problem 3704.
A no-zero integer is a positive integer that does not contain the digit 0 in its decimal representation.
Given an integer n, count the number of pairs (a, b) where:
aandbare no-zero integers.a + b = n
Return an integer denoting the number of such pairs.
Example 1:
Input: n = 2
Output: 1
Explanation:
The only pair is (1, 1).
Example 2:
Input: n = 3
Output: 2
Explanation:
The pairs are (1, 2) and (2, 1).
Example 3:
Input: n = 11
Output: 8
Explanation:
The pairs are (2, 9), (3, 8), (4, 7), (5, 6), (6, 5), (7, 4), (8, 3), and (9, 2). Note that (1, 10) and (10, 1) do not satisfy the conditions because 10 contains 0 in its decimal representation.
Constraints:
2 <= n <= 10^15
Solution
Approach: Digit DP
Process the digits of n from the lowest to the highest, choosing one digit for a and one for b at each position.
State: dp[carry][aliveA][aliveB], the number of ways to fill the positions handled so far.
carryis the carry coming into the current position (0 or 1).aliveXsays whether numberXis still "running". A running number must use a digit from 1 to 9 here. A finished number uses 0, which only stands for a leading zero beyond its last digit.
At each position try every allowed pair of digits (da, db) with (da + db + carry) % 10 equal to the digit of n. After the position, each number may stay running or finish (neither may finish at the lowest position, since both are positive). One extra leading 0 is appended to n so the last carry is absorbed; the answer is the count with no carry and both numbers finished.
Complexity: O(81 * L) time and O(1) space, where L is the number of digits of n.
class Solution:
def countNoZeroPairs(self, n: int) -> int:
x = n
digits = list(map(int, str(x)))[::-1]
digits.append(0) # absorb final carry
L = len(digits)
# dp[carry][aliveA][aliveB]
dp = [[[0] * 2 for _ in range(2)] for _ in range(2)]
dp[0][1][1] = 1
for pos in range(L):
ndp = [[[0] * 2 for _ in range(2)] for _ in range(2)]
target = digits[pos]
for carry in range(2):
for aliveA in range(2):
for aliveB in range(2):
ways = dp[carry][aliveA][aliveB]
if ways == 0:
continue
if aliveA:
A = [(d, 1) for d in range(1, 10)]
if pos > 0:
A.append((0, 0)) # end number here
else:
A = [(0, 0)]
if aliveB:
B = [(d, 1) for d in range(1, 10)]
if pos > 0:
B.append((0, 0))
else:
B = [(0, 0)]
for da, na in A:
for db, nb in B:
s = da + db + carry
if s % 10 != target:
continue
ndp[s // 10][na][nb] += ways
dp = ndp
return dp[0][0][0]
def countPairs(self, n: int) -> int:
return self.countNoZeroPairs(n)