#3704

Count No-Zero Pairs That Sum to N

Hard
MathDynamic ProgrammingDigit DPBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use digit dynamic programming to count valid pairs without generating them. Track digits and carry to ensure no zeros are used.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert n to its string representation to analyze each digit.
  2. 2Step 2: Use a recursive function with memoization to count valid pairs based on current digit position and carry.
  3. 3Step 3: For each digit, calculate possible values for a and b, ensuring neither contains zero.
solution.py12 lines
1def count_no_zero_pairs(n):
2    s = str(n)
3    dp = {}  
4    def dfs(pos, carry, used_zero):
5        if pos == len(s): return 1 if not used_zero else 0
6        total = 0
7        for a in range(1, 10):
8            b = int(s[pos]) - a - carry
9            if 1 <= b < 10:
10                total += dfs(pos + 1, 1 if b < 0 else 0, used_zero or (a == 0 or b == 0))
11        return total
12    return dfs(0, 0, False)

Complexity note: The digit DP approach efficiently counts pairs without generating them, leading to linear time complexity.

  • 1Pairs must consist of digits 1-9 only.
  • 2Carry affects the next digit's calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.