Skip to content
Problem 825 · LeetCode 825(opens in a new tab)

Friends Of Appropriate Ages

MediumArrays

A social site has n members, and ages[i] is the age of member i. Member x sends a friend request to a different member y unless at least one of these holds: y is at most half of x's age plus 7; y is older than x; or y is over 100 while x is under 100.

Requests go one way: x asking y does not mean y asks x. Nobody sends a request to themself. Return how many requests are sent in total.

Example 1

Input:  ages = [17, 16, 18, 17]
Output: 6
Why:    each 17 asks 16 and the other 17; 18 asks both 17s
2 more examples and the constraints

Example 2

Input:  ages = [14, 14]
Output: 0
Why:    14 is not above 14 / 2 + 7 = 14

Example 3

Input:  ages = [40, 60, 101, 99, 120]
Output: 6
Why:    120→101, 120→99, 101→99, 101→60, 99→60, 60→40

Constraints

  • 1 ≤ n ≤ 20,000
  • 1 ≤ ages[i] ≤ 120

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every ordered pairO(n²)
  2. Count people by ageO(n + 120²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 20,000 peopleVerdict
Check every ordered pairO(n²)
Too slow at 20,000
Count people by ageO(n + 120²)
Best; work barely grows

n = number of people; 120 is the largest possible age.

Edge cases to test

  • Ages 14 and under. Nobody is above a / 2 + 7 ≤ a, so they never send anything.
  • Exactly on the line. An 18 and a 16: 16 equals 18 / 2 + 7, so no request.
  • Same age. Two 16s ask each other: 2 requests, not 4 and not 1.
  • One person. No one to ask, so 0.

Common mistakes

  • Using count[a] × count[a] for equal ages, which counts people asking themselves.
  • Writing the threshold with integer division, so a / 2 + 7 rounds down and odd ages slip through.
  • Counting each friendship once instead of each one-way request.

How to talk through it

  1. 1Clarify. Are requests one way? Can someone ask themself? How large can n get?
  2. 2Give the brute force. Test all ordered pairs: O(n²), too slow for 20,000 people.
  3. 3Spot the small range. Only 120 ages exist. Bucket people by age and reason about age pairs.
  4. 4Code the counting loop. Multiply the bucket sizes, and subtract self-requests when the ages match.
  5. 5Test out loud. Run [14, 14] and [18, 16] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?