2269. Find the K-Beauty of a Number
Description
The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions:
- It has a length of
k. - It is a divisor of
num.
Given integers num and k, return the k-beauty of num.
Note:
- Leading zeros are allowed.
0is not a divisor of any value.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: num = 240, k = 2 Output: 2 Explanation: The following are the substrings of num of length k: - "24" from "240": 24 is a divisor of 240. - "40" from "240": 40 is a divisor of 240. Therefore, the k-beauty is 2.
Example 2:
Input: num = 430043, k = 2 Output: 2 Explanation: The following are the substrings of num of length k: - "43" from "430043": 43 is a divisor of 430043. - "30" from "430043": 30 is not a divisor of 430043. - "00" from "430043": 0 is not a divisor of 430043. - "04" from "430043": 4 is not a divisor of 430043. - "43" from "430043": 43 is a divisor of 430043. Therefore, the k-beauty is 2.
Constraints:
1 <= num <= 1091 <= k <= num.length(takingnumas a string)
Solutions
Solution 1: Enumeration
Thinking
The \(k\)-beauty counts length-\(k\) substrings that divide the number. \(num \le 10^9\) has few digits, so converting every window of length \(k\) is enough; skip a zero divisor.
Stringify \(num\) and take \(s[i:i+k]\) at each start.
We can convert \(num\) to a string \(s\), then enumerate all substrings of \(s\) with length \(k\), convert them to an integer \(t\), and check if \(t\) is divisible by \(num\). If it is, we increment the answer.
The time complexity is \(O(\log num \times k)\), and the space complexity is \(O(\log num + k)\).
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |
Solution 2: Sliding Window
Thinking
Solution 1 rebuilds an integer from a slice each time. A decimal window can drop the low digit and insert a new high digit in \(O(1)\).
Extract the lowest \(k\) digits as \(x\), then repeatedly divide \(x\) by \(10\) and add the next digit at the top, testing divisibility as we go.
We can maintain a sliding window of length \(k\). Initially, the window contains the lowest \(k\) digits of \(num\). Then, for each iteration, we move the window one digit to the right, update the number in the window, and check if the number in the window is divisible by \(num\). If it is, we increment the answer.
The time complexity is \(O(\log num)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |