Friends Of Appropriate Ages
Friends Of Appropriate Ages is a medium arrays & hashing problem solved with the prefix sum strategy pattern.
The best approach, optimal (prefix sums over age counts), runs in O(n + A) time and O(A) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (check every ordered pair) up.
Problem
A social network has n members, and ages[i] is the age of member i.
Member x sends a friend request to member y (with x != y) unless at least one of these is true:
ages[y] <= 0.5 * ages[x] + 7ages[y] > ages[x]ages[y] > 100andages[x] < 100
Requests are one-way: x sending to y does not mean y sends to x. Nobody sends a request to themselves.
Return the total number of friend requests that are sent.
Examples
Example 1
- Input
ages = [18, 18, 17]- Output
4- Why
- Each 18 sends to the other 18 (2 requests) and each 18 sends to the 17, since 17 is above 0.5 * 18 + 7 = 16 (2 more). The 17 sends nothing, because both others are older.
Example 2
- Input
ages = [16, 17, 18]- Output
2- Why
- 17 sends to 16 (16 > 15.5) and 18 sends to 17 (17 > 16). 18 does not send to 16, because 16 is not above 16.
Example 3
- Input
ages = [20, 30, 100, 110, 120]- Output
3- Why
- 110 sends to 100, and 120 sends to 100 and 110. Everyone else is too far apart: for 30 the lower bound is 22, so 20 is too young.
Constraints
n == ages.length1 <= n <= 2 * 10^41 <= ages[i] <= 120
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (check every ordered pair) | O(n²) | O(1) |
| Count by age (pairs of ages) | O(n + A²) | O(A) |
| Optimal (prefix sums over age counts) | O(n + A) | O(A) |
1Brute force (check every ordered pair)
O(n²)There are n * (n - 1) ordered pairs, each checked in O(1).O(1)Only the counter.Try every ordered pair of different people (x, y) and apply the three rules directly. Count the pairs where none of the rules blocks the request.
- Set total = 0.
- For every x and every y with x != y: if none of the three blocking rules holds, add 1.
- Return total.
class Solution {
public int numFriendRequests(int[] ages) {
int n = ages.length, total = 0;
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
if (x != y && sends(ages[x], ages[y])) total++;
}
}
return total;
}
private boolean sends(int ax, int ay) {
return !(ay <= 0.5 * ax + 7 || ay > ax || (ay > 100 && ax < 100));
}
}class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
n = len(ages)
total = 0
for x in range(n):
for y in range(n):
if x != y and self.sends(ages[x], ages[y]):
total += 1
return total
def sends(self, ax, ay):
return not (ay <= 0.5 * ax + 7 or ay > ax or (ay > 100 and ax < 100))class Solution {
public:
int numFriendRequests(vector<int>& ages) {
int n = ages.size(), total = 0;
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
if (x != y && sends(ages[x], ages[y])) total++;
}
}
return total;
}
private:
bool sends(int ax, int ay) {
return !(ay <= 0.5 * ax + 7 || ay > ax || (ay > 100 && ax < 100));
}
};function numFriendRequests(ages) {
const n = ages.length;
let total = 0;
for (let x = 0; x < n; x++) {
for (let y = 0; y < n; y++) {
if (x !== y && sends(ages[x], ages[y])) total++;
}
}
return total;
function sends(ax, ay) {
return !(ay <= 0.5 * ax + 7 || ay > ax || (ay > 100 && ax < 100));
}
}2Count by age (pairs of ages)
O(n + A²)One pass counts the ages, then A * A pairs of ages with A = 120, which is a constant 14,400 checks.O(A)The count array has A + 1 entries.Whether x sends to y depends only on their two ages, and ages run from 1 to 120. So count how many people have each age, then try every pair of ages (ax, ay). If an age-ax person sends to an age-ay person, that pair of ages gives count[ax] * count[ay] requests. When ax == ay, the people of that age cannot send to themselves, so subtract count[ax]. The third rule is already covered by ay > ax, so only two checks are needed.
- Build count[a] = how many people are a years old.
- For every age ax with count[ax] > 0 and every age ay with count[ay] > 0:
- Skip the pair if ay <= 0.5 * ax + 7 or ay > ax.
- Otherwise add count[ax] * count[ay], and subtract count[ax] when ax == ay.
- Return the total.
class Solution {
public int numFriendRequests(int[] ages) {
int[] count = new int[121];
for (int a : ages) count[a]++;
int total = 0;
for (int ax = 1; ax <= 120; ax++) {
if (count[ax] == 0) continue;
for (int ay = 1; ay <= 120; ay++) {
if (count[ay] == 0 || ay <= 0.5 * ax + 7 || ay > ax) continue;
total += count[ax] * count[ay];
if (ax == ay) total -= count[ax];
}
}
return total;
}
}class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
count = [0] * 121
for a in ages:
count[a] += 1
total = 0
for ax in range(1, 121):
if count[ax] == 0:
continue
for ay in range(1, 121):
if count[ay] == 0 or ay <= 0.5 * ax + 7 or ay > ax:
continue
total += count[ax] * count[ay]
if ax == ay:
total -= count[ax]
return totalclass Solution {
public:
int numFriendRequests(vector<int>& ages) {
vector<int> count(121, 0);
for (int a : ages) count[a]++;
int total = 0;
for (int ax = 1; ax <= 120; ax++) {
if (count[ax] == 0) continue;
for (int ay = 1; ay <= 120; ay++) {
if (count[ay] == 0 || ay <= 0.5 * ax + 7 || ay > ax) continue;
total += count[ax] * count[ay];
if (ax == ay) total -= count[ax];
}
}
return total;
}
};function numFriendRequests(ages) {
const count = new Array(121).fill(0);
for (const a of ages) count[a]++;
let total = 0;
for (let ax = 1; ax <= 120; ax++) {
if (count[ax] === 0) continue;
for (let ay = 1; ay <= 120; ay++) {
if (count[ay] === 0 || ay <= 0.5 * ax + 7 || ay > ax) continue;
total += count[ax] * count[ay];
if (ax === ay) total -= count[ax];
}
}
return total;
}3Optimal (prefix sums over age counts)
O(n + A)One pass counts the ages, one pass of A = 120 builds the prefix sums, and each age is then handled in O(1).O(A)Two arrays of A + 1 entries.A person of age a sends to exactly the people whose age lies in the window 0.5 * a + 7 < age <= a. In whole numbers that is a / 2 + 8 up to a (integer division), and the window is empty below 15. With a prefix sum over the age counts, prefix[a] - prefix[a / 2 + 7] is the number of people in that window in O(1). Each of the count[a] people of age a is inside their own window, so each one sends to that many people minus one.
- Build count[a] for every age, and prefix[a] = count[1] + ... + count[a].
- For every age a from 15 to 120 with count[a] > 0:
- inRange = prefix[a] - prefix[a / 2 + 7], the people aged a / 2 + 8 through a.
- Add count[a] * (inRange - 1): every age-a person sends to everyone in the window except themselves.
- Return the total.
class Solution {
public int numFriendRequests(int[] ages) {
int[] count = new int[121];
for (int a : ages) count[a]++;
int[] prefix = new int[121];
for (int a = 1; a <= 120; a++) prefix[a] = prefix[a - 1] + count[a];
int total = 0;
for (int a = 15; a <= 120; a++) {
if (count[a] == 0) continue;
int inRange = prefix[a] - prefix[a / 2 + 7];
total += count[a] * (inRange - 1);
}
return total;
}
}class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
count = [0] * 121
for a in ages:
count[a] += 1
prefix = [0] * 121
for a in range(1, 121):
prefix[a] = prefix[a - 1] + count[a]
total = 0
for a in range(15, 121):
if count[a] == 0:
continue
in_range = prefix[a] - prefix[a // 2 + 7]
total += count[a] * (in_range - 1)
return totalclass Solution {
public:
int numFriendRequests(vector<int>& ages) {
vector<int> count(121, 0);
for (int a : ages) count[a]++;
vector<int> prefix(121, 0);
for (int a = 1; a <= 120; a++) prefix[a] = prefix[a - 1] + count[a];
int total = 0;
for (int a = 15; a <= 120; a++) {
if (count[a] == 0) continue;
int inRange = prefix[a] - prefix[a / 2 + 7];
total += count[a] * (inRange - 1);
}
return total;
}
};function numFriendRequests(ages) {
const count = new Array(121).fill(0);
for (const a of ages) count[a]++;
const prefix = new Array(121).fill(0);
for (let a = 1; a <= 120; a++) prefix[a] = prefix[a - 1] + count[a];
let total = 0;
for (let a = 15; a <= 120; a++) {
if (count[a] === 0) continue;
const inRange = prefix[a] - prefix[Math.floor(a / 2) + 7];
total += count[a] * (inRange - 1);
}
return total;
}Edge cases to test
- Everyone younger than 15: the lower bound 0.5 * a + 7 is at least a, so nobody sends anything
- Age 15 is the youngest that can send: the window is just [15, 15], so two 15-year-olds send to each other
- Many people of the same age a >= 15: each of them sends to all the others, c * (c - 1) requests
- Odd ages: 0.5 * 17 + 7 = 15.5, so 16 is allowed and the integer lower bound is a / 2 + 8
- A single person: no requests
- All 2 * 10^4 people aged 120: almost 4 * 10^8 requests, which still fits in an int
Hints
Hint 1
The third rule never matters on its own: if age[y] > 100 and age[x] < 100, then age[y] > age[x], which the second rule already forbids.
Hint 2
So x sends to y exactly when 0.5 * age[x] + 7 < age[y] <= age[x]. Only the ages matter, and there are just 120 of them.
Hint 3
Count how many people have each age. For an age a, the people it sends to are those with an age in a window that ends at a. A prefix sum over the counts gives the size of that window in O(1); remember to leave out the sender.
FAQ
What is the best time complexity for Friends Of Appropriate Ages?
Optimal (prefix sums over age counts) runs in O(n + A) time and O(A) extra space. One pass counts the ages, one pass of A = 120 builds the prefix sums, and each age is then handled in O(1).
Which pattern does Friends Of Appropriate Ages use?
It is a arrays & hashing problem that uses the prefix sum strategy pattern. Other problems with the same pattern: Subarray Sum Equals K, Subarray with given XOR, Range Sum Query - Immutable.
Is there a brute force solution for Friends Of Appropriate Ages?
Yes. Brute force (check every ordered pair) takes O(n²) time and O(1) space. Try every ordered pair of different people (x, y) and apply the three rules directly.
Which edge cases should I test for Friends Of Appropriate Ages?
Everyone younger than 15: the lower bound 0.5 a + 7 is at least a, so nobody sends anything; Age 15 is the youngest that can send: the window is just [15, 15], so two 15-year-olds send to each other; Many people of the same age a = 15: each of them sends to all the others, c (c - 1) requests; Odd ages: 0.5 17 + 7 = 15.5, so 16 is allowed and the integer lower bound is a / 2 + 8; A single person: no requests; All 2 10^4 people aged 120: almost 4 10^8 requests, which still fits in an int.