#2269

Find the K-Beauty of a Number

Easy
MathStringSliding WindowString ManipulationSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can still use the same approach but optimize the way we check for divisibility by ensuring we only convert substrings once and handle leading zeros effectively.

⚙️

Algorithm

5 steps
  1. 1Step 1: Convert the number 'num' to a string.
  2. 2Step 2: Initialize a counter for valid divisors.
  3. 3Step 3: Loop through the string and extract substrings of length k.
  4. 4Step 4: Convert each substring to an integer and check if it's a divisor of 'num', skipping '0'.
  5. 5Step 5: Return the count of valid divisors.
solution.py16 lines
1# Full working Python code
2
3def k_beauty(num: int, k: int) -> int:
4    num_str = str(num)
5    count = 0
6    for i in range(len(num_str) - k + 1):
7        substring = num_str[i:i + k]
8        if substring != '0':  # Skip if substring is '0'
9            divisor = int(substring)
10            if num % divisor == 0:
11                count += 1
12    return count
13
14# Example usage
15print(k_beauty(240, 2))  # Output: 2
16

Complexity note: The time complexity is O(n) because we only loop through the string once to check each substring of length k, making it efficient.

  • 1Substrings can be efficiently generated by using string slicing.
  • 2Divisibility checks are straightforward but must handle edge cases like '0'.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.