LeetCode - Friends Of Appropriate Ages Solution - The Coding Shala

Home >> LeetCode >> Friend of Appropriate Ages

 In this post, we will see how to solve LeetCode's Friends Of Appropriate Ages Problem and its solution in Java.

Friends Of Appropriate Ages

Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person. 

Person A will NOT friend request person B (B != A) if any of the following conditions are true:

age[B] <= 0.5 * age[A] + 7
age[B] > age[A]
age[B] > 100 && age[A] < 100
Otherwise, A will friend request B.

Note that if A requests B, B does not necessarily request A.  Also, people will not friend request themselves.

How many total friend requests are made?

Example 1:
Input: [16,16]
Output: 2
Explanation: 2 people friend request each other.

Example 2:
Input: [16,17,18]
Output: 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.

Example 3:
Input: [20,30,100,110,120]
Output: 3
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.

Friends Of Appropriate Ages Java Solution

Approach 1:
We can use binary search here. If person B's range comes in 0.5 * age[A] + 7 then person A can sent friend request. Other two conditions became true if we sort the array.

Java Program: 

class Solution {
    public int numFriendRequests(int[] ages) {
        int ans = 0;
        Arrays.sort(ages);
        for(int i = 0; i < ages.length; i++) {
            int age = ages[i];
            //upper can be i but in same ages upper change
            //so need to find upper index also
            int upper = findIndex(ages, age);
            //lower index is from where all the ages comes in
            //range age[A]*.5 + 7 
            int lower = findIndex(ages, ((age/2)+7));
            ans += Math.max(upper-lower-1, 0);
        }
        return ans;
    }
    
    //binary search
    public static int findIndex(int[] ages, int target) {
        int start = 0;
        int end = ages.length-1;
        while(start <= end) {
            int mid = start + (end - start) / 2;
            if(ages[mid] <= target) start = mid + 1;
            else end = mid-1;
        }
        return start;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala