Facebook Pixel

1317. Convert Integer to the Sum of Two No-Zero Integers

Problem Description

This problem asks you to split a positive integer n into two positive integers a and b such that both numbers are "No-Zero integers" and their sum equals n.

A No-Zero integer is defined as a positive integer that doesn't contain the digit 0 anywhere in its decimal representation. For example, 123 is a No-Zero integer, but 105 is not because it contains a 0.

Given an integer n, you need to find two positive integers a and b where:

  • Both a and b are No-Zero integers (neither contains the digit 0)
  • a + b = n
  • You return these two numbers as a list [a, b]

The problem guarantees that at least one valid solution exists for the given test cases. If multiple valid solutions exist, you can return any one of them.

For example, if n = 11, you could return [2, 9] because both 2 and 9 are No-Zero integers and 2 + 9 = 11. Another valid answer would be [3, 8] or [4, 7], etc.

The solution approach iterates through possible values of a from 1 to n-1, calculates b = n - a, and checks if both a and b are No-Zero integers by converting them to strings and checking if the character '0' appears in either string. The first valid pair found is returned.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

Since we need to find two numbers a and b that sum to n, we know that once we choose a, the value of b is automatically determined as b = n - a. This reduces our search space significantly - instead of searching for two independent numbers, we only need to search for one.

The key insight is that we can use a brute force approach because:

  1. We're guaranteed at least one valid solution exists
  2. The constraint is simple - just check if a number contains the digit 0
  3. We can stop as soon as we find the first valid pair

To check if a number is a No-Zero integer, the simplest approach is to convert it to a string and check if the character '0' appears in it. This is more straightforward than checking each digit mathematically.

Starting from a = 1 and incrementing upward makes sense because:

  • We need positive integers (so we start from 1, not 0)
  • We want to find any valid solution quickly
  • Smaller values of a mean we explore the full range systematically

For each value of a we try, we calculate b = n - a and check if both numbers are No-Zero integers by concatenating their string representations and checking for the absence of '0'. The concatenation str(a) + str(b) is a clever way to check both numbers in a single condition - if '0' is not in the concatenated string, then neither a nor b contains a zero digit.

The first pair that satisfies our condition is immediately returned, making this an efficient solution despite being brute force, as we typically find a valid answer quickly for most inputs.

Learn more about Math patterns.

Solution Approach

The solution uses a direct enumeration approach to find a valid pair of No-Zero integers that sum to n.

Algorithm Steps:

  1. Iterate through possible values of a: We loop through values from 1 to n-1. We start at 1 because we need positive integers, and we stop at n-1 because if a = n, then b would be 0, which is not a positive integer.

  2. Calculate b for each a: For each value of a, we calculate b = n - a. This ensures that a + b = n.

  3. Check if both numbers are No-Zero integers:

    • Convert both a and b to strings using str(a) and str(b)
    • Concatenate these strings: str(a) + str(b)
    • Check if the character '0' exists in the concatenated string
    • If '0' is not found, both numbers are No-Zero integers
  4. Return the first valid pair: As soon as we find a pair [a, b] where neither contains a zero digit, we immediately return it.

Implementation Details:

for a in range(1, n):           # Try each possible value of a
    b = n - a                   # Calculate corresponding b
    if "0" not in str(a) + str(b):  # Check if both are No-Zero integers
        return [a, b]           # Return first valid pair found

The string concatenation trick str(a) + str(b) allows us to check both numbers in a single condition. For example:

  • If a = 2 and b = 9, the concatenated string is "29", which doesn't contain '0'
  • If a = 10 and b = 1, the concatenated string is "101", which contains '0'

Time Complexity: O(n) in the worst case, as we might need to check up to n-1 values of a. For each check, the string conversion and search operation takes O(log n) time (proportional to the number of digits).

Space Complexity: O(log n) for the string representations of the numbers.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with n = 11:

Step 1: Start with a = 1

  • Calculate b = 11 - 1 = 10
  • Convert to strings: str(1) = "1", str(10) = "10"
  • Concatenate: "1" + "10" = "110"
  • Check for '0': "110" contains '0' ❌
  • This pair is invalid, continue

Step 2: Try a = 2

  • Calculate b = 11 - 2 = 9
  • Convert to strings: str(2) = "2", str(9) = "9"
  • Concatenate: "2" + "9" = "29"
  • Check for '0': "29" does not contain '0' ✓
  • Both 2 and 9 are No-Zero integers!
  • Return [2, 9]

The algorithm found a valid answer on the second iteration. We can verify: 2 + 9 = 11, and neither 2 nor 9 contains the digit 0.

Let's see another example with n = 101:

Step 1: a = 1, b = 100

  • Concatenate: "1100" contains '0' ❌

Step 2: a = 2, b = 99

  • Concatenate: "299" does not contain '0' ✓
  • Return [2, 99]

Even for a larger number with zeros in it (101), we quickly find that [2, 99] is a valid solution since neither 2 nor 99 contains any zero digits.

Solution Implementation

1class Solution:
2    def getNoZeroIntegers(self, n: int) -> List[int]:
3        """
4        Find two positive integers without digit '0' that sum to n.
5      
6        Args:
7            n: The target sum (2 <= n <= 10^4)
8          
9        Returns:
10            A list containing two integers [a, b] where a + b = n
11            and neither a nor b contains the digit '0'
12        """
13        # Iterate through all possible values for the first integer
14        for first_num in range(1, n):
15            # Calculate the second integer to make the sum equal to n
16            second_num = n - first_num
17          
18            # Convert both numbers to strings and concatenate them
19            combined_str = str(first_num) + str(second_num)
20          
21            # Check if the digit '0' appears in either number
22            if '0' not in combined_str:
23                # Return the valid pair as soon as we find one
24                return [first_num, second_num]
25
1class Solution {
2    /**
3     * Find two non-zero integers whose sum equals n.
4     * A non-zero integer is a positive integer that doesn't contain any 0 digit.
5     * 
6     * @param n The target sum (2 <= n <= 10^4)
7     * @return An array containing two non-zero integers [a, b] where a + b = n
8     */
9    public int[] getNoZeroIntegers(int n) {
10        // Iterate through possible values of the first integer starting from 1
11        for (int firstInteger = 1; ; firstInteger++) {
12            // Calculate the second integer as the difference
13            int secondInteger = n - firstInteger;
14          
15            // Convert both integers to strings and concatenate them
16            String concatenatedString = firstInteger + "" + secondInteger;
17          
18            // Check if the concatenated string contains the digit '0'
19            // If it doesn't contain '0', both integers are non-zero integers
20            if (!concatenatedString.contains("0")) {
21                // Return the pair of non-zero integers
22                return new int[] {firstInteger, secondInteger};
23            }
24        }
25    }
26}
27
1class Solution {
2public:
3    vector<int> getNoZeroIntegers(int n) {
4        // Iterate through all possible values of the first integer starting from 1
5        for (int firstNum = 1; ; ++firstNum) {
6            // Calculate the second integer such that their sum equals n
7            int secondNum = n - firstNum;
8          
9            // Convert both integers to strings and concatenate them
10            string combinedStr = to_string(firstNum) + to_string(secondNum);
11          
12            // Check if the concatenated string contains the digit '0'
13            // string::npos is returned when '0' is not found
14            if (combinedStr.find('0') == string::npos) {
15                // If no '0' is found in either number, return the pair
16                return {firstNum, secondNum};
17            }
18        }
19    }
20};
21
1/**
2 * Finds two non-zero integers that sum to n
3 * Non-zero integers are positive integers that don't contain the digit 0
4 * @param n - The target sum to decompose into two non-zero integers
5 * @returns An array containing two non-zero integers [a, b] where a + b = n
6 */
7function getNoZeroIntegers(n: number): number[] {
8    // Iterate through possible values of the first integer starting from 1
9    for (let firstInteger = 1; ; firstInteger++) {
10        // Calculate the second integer as the difference
11        const secondInteger = n - firstInteger;
12      
13        // Convert both integers to strings and check if they contain '0'
14        // Concatenating both numbers as strings allows checking both at once
15        const combinedString = `${firstInteger}${secondInteger}`;
16      
17        // If neither integer contains the digit '0', we found our answer
18        if (!combinedString.includes('0')) {
19            return [firstInteger, secondInteger];
20        }
21    }
22}
23

Time and Space Complexity

Time Complexity: O(n × log n)

The algorithm iterates through values from 1 to n-1 in the worst case, which gives us O(n) iterations. For each iteration, we perform:

  • Computing b = n - a: O(1)
  • Converting a to string: O(log a) since the number of digits in a is proportional to log a
  • Converting b to string: O(log b) since the number of digits in b is proportional to log b
  • Concatenating strings: O(log a + log b)
  • Checking if "0" is in the concatenated string: O(log a + log b)

Since both a and b are bounded by n, the string operations take O(log n) time per iteration. Therefore, the overall time complexity is O(n × log n).

Space Complexity: O(log n)

The space is used for:

  • Variables a and b: O(1)
  • String representation of a: O(log a)O(log n)
  • String representation of b: O(log b)O(log n)
  • Concatenated string: O(log a + log b)O(log n)

The maximum space used at any point is proportional to the number of digits in n, which is O(log n).

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Inefficient String Operations in Loop

The current solution creates new string objects in every iteration by concatenating str(first_num) + str(second_num). This can be inefficient, especially for larger values of n.

Better approach:

def getNoZeroIntegers(self, n: int) -> List[int]:
    for first_num in range(1, n):
        second_num = n - first_num
        # Check each number separately to avoid unnecessary concatenation
        if '0' not in str(first_num) and '0' not in str(second_num):
            return [first_num, second_num]

2. Not Considering Early Termination Optimization

The brute force approach always starts from 1, but we could optimize by starting from a better position or using a bidirectional search.

Optimized approach:

def getNoZeroIntegers(self, n: int) -> List[int]:
    # Start from middle and work outward for potentially faster results
    mid = n // 2
    for offset in range(mid):
        # Check both directions from middle
        for first_num in [mid - offset, mid + offset + 1]:
            if 1 <= first_num < n:
                second_num = n - first_num
                if '0' not in str(first_num) and '0' not in str(second_num):
                    return [first_num, second_num]

3. Helper Function for Clarity

The zero-checking logic is embedded in the main loop, which reduces code readability and reusability.

Cleaner approach:

def getNoZeroIntegers(self, n: int) -> List[int]:
    def has_no_zero(num):
        """Check if a number contains no zero digits"""
        return '0' not in str(num)
  
    for first_num in range(1, n):
        second_num = n - first_num
        if has_no_zero(first_num) and has_no_zero(second_num):
            return [first_num, second_num]

4. Mathematical Approach Instead of String Conversion

Converting to strings repeatedly can be avoided by using mathematical operations to check for zero digits.

Mathematical approach:

def getNoZeroIntegers(self, n: int) -> List[int]:
    def has_zero_digit(num):
        """Check if a number contains digit 0 using modulo operation"""
        while num > 0:
            if num % 10 == 0:
                return True
            num //= 10
        return False
  
    for first_num in range(1, n):
        second_num = n - first_num
        if not has_zero_digit(first_num) and not has_zero_digit(second_num):
            return [first_num, second_num]

5. Edge Case Consideration

While the problem guarantees a solution exists, defensive programming would include handling the theoretical case where no solution is found.

Defensive approach:

def getNoZeroIntegers(self, n: int) -> List[int]:
    for first_num in range(1, n):
        second_num = n - first_num
        if '0' not in str(first_num) and '0' not in str(second_num):
            return [first_num, second_num]
  
    # This should never be reached given problem constraints
    # but good practice for production code
    return [1, n-1]  # Fallback (though problem guarantees a solution)
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which data structure is used to implement priority queue?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More