Can somebody please demonstrate for me a more efficient Cartesian product algorithm than the one I am using currently (assuming there is one). I\'ve looked around SO and go
I can't propose anything better, than O(n^2), because that's the size of the output, and the algorithm hence can't be any faster.
What I can suggest is using another approach to whether you need to compute product. For example, you may not even need the product set P if only you are going to query whether certain elements belong to it. You only need the information about the sets it's composed of.
Indeed (pseudocode)
bool IsInSet(pair (x,y), CartesianProductSet P)
{
return IsInHash(x,P.set[1]) && IsInHash(y,P.set[2])
}
where Cartesian product is calculated like this:
// Cartesian product of A and B is
P.set[1]=A; P.set[2]=B;
If you implement sets as hashes, then lookup in a cartesian product of m sets is just a lookup in m hashes you get for free. Construction of the cartesian product and IsInSet lookup each take O(m) time, where m is a number of sets you multiply, and it's much less than n--size of each set.