my approach : i am taking 1 as the root and then calculate the nodes at every distance k (1 <= k <= 500) in it’s subtree and then for each node i am calculating the number of nodes at every distance k without considering it’s subtree. Finally i sum up all the values within the subtree and outside the subtree for the given k and as all the possible pairs are counted twice , i just make my answer half.

it is failing in test 21 please help me where i am going wrong !

Hey dear. I tried debugging your code, yesterday and again today, with many small inputs but it returns the correct answer for all of them. Thats quite a bit over 40 TC.

I suspect that TC 21 is a really specific/special case where your approach is making some error in counting. Its really difficult (atleast for me) to come up with a corner case or find bug in the algo since whichever case I take, it seems to be working fine. Even that corner case, it works fine for N<=100. IDK perhaps the case is more than what I am seeing but yeah, it quite got me

Your best bet is to look at one of the passed solution which resembles your approach and compare differences. That can help in coming up with corner case as well.