Why was my solution giving a WA first, then RE afterwards for NMNX?

I was following the logic of using combinatorics for this problem. My first approach was giving me a TLE because I was finding out a lot of coefficients beforehand. However, this new approach works fine as per my understanding. Can you all help me find my mistake?

Question

Solution