Skip to content
LC-0089 Medium LeetCode

89. Gray Code

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 62% Topics: Math, Backtracking, Bit Manipulation
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(2^n)
# Space: O(1)

class Solution(object):
    def grayCode(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        result = [0]
        for i in xrange(n):
            for n in reversed(result):
                result.append(1 << i | n)
        return result


# Proof of closed form formula could be found here:
# http://math.stackexchange.com/questions/425894/proof-of-closed-form-formula-to-convert-a-binary-number-to-its-gray-code
class Solution2(object):
    def grayCode(self, n):
        """
        :type n: int
        :rtype: List[int]
        """
        return [i >> 1 ^ i for i in xrange(1 << n)]


Solution from kamyu104/LeetCode-Solutions · MIT