Find the K-Beauty of a Number - Problem

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.
  • 0 is not a divisor of any value.

A substring is a contiguous sequence of characters in a string.

Input & Output

Example 1 — Basic Case
$ Input: num = 240, k = 2
Output: 2
💡 Note: Substrings of length 2: "24" and "40". Both 24 and 40 divide 240 evenly, so k-beauty is 2.
Example 2 — With Leading Zero
$ Input: num = 430, k = 2
Output: 1
💡 Note: Substrings: "43", "30". 430 ÷ 43 = 10 (exact division), but 430 ÷ 30 = 14.333... (not exact). Only "43" divides evenly, so k-beauty is 1.
Example 3 — No Valid Divisors
$ Input: num = 123, k = 3
Output: 1
💡 Note: Only substring is "123". Since 123 ÷ 123 = 1, it divides itself, so k-beauty is 1.

Constraints

  • 1 ≤ num ≤ 109
  • 1 ≤ k ≤ num.length

Visualization

Tap to expand
K-Beauty of a Number INPUT Number as String: 2 idx 0 4 idx 1 0 idx 2 K=2 Substrings: "24" = 24 "40" = 40 Input Values: num = 240 k = 2 ALGORITHM STEPS 1 Convert to String 240 --> "240" 2 Extract Substrings Length k=2 windows 3 Check Divisibility num % substring == 0? 4 Count Valid Skip zeros, count divisors Divisibility Check: Sub 240 % n Valid? 24 240%24=0 OK 40 240%40=0 OK FINAL RESULT Valid K-Beauty Substrings: 24 240/24 = 10 40 240/40 = 6 K-Beauty Count: 2 Output: return 2 Key Insight: Use sliding window of size k to extract all substrings. Convert each substring to integer and check if it divides the original number evenly. Skip substrings with value 0 (division by zero). Time: O(n*k), Space: O(k). TutorialsPoint - Find the K-Beauty of a Number | Optimal Solution
Asked in
Amazon 15 Google 12
12.5K Views
Medium Frequency
~15 min Avg. Time
342 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