Why am I Getting memory limit exceeded ??


  • 1
    V

    I have written a small snippet to generate the gray codes. But I am getting memory limit exceeded. Please help!!!

    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> result;
            for(int i=0;i<2^n;i++)
                result.push_back(i);
            return result;
            
        }
    };

  • 1
    L

    [Disclamer: I have not used C/C++ for so many years so my answer can be total BS]

    This is what I can tell you: 2^n is not 2 to the power n, it's 2 xor n. Replacing it by (int) pow(2,n) seems to work.

    What I cannot tell you is why you're getting a memory limit exceeded. Indeed, the test cases of OJ are for all the values in [0,12], and 2 xor 0 .. 12 = 2,3,1,6,7,4,5,10,11,8,9,14. So this wouldn't cause a memory problem…


  • 2

    When n=2, it will result in MLE because i<2^n is interpreted by C++ as (i<2)^n, due to < has a higher operator precedence than ^.


  • 0
    L

    Thanks! And it becomes clear why strong type systems rock ;-)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.