Sort 201 Discussions, By:
Please Login in order to post a comment
Try this reasoning:
I (PersonA) am one out of N people, so I need to shake hands with (N-1) people. This reasoning holds true for all of the N people, so the number of hand shakes is N * (N-1). Now that PersonA and PersonB shook hands, PersonB and PersonA (same people, but from PersonB's perspective) don't need to shake anymore. So we initially counted each combination twice. Therefore, the number of hand shakes is
nShakes = (N * (N-1)) / 2
Smallest Code written in HackerRank so far:
return ((n-1)*n) /2;
In an example of 4 people:
The first person can shake hands with all the others (N-1)=3. The seconds person can shake hands with all the others, without 1: (N-1-1)=2, third = (N-1-1-1)=1, fourth = (N-1-1-1-1)=0. Hence we get exactly range(4) [at least in Python]. So if we do
0+1+2+3 == 6, we get the total number of handshakes.
It is a standard combinatorics problem. You need to select a pair of people from N people. How many different pairs are there? N choose 2. N! / ((N-2)! * 2!) which simplifies to (N * (N-1)) / 2.
I have a qualm with the sample test cases provided. Don't use 0 or 1, because most of the times they represent some boundary case or special case.
Maybe you can include one example with a bigger number, like 4 or 5?