Find Next Sparse Number

Last Updated : 7 Jul, 2026

Given an integerĀ nĀ in the input, find its next sparse binary number. A sparse binary number is a number whose binary representation does not contain any consecutive 1s.

Examples:Ā 

Input: n = 3
Output:Ā 4
Explanation: Binary representation of 4 is (0100).

Input: n = 38
Output: 40
Explanation: Binary representation of 40 is (101000).

Input: n = 5
Output:Ā 5
Explanation: Binary representation of 5 is (0101).

Try It Yourself
redirect icon

[Naive Approach] Linear Search with Binary Check - O(n) Time and O(1) Space

Starting from n, check each number one by one. The first sparse number encountered will be the answer, as we need the smallest sparse number greater than or equal to n.

To check whether a number is sparse, we need to verify that it does not contain any two adjacent set bits. This can be done using the expression (n & (n >> 1)) == 0.

For example, let n = 45.
Binary representation of 45 = (101101)2
Binary representation of (45 >> 1) = (010110)2

Performing bitwise AND: (101101)2 & (010110)2 = (000100)2

Since the result is non-zero, so 45 is not a sparse number.

C++
#include <iostream>
using namespace std;

bool isSparseNumber(int n){
    
     // A sparse number has no adjacent set bits
    return (n & (n >> 1)) == 0;
}

int nextSparse(int n) {
    
    // try all possible number >= n
    while(true){
        if(isSparseNumber(n))return n;
        n++;
    }
}

int main() {

    int n = 38;

    cout << nextSparse(n);

    return 0;
}
Java
public class GFG {

    public static boolean isSparseNumber(int n) {
        // A sparse number has no adjacent set bits
        return (n & (n >> 1)) == 0;
    }

    public static int nextSparse(int n) {
        // try all possible number >= n
        while (true) {
            if (isSparseNumber(n)) return n;
            n++;
        }
    }

    public static void main(String[] args) {
        int n = 38;
        System.out.println(nextSparse(n));
    }
}
Python
def isSparseNumber(n):
    # A sparse number has no adjacent set bits
    return (n & (n >> 1)) == 0

def nextSparse(n):
    # try all possible number >= n
    while True:
        if isSparseNumber(n):
            return n
        n += 1

if __name__ == "__main__":
    n = 38
    print(nextSparse(n))
C#
using System;

public class GFG {

    public static bool isSparseNumber(int n) {
        // A sparse number has no adjacent set bits
        return (n & (n >> 1)) == 0;
    }

    public static int nextSparse(int n) {
        // try all possible number >= n
        while (true) {
            if (isSparseNumber(n)) return n;
            n++;
        }
    }

    public static void Main() {
        int n = 38;
        Console.WriteLine(nextSparse(n));
    }
}
JavaScript
function isSparseNumber(n) {
    // A sparse number has no adjacent set bits
    return (n & (n >> 1)) === 0;
}

function nextSparse(n) {
    // try all possible number >= n
    while (true) {
        if (isSparseNumber(n)) return n;
        n++;
    }
}

// Driver code
let n = 38;
console.log(nextSparse(n));

Output
40

[Expected Approach] Bit Manipulation with Carry Propagation - O(log n) Time and O(log n) Space

Find binary representation from LSB to MSB. Scan from left to right. When two consecutive 1's are found, set next bit to 1 and clear all previous bits to get smallest next sparse number.

  • Convert x to binary vector with LSB at index 0
  • Add extra bit at end to handle carry
  • Scan from bit 1 to n-2
  • If current bit and previous bit are 1 and next bit is not 1
  • Set next bit to 1
  • Clear all bits from current position down to last_final
  • Update last_final to next bit position
  • Convert binary vector back to decimal
  • Return result
C++
#include <iostream>
#include <vector>
using namespace std;

int nextSparse(int n) {

    // Store binary representation from LSB to MSB
    vector<bool> bits;
    while (n) {
        bits.push_back(n & 1);
        n >>= 1;
    }

    // Extra bit to handle carry
    bits.push_back(0);

    int m = bits.size();
    int lastFinal = 0;

    for (int i = 1; i < m - 1; i++) {

        // Found consecutive set bits
        if (bits[i] && bits[i - 1] && !bits[i + 1]) {

            // Set the next higher bit
            bits[i + 1] = 1;

            // Clear lower bits to get the 
            // smallest valid number
            for (int j = i; j >= lastFinal; j--)
                bits[j] = 0;

            lastFinal = i + 1;
        }
    }

    // Convert the modified bit representation 
    // back to decimal
    int ans = 0;
    for (int i = 0; i < m; i++)
        ans += bits[i] * (1 << i);

    return ans;
}

int main() {
    int n = 38;
    cout << nextSparse(n);
    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;

public class GFG {
    public static int nextSparse(int n) {
        // Store binary representation from LSB to MSB
        List<Boolean> bits = new ArrayList<>();
        while (n!= 0) {
            bits.add((n & 1) == 1);
            n >>= 1;
        }

        // Extra bit to handle carry
        bits.add(false);

        int m = bits.size();
        int lastFinal = 0;

        for (int i = 1; i < m - 1; i++) {
            // Found consecutive set bits
            if (bits.get(i) && bits.get(i - 1) && !bits.get(i + 1)) {
                // Set the next higher bit
                bits.set(i + 1, true);

                // Clear lower bits to get the 
                // smallest valid number
                for (int j = i; j >= lastFinal; j--)
                    bits.set(j, false);

                lastFinal = i + 1;
            }
        }

        // Convert the modified bit representation 
        // back to decimal
        int ans = 0;
        for (int i = 0; i < m; i++)
            if (bits.get(i))
                ans += 1 << i;

        return ans;
    }

    public static void main(String[] args) {
        int n = 38;
        System.out.println(nextSparse(n));
    }
}
Python
def nextSparse(n):
    # Store binary representation from LSB to MSB
    bits = []
    while n:
        bits.append(n & 1)
        n >>= 1

    # Extra bit to handle carry
    bits.append(0)

    m = len(bits)
    lastFinal = 0

    for i in range(1, m - 1):
        # Found consecutive set bits
        if bits[i] and bits[i - 1] and not bits[i + 1]:
            # Set the next higher bit
            bits[i + 1] = 1

            # Clear lower bits to get the 
            # smallest valid number
            for j in range(i, lastFinal - 1, -1):
                bits[j] = 0

            lastFinal = i + 1

    # Convert the modified bit representation 
    # back to decimal
    ans = 0
    for i in range(m):
        if bits[i]:
            ans += 1 << i

    return ans

if __name__ == '__main__':
    n = 38
    print(nextSparse(n))
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static int nextSparse(int n) {
        // Store binary representation from LSB to MSB
        List<bool> bits = new List<bool>();
        while (n!= 0) {
            bits.Add((n & 1) == 1);
            n >>= 1;
        }

        // Extra bit to handle carry
        bits.Add(false);

        int m = bits.Count;
        int lastFinal = 0;

        for (int i = 1; i < m - 1; i++) {
            // Found consecutive set bits
            if (bits[i] && bits[i - 1] && !bits[i + 1]) {
                // Set the next higher bit
                bits[i + 1] = true;

                // Clear lower bits to get the 
                // smallest valid number
                for (int j = i; j >= lastFinal; j--)
                    bits[j] = false;

                lastFinal = i + 1;
            }
        }

        // Convert the modified bit representation 
        // back to decimal
        int ans = 0;
        for (int i = 0; i < m; i++)
            if (bits[i])
                ans += 1 << i;

        return ans;
    }

    public static void Main() {
        int n = 38;
        Console.WriteLine(nextSparse(n));
    }
}
JavaScript
function nextSparse(n) {
    // Store binary representation from LSB to MSB
    let bits = [];
    while (n) {
        bits.push((n & 1) === 1);
        n >>= 1;
    }

    // Extra bit to handle carry
    bits.push(false);

    let m = bits.length;
    let lastFinal = 0;

    for (let i = 1; i < m - 1; i++) {
        // Found consecutive set bits
        if (bits[i] && bits[i - 1] && !bits[i + 1]) {
            // Set the next higher bit
            bits[i + 1] = true;

            // Clear lower bits to get the 
            // smallest valid number
            for (let j = i; j >= lastFinal; j--)
                bits[j] = false;

            lastFinal = i + 1;
        }
    }

    // Convert the modified bit representation 
    // back to decimal
    let ans = 0;
    for (let i = 0; i < m; i++)
        if (bits[i])
            ans += 1 << i;

    return ans;
}

// Driver code
let n = 38;
console.log(nextSparse(n));

Output
40
Comment