Leetcode 825. Friends Of Appropriate Ages
You are given an array ages
where ages[i]
is the age of the i-th person. A person A
can send a friend request to person B
if the following conditions are met:
age[B] <= 0.5 * age[A] + 7
age[B] > age[A]
age[B] > 100 && age[A] < 100
Given these conditions, return the total number of friend requests made.
age[B] = age[A]
requests allowed?ages
array or any constraints on it?Assuming the constraints are reasonably large (say up to a few thousand elements in ages
and age ranges from 1 to 120).
We will:
import java.util.Arrays;
public class FriendsOfAppropriateAges {
public int numFriendRequests(int[] ages) {
// Sort the ages array to facilitate efficient range queries
Arrays.sort(ages);
int totalRequests = 0;
for (int i = 0; i < ages.length; i++) {
int ageA = ages[i];
if (ageA < 15) continue; // No person with age < 15 can send any valid request
// Find ageB's lower and upper bounds
int minAgeB = ageA / 2 + 7;
int maxAgeB = ageA;
int countInRange = countInRange(ages, minAgeB, maxAgeB);
totalRequests += (countInRange - 1); // Exclude self from the count
}
return totalRequests;
}
private int countInRange(int[] ages, int minAge, int maxAge) {
return upperBound(ages, maxAge) - lowerBound(ages, minAge);
}
private int lowerBound(int[] ages, int minAge) {
int left = 0, right = ages.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (ages[mid] > minAge) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private int upperBound(int[] ages, int maxAge) {
int left = 0, right = ages.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (ages[mid] <= maxAge) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
public static void main(String[] args) {
FriendsOfAppropriateAges solution = new FriendsOfAppropriateAges();
int[] ages = {16, 17, 18};
System.out.println(solution.numFriendRequests(ages)); // Output 2
}
}
ages
array.countInRange
, which involves two binary searches, takes (O(\log n)). Since we do this for each age, this step takes (O(n \log n)) in total.Thus, the overall time complexity is (O(n \log n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?