There are n friends in a group. When they meet, everybody shakes hands with everybody. How many hand shakes happen?
Example:
Input: n = 3 Output: 3 Explanation: Considering A, B, and C are the 3 friends. The hand shakes are: (A, B), (A, C) and (B, C)Hints:
Take an example with n = 4 and write down all the hand shakes as in the explanation above. What do you notice?
Hopefully you wrote the following pairs: (A, B), (A, C), (A, D), (B, C), (B, D), (C, D)
How many hand shakes are there of the form (A, X) ? What about (B, X) ?
(A, B), (A, C), (A, D)
(B, C), (B, D)
(C, D)
We have 3 hand shakes that start with A
We have 2 hand shakes that start with B
And 1 hand shake that start with C
In total we have 3 + 2 + 1 = 6
Can you come up with a formula for this?
Let's put the first letter of each handshake in a square:
A A A O
B B O O
C O O O
O O O O
Notice that the last row is empty, so we should remove that:
A A A O
B B O O
C O O O
In this rectangle we have 6 empty and 6 filled (the hand shakes)
This means that our answer is the area of rectangle / 2
Let's recap. For n = 4 we have a rectangle with (n - 1) rows and n columns.
Our answer is the area / 2.
The area for the rectangle is (n - 1) * n
Therefore the full answer is ((n - 1) * n) / 2
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check