Given an integer num
and an integer k
, the k-beauty of num
is defined as the count of distinct integers of length k
that are a contiguous substring of num
and are divisible by k
.
Given an integer num
and an integer k
, return the k-beauty of num
.
num
: A positive integer.k
: A positive integer.num
.Input: num = 240, k = 2
Output: 2
Explanation: The substrings of length 2 are "24" and "40". Both "24" and "40" are divisible by 2.
num
has length less than k
, return 0.num
contains zeros or leading zeros.k
.k
.Here’s the Python code to solve the problem:
def find_k_beauty(num: int, k: int) -> int:
num_str = str(num)
n = len(num_str)
if k > n:
return 0
k_beauty_set = set()
for i in range(n - k + 1):
substring = num_str[i:i + k]
sub_num = int(substring)
if sub_num % k == 0:
k_beauty_set.add(sub_num)
return len(k_beauty_set)
# Example usage:
num = 240
k = 2
print(find_k_beauty(num, k)) # Output: 2
O(d)
time, where d
is the number of digits in num
.n - k + 1
times, where n
is the number of digits in num
. Each iteration involves slicing the string and converting to an integer, both of which are O(k)
operations. Thus, the overall complexity of the loop is O((n - k + 1) * k)
.O(d * k)
.O(d)
for storing the string representation of the number and additional space for the set to hold unique k-beauties which, in the worst case, also holds O(d)
elements.O(d)
.Feel free to ask further clarifying questions or for additional test cases!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?