Magicsheet logo

Friends Of Appropriate Ages

Medium
12.5%
Updated 8/1/2025

Friends Of Appropriate Ages

What is this problem about?

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:

  1. age[y] <= 0.5 * age[x] + 7
  2. age[y] > age[x]
  3. 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.

Why is this asked in interviews?

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).

Algorithmic pattern used

This problem is best solved using a Frequency Array (Counting Sort logic). Since ages are limited (1 to 120), you can:

  1. Count the frequency of each age.
  2. Iterate through all possible pairs of ages (from 1 to 120).
  3. For each pair of ages ageA and ageB, check the three conditions.
  4. If valid, the number of requests sent from people of ageA to ageB is count[ageA] * count[ageB].
  5. If 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.

Example explanation

Ages: [16, 16]

  1. Frequencies: count[16] = 2.
  2. Check ageA = 16, ageB = 16:
    • 16 <= 0.5 * 16 + 7 -> 16 <= 15 (False)
    • 16 > 16 (False)
    • Both are < 100.
    • It's a valid pair.
  3. Requests: count[16] * (count[16] - 1) = 2 * 1 = 2. Result: 2 requests (Person 1 -> Person 2, Person 2 -> Person 1).

Common mistakes candidates make

  • O(N^2) Brute Force: Iterating through the input array with nested loops, which is too slow for 10^5 elements.
  • Self-Requests: Forgetting to subtract 1 when people of the exact same age send requests to each other.
  • Float Comparison: Using float division (0.5 * age) loosely without considering edge cases, though integer logic age[y] <= age[x] / 2 + 7 is usually fine.

Interview preparation tip

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.

Similar Questions