Friends Of Appropriate Ages Problem
Description
LeetCode Problem 825.
There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the i^th 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 * 10^4
- 1 <= ages[i] <= 120
Solution
Approach: Count People by Age
Checking every pair of people is O(n2), up to 4 · 108 pairs. But whether x sends a request to y depends only on their ages, and there are just 120 possible ages. So count how many people have each age and check pairs of ages instead.
- Build
count[a], the number of people ageda. - For every pair of ages
(x, y)from 1 to 120, decide whether a person agedxsends a request to a person agedy: it happens unlessy <= 0.5 * x + 7ory > x. The third rule never needs checking: ify > 100andx < 100, theny > xalready rules the pair out. - If the request is sent, every person aged
xsends one to every person agedy, which iscount[x] * count[y]requests.
The detail that is easy to miss is the pair x == y. People of the same age may request each other, but nobody requests themselves, so each of the count[x] people sends only count[x] - 1 requests: add count[x] * (count[x] - 1). For ages = [16, 16] that gives 2 · 1 = 2. Note that ages up to 14 never send anything, since y <= x <= 0.5 * x + 7 whenever x <= 14.
Complexity: O(n + A2) time and O(A) space, where n is the length of ages and A = 120 is the largest age.
class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
MAX_AGE = 120
count = [0] * (MAX_AGE + 1) # count[a] = number of people aged a
for age in ages:
count[age] += 1
def sends_request(x: int, y: int) -> bool:
# The third rule (y > 100 and x < 100) already fails y <= x, so it needs no check.
return not (y <= 0.5 * x + 7 or y > x)
requests = 0
for x in range(1, MAX_AGE + 1):
for y in range(1, MAX_AGE + 1):
if count[x] > 0 and count[y] > 0 and sends_request(x, y):
# Everyone aged x asks everyone aged y, except themselves when x == y.
requests += count[x] * (count[y] - (1 if x == y else 0))
return requests
Now write it from memory
Close the write-up and solve it yourself against the tests.