Leetcode 852 Solution

This article provides solution to leetcode question 852 (friends-of-appropriate-ages)

https://leetcode.com/problems/friends-of-appropriate-ages

Solution

class Solution:
    def numFriendRequests(self, ages: List[int]) -> int:
        ages.sort()

        ans = 0
        for i, age in enumerate(ages):
            lbound = age * 0.5 + 7
            rbound = age

            start = 0
            end = 0

            l = 0
            r = len(ages) - 1
            while l < r:
                m = (l + r) // 2
                if ages[m] > lbound:
                    r = m
                else:
                    l = m + 1
            start = l

            l = 0
            r = len(ages) - 1
            while l < r:
                m = (l + r) // 2
                if ages[m] > rbound:
                    r = m
                else:
                    l = m + 1
            end = l if ages[l] > rbound else len(ages)

            ans += max(0, end - start - 1)

        return ans