#3352

Count K-Reducible Numbers Less Than N

Hard
MathStringDynamic ProgrammingCombinatoricsDynamic ProgrammingBit Manipulation
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages dynamic programming and precomputation to efficiently determine the number of k-reducible numbers without iterating through each number individually.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute the number of operations needed to reduce each number to 1 for all numbers up to n.
  2. 2Step 2: Use a dynamic programming approach to count how many numbers can be reduced to 1 in k or fewer operations.
  3. 3Step 3: Return the count of k-reducible numbers less than n.
solution.py16 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def countKReducible(s, k):
5    n = int(s, 2)
6    dp = [0] * (n + 1)
7    for i in range(1, n + 1):
8        x = i
9        operations = 0
10        while x > 1:
11            x = bin(x).count('1')
12            operations += 1
13            if operations > k:
14                break
15        dp[i] = operations
16    return sum(1 for i in range(1, n) if dp[i] <= k) % MOD

Complexity note: This complexity arises because we are iterating through all numbers up to n and counting set bits requires log n operations.

  • 1Understanding how to count set bits is crucial for this problem.
  • 2Dynamic programming can significantly reduce the time complexity by avoiding repeated calculations.

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