Find the K-Beauty of a Number

Implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def divisorSubstrings(self, num: int, k: int) -> int:
        num_str = str(num)
        count = 0

        # Iterate through all substrings of length k
        for i in range(len(num_str) - k + 1):
            substring_num = int(num_str[i:i + k])

            # Check if it is a non-zero divisor of num
            if substring_num != 0 and num % substring_num == 0:
                count += 1

        return count

Explanation

  • For Input: num = 430043, k = 2
  • Substrings of Length 2: “43”, “30”, “00”, “04”, “43”
  • Valid Divisors: “43”, “43” (only these two are non-zero and divide 430043 evenly)
  • Output: 2

By counting each valid divisor individually, we address the issue with the original implementation and obtain the expected result. The complexity of the code remains the same, with a time complexity of ( O(nk) ) and a space complexity of ( O(1) ), as we are only using a constant amount of additional space.