Given a number n, find all 1 to n bit numbers with no consecutive 1's in their binary representation.
Examples:
Input: n = 3
Output: [1, 2, 4, 5]
Explanation: The binary representations of the numbers from 1 to 7 are 1, 10, 11, 100, 101, 110, and 111. Among these, 3 (11), 6 (110), and 7 (111) contain consecutive 1's.Input: n = 2
Output: [1, 2]
Explanation: The binary representations of the numbers from 1 to 3 are 1, 10, and 11. Among these, 3 (11) contains consecutive 1's in its binary representation.
Table of Content
[Naive Approach] Brute Force Check - O(2ⁿ × n) Time and O(2ⁿ) Space
Generate all n-bit numbers from 0 to 2n - 1. Check each number for consecutive 1's by scanning bits.
#include <vector>
#include <iostream>
using namespace std;
// Checks whether a number has consecutive 1's
bool isValid(int num) {
while (num > 0) {
if ((num & 1) && (num & 2))
return false;
num >>= 1;
}
return true;
}
// Returns all n-bit numbers having no consecutive 1's
vector<int> noConsecutiveOnes(int n) {
vector<int> ans;
// Check every n-bit number
for (int num = 0; num < (1 << n); num++) {
if (isValid(num))
ans.push_back(num);
}
// Remove 0 if only positive numbers are required
ans.erase(remove(ans.begin(), ans.end(), 0), ans.end());
return ans;
}
int main() {
int n = 3;
vector<int> ans = noConsecutiveOnes(n);
for (int x : ans)
cout << x << " ";
return 0;
}
import java.util.ArrayList;
class GFG {
// Checks whether a number has consecutive 1's
static boolean isValid(int num) {
while (num > 0) {
if ((num & 1) != 0 && (num & 2) != 0)
return false;
num >>= 1;
}
return true;
}
// Returns all n-bit numbers having no consecutive 1's
static ArrayList<Integer> noConsecutiveOnes(int n) {
ArrayList<Integer> ans = new ArrayList<Integer>();
// Check every n-bit number
for (int num = 0; num < (1 << n); num++) {
if (isValid(num))
ans.add(num);
}
// Remove 0 if only positive numbers are required
ans.removeIf(x -> x == 0);
return ans;
}
public static void main(String[] args) {
int n = 3;
ArrayList<Integer> ans = noConsecutiveOnes(n);
for (int x : ans)
System.out.print(x + " ");
}
}
# Checks whether a number has consecutive 1's
def isValid(num):
while (num > 0):
if ((num & 1) and (num & 2)):
return False
num >>= 1
return True
# Returns all n-bit numbers having no consecutive 1's
def noConsecutiveOnes(n):
ans = []
# Check every n-bit number
for num in range(1 << n):
if isValid(num):
ans.append(num)
# Remove 0 if only positive numbers are required
if 0 in ans:
ans.remove(0)
return ans
if __name__ == "__main__":
n = 3
ans = noConsecutiveOnes(n)
for x in ans:
print(x, end=" ")
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
// Checks whether a number has consecutive 1's
static bool isValid(int num) {
while (num > 0) {
if ((num & 1) != 0 && (num & 2) != 0)
return false;
num >>= 1;
}
return true;
}
// Returns all n-bit numbers having no consecutive 1's
static List<int> noConsecutiveOnes(int n) {
List<int> ans = new List<int>();
// Check every n-bit number
for (int num = 0; num < (1 << n); num++) {
if (isValid(num))
ans.Add(num);
}
// Remove 0 if only positive numbers are required
ans.RemoveAll(x => x == 0);
return ans;
}
static void Main(string[] args) {
int n = 3;
List<int> ans = noConsecutiveOnes(n);
foreach (int x in ans)
Console.Write(x + " ");
}
}
// Checks whether a number has consecutive 1's
function isValid(num) {
while (num > 0) {
if ((num & 1) && (num & 2))
return false;
num >>= 1;
}
return true;
}
// Returns all n-bit numbers having no consecutive 1's
function noConsecutiveOnes(n) {
let ans = [];
// Check every n-bit number
for (let num = 0; num < (1 << n); num++) {
if (isValid(num))
ans.push(num);
}
// Remove 0 if only positive numbers are required
ans = ans.filter(x => x !== 0);
return ans;
}
// Driver code
let n = 3;
let ans = noConsecutiveOnes(n);
let output = "";
for (let x of ans)
output += x + " ";
console.log(output);
Output
1 2 4 5
[Expected Approach] DFS with Constraint - O(2ⁿ) Time and O(2ⁿ) Space
Build n-bit numbers recursively. At each position, always place 0. Place 1 only if previous bit was 0. This avoids generating invalid numbers.
- Start DFS with pos=0, prevBit=0, num=0
- If pos == n, add num to answer
- Place 0 at current position and recurse
- If prevBit == 0, place 1 and recurse
- Remove 0 from answer if positive numbers needed
- Return answer
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Build valid numbers one bit at a time
void dfs(int pos, int n, int prevBit, int num, vector<int> &ans) {
// A complete n-bit number is formed
if (pos == n) {
ans.push_back(num);
return;
}
// Place 0
dfs(pos + 1, n, 0, num << 1, ans);
// Place 1 only if previous bit is 0
if (prevBit == 0) {
dfs(pos + 1, n, 1, (num << 1) | 1, ans);
}
}
// Returns all n-bit numbers having no consecutive 1's
vector<int> noConsecutiveOnes(int n) {
vector<int> ans;
dfs(0, n, 0, 0, ans);
// Remove 0 if only positive numbers are required
ans.erase(remove(ans.begin(), ans.end(), 0), ans.end());
return ans;
}
int main() {
int n = 3;
vector<int> ans = noConsecutiveOnes(n);
for (int x : ans)
cout << x << " ";
return 0;
}
import java.util.ArrayList;
class GFG {
// Build valid numbers one bit at a time
static void dfs(int pos, int n, int prevBit, int num, ArrayList<Integer> ans) {
// A complete n-bit number is formed
if (pos == n) {
ans.add(num);
return;
}
// Place 0
dfs(pos + 1, n, 0, num << 1, ans);
// Place 1 only if previous bit is 0
if (prevBit == 0) {
dfs(pos + 1, n, 1, (num << 1) | 1, ans);
}
}
// Returns all n-bit numbers having no consecutive 1's
static ArrayList<Integer> noConsecutiveOnes(int n) {
ArrayList<Integer> ans = new ArrayList<>();
dfs(0, n, 0, 0, ans);
// Remove 0 if only positive numbers are required
ans.remove(Integer.valueOf(0));
return ans;
}
public static void main(String[] args) {
int n = 3;
ArrayList<Integer> ans = noConsecutiveOnes(n);
for (int x : ans) {
System.out.print(x + " ");
}
}
}
# Build valid numbers one bit at a time
def dfs(pos, n, prevBit, num, ans):
# A complete n-bit number is formed
if pos == n:
ans.append(num)
return
# Place 0
dfs(pos + 1, n, 0, num << 1, ans)
# Place 1 only if previous bit is 0
if prevBit == 0:
dfs(pos + 1, n, 1, (num << 1) | 1, ans)
# Returns all n-bit numbers having no consecutive 1's
def noConsecutiveOnes(n):
ans = []
dfs(0, n, 0, 0, ans)
# Remove 0 if only positive numbers are required
if 0 in ans:
ans.remove(0)
return ans
if __name__ == "__main__":
n = 3
ans = noConsecutiveOnes(n)
print(' '.join(map(str, ans)))
using System;
using System.Collections.Generic;
class GFG {
// Build valid numbers one bit at a time
static void dfs(int pos, int n, int prevBit, int num, List<int> ans) {
// A complete n-bit number is formed
if (pos == n) {
ans.Add(num);
return;
}
// Place 0
dfs(pos + 1, n, 0, num << 1, ans);
// Place 1 only if previous bit is 0
if (prevBit == 0) {
dfs(pos + 1, n, 1, (num << 1) | 1, ans);
}
}
// Returns all n-bit numbers having no consecutive 1's
static List<int> noConsecutiveOnes(int n) {
List<int> ans = new List<int>();
dfs(0, n, 0, 0, ans);
// Remove 0 if only positive numbers are required
ans.Remove(0);
return ans;
}
static void Main(string[] args) {
int n = 3;
List<int> ans = noConsecutiveOnes(n);
foreach (int x in ans) {
Console.Write(x + " ");
}
}
}
// Build valid numbers one bit at a time
function dfs(pos, n, prevBit, num, ans) {
// A complete n-bit number is formed
if (pos === n) {
ans.push(num);
return;
}
// Place 0
dfs(pos + 1, n, 0, num << 1, ans);
// Place 1 only if previous bit is 0
if (prevBit === 0) {
dfs(pos + 1, n, 1, (num << 1) | 1, ans);
}
}
// Returns all n-bit numbers having no consecutive 1's
function noConsecutiveOnes(n) {
let ans = [];
dfs(0, n, 0, 0, ans);
// Remove 0 if only positive numbers are required
ans = ans.filter(x => x !== 0);
return ans;
}
// Driver code
const n = 3;
const ans = noConsecutiveOnes(n);
console.log(ans.join(' '));
Output
1 2 4 5