VOOZH about

URL: https://www.geeksforgeeks.org/dsa/backtracking-approach-generate-n-bit-gray-codes/

⇱ A backtracking approach to generate n bit Gray Codes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

A backtracking approach to generate n bit Gray Codes

Last Updated : 5 Feb, 2024

Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit) 

Examples:

Input : 2 
Output : 0 1 3 2
Explanation :
00 - 0
01 - 1
11 - 3
10 - 2
Input : 3
Output : 0 1 3 2 6 7 5 4

We have discussed an approach in Generate n-bit Gray Codes
This article provides a backtracking approach to the same problem. Idea is that for each bit out of n bit we have a choice either we can ignore it or we can invert the bit so this means our gray sequence goes upto 2 ^ n for n bits. So we make two recursive calls for either inverting the bit or leaving the bit as it is. 

Output:

0
1
3
2
6
7
5
4

Time Complexity: O(2n)
Auxiliary Space: O(n)

Comment
Article Tags: