The Friends Of Appropriate Ages interview question asks you to calculate the total number of friend requests sent among a group of people given their ages. The rules for sending a friend request from person x to person y are strictly defined:
x will NOT send a request to y if any of these conditions are true:
age[y] <= 0.5 * age[x] + 7age[y] > age[x]age[y] > 100 and age[x] < 100 (Though rule 2 already covers this in standard logic).
You need to return the total number of valid requests.Companies like Meta and Amazon ask this math and array interview pattern to test your ability to translate logical conditions into an efficient counting algorithm. A naive O(N^2) approach checking every pair will timeout. It evaluates your ability to use Frequency Counting or Sorting and Two Pointers to optimize the solution to O(N) or O(N log N).
This problem is best solved using a Frequency Array (Counting Sort logic). Since ages are limited (1 to 120), you can:
ageA and ageB, check the three conditions.ageA to ageB is count[ageA] * count[ageB].ageA == ageB and it's valid, the number of requests is count[ageA] * (count[ageA] - 1) because a person doesn't send a request to themselves.Ages: [16, 16]
count[16] = 2.ageA = 16, ageB = 16:
16 <= 0.5 * 16 + 7 -> 16 <= 15 (False)16 > 16 (False)count[16] * (count[16] - 1) = 2 * 1 = 2.
Result: 2 requests (Person 1 -> Person 2, Person 2 -> Person 1).0.5 * age) loosely without considering edge cases, though integer logic age[y] <= age[x] / 2 + 7 is usually fine.Whenever the range of values is small and fixed (like ages 1-120, or letters a-z), a frequency array is almost always the key to an O(N) solution. It turns a "compare every person" problem into a "compare every age group" problem.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Subsequences That Satisfy the Given Sum Condition | Medium | Solve | |
| Successful Pairs of Spells and Potions | Medium | Solve | |
| The Latest Time to Catch a Bus | Medium | Solve | |
| Count the Number of Fair Pairs | Medium | Solve | |
| 3Sum Smaller | Medium | Solve |