Friends Of Appropriate Ages — LeetCode 825 Python Solution

MediumArrayTwo PointersBinary SearchSorting
Problem
#825
Reading time
2 min

The problem

There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.

Example

Input
ages = [16,16]
Output
2
Explanation
2 people friend request each other.

Python solution

Python
class Solution:
    def numFriendRequests(self, ages: List[int]) -> int:
        cnt = [0] * 121
        for x in ages:
            cnt[x] += 1
        ans = 0
        for ax, x in enumerate(cnt):
            for ay, y in enumerate(cnt):
                if not (ay <= 0.5 * ax + 7 or ay > ax or (ay > 100 and ax < 100)):
                    ans += x * (y - int(ax == ay))
        return ans

Complexity

MeasureComplexity
TimeO(n + m^2), where n is the length of the array \textit{ages}, and m is the maximum age, which is 121 in this problem
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 825. Friends Of Appropriate Ages is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 825. Friends Of Appropriate Ages?
LeetCode 825. Friends Of Appropriate Ages is rated Medium on LeetCode.
What is the time complexity of LeetCode 825. Friends Of Appropriate Ages?
The Python solution on this page runs in O(n + m^2), where n is the length of the array \textit{ages}, and m is the maximum age, which is 121 in this problem.
What is the space complexity of LeetCode 825. Friends Of Appropriate Ages?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 825. Friends Of Appropriate Ages cover?
LeetCode 825. Friends Of Appropriate Ages is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview