Count numbers in range [L, R] having K consecutive set bits

Last Updated : 23 Jul, 2025

Given three positive integers l, r, and k, the task is to find the count of numbers in the range [l, r] having k consecutive set bits in their binary representation.

Examples:

Input: l = 4, r = 15, k = 3 
Output:
Explanation: 
Numbers whose binary representation contains k=3 consecutive set bits are: 
(7)10 = (111)2 
(14)10 = (1110)2 
(15)10 = (1111)2 
Therefore, the required output is 3. 

Input: l = 8, r = 100, k = 3 
Output: 27

Using Brute Force Method - O(r) Time and O(1) Space

The idea is to traverse all possible integers in the range [l, r] and for each number, check if binary representation of the number contains k consecutive 1's or not. If true, increment the answer.

C++
// C++ program to count numbers in range
// [L, R] having K consecutive set bits
#include <bits/stdc++.h>
using namespace std;

// Function to count numbers having
// k consecutive set bits
int count(int l, int r, int k) {
    int ans = 0;

    for (int num = l; num <= r; num++) {

        // Variable to count continuos bits
        int cnt = 0;
        bool f = false;

        for (int i = 0; i < 32; i++) {
            if ((num & (1 << i))) {
                cnt++;
                if (cnt >= k)
                    f = true;
            }
            else {
                cnt = 0;
            }
        }

        if (f)
            ans++;
    }

    return ans;
}

int main() {
  
    int l = 4, r = 15, k = 3;
    cout << count(l, r, k) << endl;

    return 0;
}
Java
// Java program to count numbers in range 
// [L, R] having K consecutive set bits

class GfG {

    // Function to count numbers having
    // k consecutive set bits
    static int count(int l, int r, int k) {
        int ans = 0;

        for (int num = l; num <= r; num++) {

            // Variable to count continuous bits
            int cnt = 0;
            boolean f = false;

            for (int i = 0; i < 32; i++) {
                if ((num & (1 << i)) != 0) {
                    cnt++;
                    if (cnt >= k) f = true;
                } else {
                    cnt = 0;
                }
            }

            if (f) ans++;
        }

        return ans;
    }

    public static void main(String[] args) {
        int l = 4, r = 15, k = 3;
        System.out.println(count(l, r, k));
    }
}
Python
# Python program to count numbers in range 
# [L, R] having K consecutive set bits

# Function to count numbers having
# k consecutive set bits
def count(l, r, k):
    ans = 0

    for num in range(l, r + 1):

        # Variable to count continuous bits
        cnt = 0
        f = False

        for i in range(32):
            if (num & (1 << i)):
                cnt += 1
                if cnt >= k:
                    f = True
            else:
                cnt = 0

        if f:
            ans += 1

    return ans


if __name__ == "__main__":
    l, r, k = 4, 15, 3
    print(count(l, r, k))
C#
// C# program to count numbers in range 
// [L, R] having K consecutive set bits

using System;

class GfG {

    // Function to count numbers having
    // k consecutive set bits
    static int count(int l, int r, int k) {
        int ans = 0;

        for (int num = l; num <= r; num++) {

            // Variable to count continuous bits
            int cnt = 0;
            bool f = false;

            for (int i = 0; i < 32; i++) {
                if ((num & (1 << i)) != 0) {
                    cnt++;
                    if (cnt >= k) f = true;
                } else {
                    cnt = 0;
                }
            }

            if (f) ans++;
        }

        return ans;
    }

    static void Main(string[] args) {
        int l = 4, r = 15, k = 3;
        Console.WriteLine(count(l, r, k));
    }
}
JavaScript
// JavaScript program to count numbers in range 
// [L, R] having K consecutive set bits

// Function to count numbers having
// k consecutive set bits
function count(l, r, k) {
    let ans = 0;

    for (let num = l; num <= r; num++) {

        // Variable to count continuous bits
        let cnt = 0;
        let f = false;

        for (let i = 0; i < 32; i++) {
            if ((num & (1 << i)) !== 0) {
                cnt++;
                if (cnt >= k) f = true;
            } else {
                cnt = 0;
            }
        }

        if (f) ans++;
    }

    return ans;
}

let l = 4, r = 15, k = 3;
console.log(count(l, r, k));

Output
3

Using Dynamic Programming - O(32 * k * (log(r) + log(l))) Time and O(k) Space

The idea is to use a digit dynamic programming (Digit DP) approach, where we recursively build numbers from the most significant bit (MSB) to the least significant bit (LSB), considering whether the current number is still constrained to the bounds defined by l or r.

At each step, we have two choices:

  1. Set the current bit to 0.
  2. Set the current bit to 1.

We also keep track of additional information in our DP state, like whether we’ve encountered k consecutive 1s and whether we are still bound by the upper limit. We break down the problem into subproblems by recursively processing the next bit position and transitioning from one state to another.

Each state in DP will be:

  • i: Current bit position being processed (from 31 down to 0)
  • cnt: Count of consecutive set bits (1s) encountered so far.
  • kOne: A boolean that tells us whether we have encountered exactly k consecutive set bits at some point in the number.
  • tight: A boolean indicating whether the current number we are constructing is still "tight" (i.e., whether it's still less than or equal to the number being processed - either l or r).
C++
// C++ program to count numbers in range
// [L, R] having K consecutive set bits
#include <bits/stdc++.h>
using namespace std;

int countRecur(int i, int cnt, int kOne, int tight, int num, int k, 
               vector<vector<vector<vector<int>>>> &memo) {
    if (i == -1) {
        return kOne == 1 ? 1 : 0;
    }

    // if value is memoized, return it.
    if (memo[i][cnt][kOne][tight] != -1)
        return memo[i][cnt][kOne][tight];

    // Bit at current i.
    int currBit = (num & (1 << i)) > 0 ? 1 : 0;

    int ans = 0;

    // Find count of numbers if current
    // bit is set to 0.
    ans += countRecur(i - 1, 0, kOne, tight && 
                      (currBit == 0), num, k, memo);

    // Find count of numbers if current
    // bit is set to 1.
    if (currBit == 1 || tight == false) {
        ans += countRecur(i - 1, cnt + 1, kOne 
                          || (cnt + 1 == k), tight, num, k, memo);
    }

    return memo[i][cnt][kOne][tight] = ans;
}

// Function to count numbers having
// k consecutive set bits
int count(int l, int r, int k) {

    vector<vector<vector<vector<int>>>> memo(
        32, vector<vector<vector<int>>>
      	(32, vector<vector<int>>(2, vector<int>(2, -1))));

    // Count numbers in range [1, l-1]
    // having consecutive k set bits
    int cntL = countRecur(31, 0, 0, 1, l - 1, k, memo);

    // Reset memo
    for (int i = 0; i < 32; i++) {
        for (int j = 0; j < 32; j++) {
            for (int k = 0; k < 2; k++) {
                for (int l = 0; l < 2; l++) {
                    memo[i][j][k][l] = -1;
                }
            }
        }
    }

    // Count numbers in range [1, r]
    // having consecutive k set bits
    int cntR = countRecur(31, 0, 0, 1, r, k, memo);

    return cntR - cntL;
}

int main() {
  
    int l = 4, r = 15, k = 3;
    cout << count(l, r, k) << endl;

    return 0;
}
Java
// Java program to count numbers in range 
// [L, R] having K consecutive set bits

class GfG {

    static int countRecur(int i, int cnt, int kOne, 
                          int tight, int num, int k, 
    int[][][][] memo) {
        if (i == -1) {
            return kOne == 1 ? 1 : 0;
        }

        // if value is memoized, return it.
        if (memo[i][cnt][kOne][tight] != -1) 
            return memo[i][cnt][kOne][tight];

        // Bit at current i.
        int currBit = (num & (1 << i)) > 0 ? 1 : 0;

        int ans = 0;

        // Find count of numbers if current 
        // bit is set to 0.
        ans += countRecur(i - 1, 0, kOne, 
        tight & (currBit == 0 ? 1 : 0), num, k, memo);

        // Find count of numbers if current
        // bit is set to 1.
        if (currBit == 1 || tight == 0) {
            ans += countRecur(i - 1, cnt + 1, 
            kOne | ((cnt + 1) == k ? 1 : 0), 
            tight, num, k, memo);
        }

        return memo[i][cnt][kOne][tight] = ans;
    }

    static int count(int l, int r, int k) {
        int[][][][] memo = new int[32][32][2][2];
        for (int[][][] m1 : memo)
            for (int[][] m2 : m1)
                for (int[] m3 : m2)
                    java.util.Arrays.fill(m3, -1);

        // Count numbers in range [1, l-1]
        // having consecutive k set bits
        int cntL = countRecur(31, 0, 0, 1, l - 1, k, memo);

        // Reset memo
        for (int[][][] m1 : memo)
            for (int[][] m2 : m1)
                for (int[] m3 : m2)
                    java.util.Arrays.fill(m3, -1);

        // Count numbers in range [1, r]
        // having consecutive k set bits
        int cntR = countRecur(31, 0, 0, 1, r, k, memo);

        return cntR - cntL;
    }

    public static void main(String[] args) {
        int l = 4, r = 15, k = 3;
        System.out.println(count(l, r, k));
    }
}
Python
# Python program to count numbers in range
# [L, R] having K consecutive set bits


def countRecur(i, cnt, kOne, tight, num, k, memo):
    if i == -1:
        return 1 if kOne == 1 else 0

    # if value is memoized, return it.
    if memo[i][cnt][kOne][tight] != -1:
        return memo[i][cnt][kOne][tight]

    # Bit at current i.
    currBit = 1 if (num & (1 << i)) > 0 else 0

    ans = 0

    # Find count of numbers if current
    # bit is set to 0.
    ans += countRecur(i - 1, 0, kOne, tight and \
                      currBit == 0, num, k, memo)

    # Find count of numbers if current
    # bit is set to 1.
    if currBit == 1 or not tight:
        ans += countRecur(i - 1, cnt + 1, kOne or cnt +
                          1 == k, tight, num, k, memo)

    memo[i][cnt][kOne][tight] = ans
    return ans


def count(l, r, k):
    memo = [[[[-1 for _ in range(2)] for _ in range(2)]
             for _ in range(32)] for _ in range(32)]

    # Count numbers in range [1, l-1]
    # having consecutive k set bits
    cntL = countRecur(31, 0, 0, 1, l - 1, k, memo)

    # Reset memo
    memo = [[[[-1 for _ in range(2)] for _ in range(2)]
             for _ in range(32)] for _ in range(32)]

    # Count numbers in range [1, r]
    # having consecutive k set bits
    cntR = countRecur(31, 0, 0, 1, r, k, memo)

    return cntR - cntL


if __name__ == "__main__":
    l, r, k = 4, 15, 3
    print(count(l, r, k))
C#
// C# program to count numbers in range 
// [L, R] having K consecutive set bits

using System;

class GfG {

    static int countRecur(int i, int cnt, int kOne, 
    int tight, int num, int k, int[,,,] memo) {
        if (i == -1) {
            return kOne == 1 ? 1 : 0;
        }

        // if value is memoized, return it.
        if (memo[i, cnt, kOne, tight] != -1) 
            return memo[i, cnt, kOne, tight];

        // Bit at current i.
        int currBit = (num & (1 << i)) > 0 ? 1 : 0;

        int ans = 0;

        // Find count of numbers if current 
        // bit is set to 0.
        ans += countRecur(i - 1, 0, kOne, 
        tight & (currBit == 0 ? 1 : 0), num, k, memo);

        // Find count of numbers if current
        // bit is set to 1.
        if (currBit == 1 || tight == 0) {
            ans += countRecur(i - 1, cnt + 1, 
            kOne | ((cnt + 1) == k ? 1 : 0), 
            tight, num, k, memo);
        }

        return memo[i, cnt, kOne, tight] = ans;
    }

    static int count(int l, int r, int k) {
        int[,,,] memo = new int[32, 32, 2, 2];
        for (int i = 0; i < 32; i++)
            for (int j = 0; j < 32; j++)
                for (int m = 0; m < 2; m++)
                    for (int n = 0; n < 2; n++)
                        memo[i, j, m, n] = -1;

        // Count numbers in range [1, l-1]
        // having consecutive k set bits
        int cntL = countRecur(31, 0, 0, 1, l - 1, k, memo);

        // Reset memo
        for (int i = 0; i < 32; i++)
            for (int j = 0; j < 32; j++)
                for (int m = 0; m < 2; m++)
                    for (int n = 0; n < 2; n++)
                        memo[i, j, m, n] = -1;

        // Count numbers in range [1, r]
        // having consecutive k set bits
        int cntR = countRecur(31, 0, 0, 1, r, k, memo);

        return cntR - cntL;
    }

    static void Main(string[] args) {
        int l = 4, r = 15, k = 3;
        Console.WriteLine(count(l, r, k));
    }
}
JavaScript
// JavaScript program to count numbers in range 
// [L, R] having K consecutive set bits

function countRecur(i, cnt, kOne, tight, num, k, memo) {
    if (i === -1) {
        return kOne === 1 ? 1 : 0;
    }

    // if value is memoized, return it.
    if (memo[i][cnt][kOne][tight] !== -1) 
        return memo[i][cnt][kOne][tight];

    // Bit at current i.
    let currBit = (num & (1 << i)) > 0 ? 1 : 0;

    let ans = 0;

    // Find count of numbers if current 
    // bit is set to 0.
    ans += countRecur(i - 1, 0, kOne, 
    (tight && currBit === 0)?1:0, num, k, memo);

    // Find count of numbers if current
    // bit is set to 1.
    if (currBit === 1 || !tight) {
        ans += countRecur(i - 1, cnt + 1, 
        (kOne || cnt + 1 === k)?1:0, tight, num, k, memo);
    }

    return memo[i][cnt][kOne][tight] = ans;
}

function count(l, r, k) {
    let memo = Array.from({ length: 32 }, () =>
        Array.from({ length: 32 }, () =>
            Array.from({ length: 2 }, () => Array(2).fill(-1))
        )
    );

    // Count numbers in range [1, l-1]
    // having consecutive k set bits
    let cntL = countRecur(31, 0, 0, 1, l - 1, k, memo);

    // Reset memo
    memo = Array.from({ length: 32 }, () =>
        Array.from({ length: 32 }, () =>
            Array.from({ length: 2 }, () => Array(2).fill(-1))
        )
    );

    // Count numbers in range [1, r]
    // having consecutive k set bits
    let cntR = countRecur(31, 0, 0, 1, r, k, memo);

    return cntR - cntL;
}

let l = 4, r = 15, k = 3;
console.log(count(l, r, k));

Output
3
Comment