Problem Description
There are n persons on a social media website. Given an integer array ages where ages[i] is the age of the iᵗʰ person, person x will send a friend request to person y (with x ≠ y) if the following conditions are all met:
- age[y] > 0.5 * age[x] + 7
- age[y] ≤ age[x]
- It is not the case that age[y] > 100 and age[x] < 100. Return the total number of friend requests made.
Key Insights
- The friend request condition can be simplified to checking that age[y] > 0.5 * age[x] + 7 and age[y] ≤ age[x].
- Given that ages are within the range [1, 120], a frequency array of fixed size (e.g., 121 elements) can be used.
- Instead of comparing every pair, count the frequency of each age and then iterate over possible age pairs to compute the valid friend requests.
- If both persons have the same age, subtract self-requests since a person cannot send a friend request to themselves.
Space and Time Complexity
Time Complexity: O(120^2) ≈ O(1) when using the frequency approach due to the constant bounded range of ages. Space Complexity: O(1) since we use a fixed size array (size 121) for counting frequencies.
Solution
The solution involves first counting the number of individuals for each age. For each possible age a and for every age b from 15 to a (since ages below 15 will not satisfy the condition for most a’s), if b is greater than 0.5 * a + 7, then all individuals of age a can potentially send friend requests to all individuals of age b. If a and b are the same, we subtract self-requests by using count[a] * (count[a] - 1); otherwise, we add count[a] * count[b].