Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

89. Gray Code

Medium60.5% Acceptance
MathBacktrackingBit Manipulation
Asked by:
A
Amazon
ProblemSolutions (12)VideosCompanies (1)Notes

Problem Statement

An n-bit gray code sequence is a sequence of 2n integers where:

  • Every integer is in the inclusive range [0, 2n - 1],
  • The first integer is 0,
  • An integer appears no more than once in the sequence,
  • The binary representation of every pair of adjacent integers differs by exactly one bit, and
  • The binary representation of the first and last integers differs by exactly one bit.

Given an integer n, return any valid n-bit gray code sequence.

Example 1:

Input: n = 2
Output: [0,1,3,2]
Explanation:
The binary representation of [0,1,3,2] is [00,01,11,10].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit

Example 2:

Input: n = 1
Output: [0,1]

Constraints:

  • 1 <= n <= 16
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions

Approach

The Gray Code problem asks you to generate a sequence of integers representing an n-bit Gray code, where consecutive values differ by exactly one bit. A key observation is that Gray codes follow a predictable pattern that can be constructed without checking every pair.

One common strategy is the reflection method. Start with the base case for 0 bits and iteratively build larger sequences by reflecting the existing list and prefixing bits appropriately. This ensures that adjacent numbers differ by only one bit. Another elegant perspective uses bit manipulation, where each index can be transformed into its Gray code equivalent using a simple bitwise relationship involving right shifts and XOR operations.

Both approaches generate all 2^n values in the sequence. Since every Gray code must be produced, the time complexity grows exponentially with n, while the space complexity is dominated by storing the resulting list.

Complexity

ApproachTime ComplexitySpace Complexity
Reflection / Iterative ConstructionO(2^n)O(2^n)
Bit Manipulation FormulaO(2^n)O(2^n)

Video Solution Available

Pepcoding

View all video solutions

Solutions (12)

Using Bit Manipulation

Gray code can be generated using a simple bit manipulation technique. For a given integer k, the corresponding Gray code is obtained by XORing k with (k >> 1). This technique ensures that each step in changing numbers results in transitioning only one bit.

Time complexity: O(2n), traversing all numbers.
Space complexity: O(1), using constant extra space.

CC++JavaPythonC#JavaScript
1#include <stdio.h>
2#include <math.h>
3
4void grayCode(int n) {
5    int size = pow(2, n);
6    for (int i = 0; i < size; i++) {
7        int gray = i ^ (i >> 1);
8        printf("%d ", gray);
9    }
10}
11
12int main() {
13    int n = 2;
14    grayCode(n);
15    return 0;
16}

Explanation

This C program calculates Gray codes by iterating from 0 to 2n - 1, computing each Gray code number using i ^ (i >> 1) for each integer i.

Recursive Gray Code Generation

The Gray code can be recursively generated by reflecting the existing sequence. Start with a base case of n=1: [0,1]. For each subsequent n, reflect the current list, prepend a bit to the reflected part, and concatenate the results: if Gn-1 = [0, 1], then Gn = [0Gn-1, 1Gn-1].

Time complexity: O(2n), where recursions reflect and build upon previous results.
Space complexity: O(2n), allocating for the result array.

CC++JavaPythonC#JavaScript
1#



Video Solutions

Watch expert explanations and walkthroughs

Gray Code Explained using Recursion and Backtracking | Leetcode#89 Solution in JAVA

Pepcoding
8:2442,187 views

Asked By Companies

1 companies
A
Amazon

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Expression Add OperatorsHard
Flip Game IIMedium
Count Numbers with Unique DigitsMedium
24 GameHard
More similar problems

Related Topics

MathBacktrackingBit Manipulation

Problem Stats

Acceptance Rate60.5%
DifficultyMedium
Companies1

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Is Gray Code asked in FAANG interviews?

Yes, Gray Code and similar bit manipulation problems occasionally appear in FAANG-style interviews. They test understanding of binary representations, bitwise operations, and the ability to recognize patterns in sequence generation.

What is the optimal approach for Gray Code?

The optimal approach uses bit manipulation or the reflection technique to generate the sequence efficiently. Both methods produce each of the 2^n values directly while maintaining the one-bit difference rule between consecutive numbers.

Why does Gray Code change only one bit at a time?

Gray Code is designed so that consecutive numbers differ by exactly one bit to minimize transition errors in digital systems. This property also makes it useful in algorithmic problems where controlled state transitions are required.

What data structure is best for the Gray Code problem?

A dynamic list or array is typically used to store the resulting sequence of Gray codes. During construction, operations like appending and iterating through existing values make arrays or vectors the most practical choice.

Previous Problem

Climbing Stairs

Next Problem

Unique Binary Search Trees

include
<stdio.h>
2
#
include
<stdlib.h>
3
4
void
generate
(
int
n
,
int
*
result
)
{
5
if
(
n
==
0
)
{
6
result
[
0
]
=
0
;
7
return
;
8
}
9
10
generate
(
n
-
1
,
result
)
;
11
int
size
=
1
<<
(
n
-
1
)
;
12
for
(
int
i
=
0
;
i
<
size
;
i
++
)
{
13
result
[
size
+
i
]
=
result
[
size
-
1
-
i
]
|
(
1
<<
(
n
-
1
)
)
;
14
}
15
}
16
17
int
*
grayCode
(
int
n
,
int
*
returnSize
)
{
18
*
returnSize
=
1
<<
n
;
19
int
*
result
=
(
int
*
)
malloc
(
sizeof
(
int
)
*
(
*
returnSize
)
)
;
20
generate
(
n
,
result
)
;
21
return
result
;
22
}
23
24
int
main
(
)
{
25
int
n
=
2
;
26
int
returnSize
;
27
int
*
gray
=
grayCode
(
n
,
&
returnSize
)
;
28
for
(
int
i
=
0
;
i
<
returnSize
;
i
++
)
{
29
printf
(
"%d "
,
gray
[
i
]
)
;
30
}
31
free
(
gray
)
;
32
return
0
;
33
}

Explanation

This C implementation uses recursion to build the Gray code sequence by reflecting and appending. Allocate memory for the result array and fill it with generated codes.