#825
Friends Of Appropriate Ages
MediumArrayTwo PointersBinary SearchSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
We can optimize the process by sorting the ages and using a single loop with a two-pointer technique to count valid friend requests, which reduces unnecessary comparisons.
⚙️
Algorithm
3 steps- 1Step 1: Sort the ages array.
- 2Step 2: Initialize a counter for friend requests.
- 3Step 3: Use a loop to iterate through each age and use a two-pointer technique to find the range of valid ages that can receive requests.
solution.py11 lines
1def numFriendRequests(ages):
2 ages.sort()
3 count = 0
4 n = len(ages)
5 for i in range(n):
6 for j in range(i + 1, n):
7 if ages[j] > ages[i]:
8 if not (ages[j] <= 0.5 * ages[i] + 7 or (ages[j] > 100 and ages[i] < 100)):
9 count += 1
10 return count + (ages.count(ages[i]) - 1) * (ages.count(ages[i])) // 2
11ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the nested loop runs in O(n²) in the worst case, but we avoid many unnecessary checks. The space complexity is O(1) as we are using a constant amount of extra space.
- 1Understanding the conditions for sending friend requests is crucial.
- 2Sorting the ages can help reduce the number of comparisons needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.