Magicsheet logo

Count K-Reducible Numbers Less Than N

Hard
100%
Updated 8/1/2025

Count K-Reducible Numbers Less Than N

What is this problem about?

A number is "K-reducible" if it takes at most kk operations to reduce it to 1. An operation consists of replacing a number with the count of set bits (1s) in its binary representation. You are given a binary string nn and an integer kk. You need to find how many positive integers less than nn are kk-reducible.

Why is this asked in interviews?

This "Hard" problem is asked by companies like Schneider Electric to test proficiency in Combinatorics and Digit Dynamic Programming (Digit DP). It requires a deep understanding of how bit counts change and how to count numbers with a specific bit count using combinations (nCr). It evaluates your ability to break a complex recursive reduction process into a simple counting task.

Algorithmic pattern used

This problem follows the Digit DP and Bit Manipulation pattern.

  1. Precompute how many operations it takes for any bit count xx to reach 1. This range is small (up to 1000).
  2. For each bit count xx that is kk-reducible, use Digit DP or Combinations to count how many numbers less than nn have exactly xx set bits.
  3. Sum these counts together (modulo 109+710^9+7).

Example explanation

Let n="101"n = "101" (which is 5), k=1k = 1.

  • Numbers less than 5: 1, 2, 3, 4.
  • 1 (binary "001"): 1 set bit. 1 op: 1 -> done. 1 is 1-reducible.
  • 2 (binary "010"): 1 set bit. 1 op: 1 -> done. 2 is 1-reducible.
  • 3 (binary "011"): 2 set bits. 1 op: 2. 2 is not 1. Not 1-reducible.
  • 4 (binary "100"): 1 set bit. 1 op: 1 -> done. 4 is 1-reducible. Total: 3.

Common mistakes candidates make

A major challenge is correctly implementing the Digit DP or Combinatorial counting for a binary string. Another error is forgetting that the reduction process counts set bits from the previous step—for example, if a number has 3 bits, the first operation results in the number 3, not the number of bits in 3. Finally, failing to handle the "less than nn" constraint strictly (and excluding nn itself) is a frequent logic bug.

Interview preparation tip

When counting numbers based on their binary properties, Combinations (nCrnCr) are often faster than full DP. If you need to find how many mm-bit numbers have rr bits set, it’s simply (mr)\binom{m}{r}. Practice building a Pascal's triangle for nCrnCr values to speed up these types of counting problems.

Similar Questions