Easy 0 solved 0% acceptance

Count Handshakes

Count handshakes when every pair of people shakes hands once.

What you'll learn

  • Count pairs with n × (n - 1) / 2
  • Reason about counting each pair once
  • Replace a loop with a formula

Problem

Every person shakes hands once with every other person. A handshake between A and B is the same event as one between B and A. Nobody shakes their own hand.

Implement handshake_count(people).

Input

people: The number of people.

Output

Return the total number of distinct handshakes.

Constraints

0 ≤ people ≤ 1,000,000,000. The answer fits a signed 64-bit integer.

Examples

Example 1
Input:
people = 4

Expected output:
expected = 6
Input:
long long people = 4;

Expected output:
long long expected = 6;
Input:
long people = 4;

Expected output:
long expected = 6;

Explanation

The pairs are AB, AC, AD, BC, BD, and CD: six handshakes.

Example 2
Input:
people = 1

Expected output:
expected = 0
Input:
long long people = 1;

Expected output:
long long expected = 0;
Input:
long people = 1;

Expected output:
long expected = 0;

Explanation

One person has nobody else to greet.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Each handshake is just an unordered pair of distinct people.

Hint 2

Count how many pairs can be formed from all people without double-counting.

Hint 3

Be careful that zero or one person means no handshakes at all.

Expected complexity

O(1) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.