Friends Of Appropriate Ages - Problem

There are n people on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.

A person x will not send a friend request to person y (where x != y) if any of the following conditions is true:

  • age[y] <= 0.5 * age[x] + 7
  • age[y] > age[x]
  • age[y] > 100 && age[x] < 100

Otherwise, person x will send a friend request to person y.

Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themselves.

Return the total number of friend requests made.

Input & Output

Example 1 — Basic Case
$ Input: ages = [16,16]
Output: 2
💡 Note: Both 16-year-olds can send requests to each other. Person 0 sends to person 1, and person 1 sends to person 0. Total: 2 requests.
Example 2 — Multiple Ages
$ Input: ages = [16,17,18]
Output: 2
💡 Note: Person aged 17 can send to 16 (17 > 0.5×17+7=15.5). Person aged 18 can send to 17 (18 > 0.5×18+7=16). Total: 2 requests.
Example 3 — No Valid Requests
$ Input: ages = [20,30,100,110,120]
Output: 3
💡 Note: Only age 100 people can send requests among themselves. With 1 person of age 100, no requests are possible between different people.

Constraints

  • 1 ≤ ages.length ≤ 2 × 104
  • 1 ≤ ages[i] ≤ 120

Visualization

Tap to expand
Friends Of Appropriate Ages INPUT ages array: 16 index 0 16 index 1 Two people, both age 16: Person X Person Y No request if: y <= 0.5*x + 7 y > x y > 100 AND x < 100 ALGORITHM STEPS 1 Count ages Build frequency array count[16] = 2 2 Check X to Y age[y]=16, age[x]=16 16 <= 0.5*16+7 = 15? NO 16 > 16? NO 3 Request valid! All conditions false 4 Calculate total Same age: n*(n-1) 2 * (2-1) = 2 FINAL RESULT Friend Requests: X (16) Y (16) Request 1 Request 2 Total Requests: 2 Output: 2 [OK] Both can send to each other (same age) Key Insight: For same-age pairs: if age > 14, they can send requests to each other. Formula: count[age] * (count[age] - 1) for valid same-age groups. Use counting sort (ages 1-120) for O(n) optimal solution instead of O(n^2). TutorialsPoint - Friends Of Appropriate Ages | Optimal Solution
Asked in
Facebook 35 Google 28 Amazon 22
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen