C++ || Simple and Intuitive || With Explanation
One aproach can be to form the sequence of n ugli numbers and report the last one. While trying to do so, one usually gets stuck with thinking how to form the s
One aproach can be to form the sequence of `n` ugli numbers and report the last one. While trying to do so, one usually gets stuck with thinking how to form the sequence so that no number is left out, that is, how to make sure the sequence contains all the `n` numbers in the right order. \n\nOne way to get around this is to look at the sequence from different perspective. Instead of inserting the numbers in the right order, what if you popped out the numbers in the right order? Hence while popping off the next number, you can make sure that the number you are removing is the lowest number possible among the given choices.\n\nLook at the code with this idea in mind!\n\n```\nclass Solution {\npublic:\n    int nthSuperUglyNumber(int n, vector<int>& primes) {\n        unordered_set<long long> alreadyCame;\n        priority_queue<long long, vector<long long>, greater<long long>> pq;\n        alreadyCame.insert(1);\n        pq.push(1);\n        long long current;\n        \n        while(n--){\n            current = pq.top();\n            pq.pop();\n            \n            if(!n) return current; // for decreasing time, not necessary for the logic\n            \n            for(int prime: primes){\n                long long temp = prime*current;\n                \n                if(temp >= INT_MAX) break; // for decreasing time, not necessary for the logic\n                \n                if(!alreadyCame.count(temp)){\n                    alreadyCame.insert(temp);\n                    pq.push(temp);\n                }\n            }\n        }\n        \n        return (int)current;\n    }\n};\n```
[]