All you need is a bit of careful thought.
Btw, it's extremely useful to write down your thought/demo in comments before you actually start to write the code, especially during interview.
Even if you do not solve the problem finally, the interviewer at least get to know what you're thinking.
And if you don't get the problem right, he/she will have a chance to correct you.
class Solution: # @return a list of integers ''' from up to down, then left to right 0 1 11 110 10 111 101 100 start:  i = 0: [0, 1] i = 1: [0, 1, 3, 2] i = 2: [0, 1, 3, 2, 6, 7, 5, 4] ''' def grayCode(self, n): results =  for i in range(n): results += [x + pow(2, i) for x in reversed(results)] return results
@byronyi O(n*(n+m)) vs O(2^x) solution where x can only go up to 31, because of this a O(2^x) is faster
I would do something like this instead:
def grayCode(self, n): if n == 0: return  nMax = 2**n return [(x>>1)^x for x in range(nMax)]
Same idea but slightly different implementation.
class Solution(object): def grayCode(self, n): res =  for i in range(n): res += [x|(1<<i) for x in res[::-1]] return res
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.