Skip to main content
Back to problems
#825
Medium Algorithms

Friends of appropriate ages

Array Two Pointers Binary Search Sorting
49.9% acceptance
Feb 22, 2026
879
1275
There are n persons 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 a person y (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, x will send a friend request to 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 themself. Return the total number of friend requests made.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
/*
 * There are n persons 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 a person y (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, x will send a friend request to 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 themself.
 * Return the total number of friend requests made.
 * Example 1:
 * Input: ages = [16,16]
 * Output: 2
 * Explanation: 2 people friend request each other.
 * Example 2:
 * Input: ages = [16,17,18]
 * Output: 2
 * Explanation: Friend requests are made 17 -> 16, 18 -> 17.
 * Example 3:
 * Input: ages = [20,30,100,110,120]
 * Output: 3
 * Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
 * Constraints:
 * n == ages.length
 * 1 <= n <= 2 * 104
 * 1 <= ages[i] <= 120
 */

impl Solution {
  pub fn num_friend_requests(ages: Vec<i32>) -> i32 {
    let mut count = [0i32; 121];
    for &a in &ages { count[a as usize] += 1; }
    let mut ans = 0;
    for a in 1..=120i32 {
      if count[a as usize] == 0 { continue; }
      for b in 1..=120i32 {
        if b <= a/2 + 7 { continue; }
        if b > a { continue; }
        if b > 100 && a < 100 { continue; }
        if a == b {
          ans += count[a as usize] * (count[a as usize] - 1);
        } else {
          ans += count[a as usize] * count[b as usize];
        }
      }
    }
    ans
  }
}