As far as why it failed test case #3, perhaps you need to write better, more efficient code. The code you wrote will be a bit of a CPU hog, and I recall the Cody problems time out for excessively slow solutions. (I've not looked carefully at your code. But even if it does work, it will get a really poor Cody score. The scoring algorithm for Cody hates massively nested loops when compared to more elegant solutions.)
Since the third test case for that Cody problem is significantly larger than the others, and you claim your code worked for cases 1 and 2, I'll postulate your code is just slow as mollasses on a winter day.
Could your code be used to solve a real PE problem? NO WAY! So you probably need to find a solution that does not use massively nested loops. I can think of at least one, ok, maybe two solutions. (And while I will not tell you how to solve a problem that was put there to make you think, just telling you that massively nested loops are a bad idea might be enough of a clue.)