Find the K-Beauty of a Number - Problem

The k-beauty of an integer is a fascinating concept that combines string manipulation with mathematical divisibility!

Given an integer num and a positive integer k, we need to find how many k-length substrings of num (when treated as a string) are actual divisors of the original number.

Rules:

  • Each substring must have exactly k characters
  • The substring (as an integer) must divide num evenly
  • Leading zeros are allowed in substrings
  • Zero is never considered a divisor

Example: For num = 240 and k = 2, we check substrings "24", "40". Since 240 รท 24 = 10 and 240 รท 40 = 6 (both integers), the k-beauty is 2.

Input & Output

example_1.py โ€” Basic Case
$ Input: num = 240, k = 2
โ€บ Output: 2
๐Ÿ’ก Note: The 2-length substrings of "240" are "24" and "40". Both 24 and 40 divide 240 evenly (240รท24=10, 240รท40=6), so the k-beauty is 2.
example_2.py โ€” Single Digit
$ Input: num = 430, k = 3
โ€บ Output: 2
๐Ÿ’ก Note: The only 3-length substring of "430" is "430" itself. Since 430รท430=1, it divides evenly, so the k-beauty is 1.
example_3.py โ€” With Zeros
$ Input: num = 1012, k = 3
โ€บ Output: 0
๐Ÿ’ก Note: The 3-length substrings are "101" and "012". 1012รท101โ‰ˆ10.02 (not integer) and "012"=12, but 1012รท12โ‰ˆ84.33 (not integer). No valid divisors, so k-beauty is 0.

Constraints

  • 1 โ‰ค num โ‰ค 109
  • 1 โ‰ค k โ‰ค num.length
  • Leading zeros in substrings are allowed
  • Zero is never considered a valid divisor

Visualization

Tap to expand
K-Beauty Algorithm: Finding Divisor SubstringsExample: num = 240, k = 2Step 1: String Representation240index 0index 1index 2Step 2: Window Position 0 (substring "24")24024 divides 240? 240 รท 24 = 10 โœ“โœ“Step 3: Window Position 1 (substring "40")24040 divides 240? 240 รท 40 = 6 โœ“โœ“Final Result: K-Beauty = 2
Understanding the Visualization
1
Setup
Convert number to string for easy character access
2
Slide Window
Move window of size k from left to right
3
Extract & Test
Extract substring, convert to int, test divisibility
4
Count Valid
Increment counter for each valid divisor found
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window approach efficiently checks all possible k-length substrings in linear time, making it perfect for this divisibility problem.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 5
28.2K Views
Medium Frequency
~12 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen