The use of "set" p and q is somewhat misleading. For me, I just think that each number in a set should be unique; but that's not the case. So I recommended using "group" in replace of "set".
The equation in the explanation mismatches what is written in the code. It should be |p| * |q| = |p| * (|n| - |p|)
@BryanBo.Cao It's really a straight forward method. To sum the distances of every pair, you can make it with element one by one. For example, you check first element and second one, then check the coming third one with first and second element as: (1,2), (1,3), (2,3)...So the only thing you need to do is check how many more distances come with a new element nums[k] with passed elements nums,nums,...,nums[k-1].
@kittensing The time limit is put to block algorithms that are not good enough.Generally, your code may exceed the limit if the standard method is way better than yours or there is an endless loop in code. In this case, your implementation is fine, but the method needs to be improved :) I am newbee too.