Skip to content

Commit c263c2f

Browse files
committed
Create friends-of-appropriate-ages.py
1 parent 2a90a36 commit c263c2f

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Python/friends-of-appropriate-ages.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Time: O(a^2 + n), a is the number of ages,
2+
# n is the number of people
3+
# Space: O(a)
4+
5+
# Some people will make friend requests.
6+
# The list of their ages is given and ages[i] is the age of the ith person.
7+
#
8+
# Person A will NOT friend request person B (B != A)
9+
# if any of the following conditions are true:
10+
#
11+
# age[B] <= 0.5 * age[A] + 7
12+
# age[B] > age[A]
13+
# age[B] > 100 && age[A] < 100
14+
# Otherwise, A will friend request B.
15+
#
16+
# Note that if A requests B, B does not necessarily request A.
17+
# Also, people will not friend request themselves.
18+
#
19+
# How many total friend requests are made?
20+
#
21+
# Example 1:
22+
#
23+
# Input: [16,16]
24+
# Output: 2
25+
# Explanation: 2 people friend request each other.
26+
# Example 2:
27+
#
28+
# Input: [16,17,18]
29+
# Output: 2
30+
# Explanation: Friend requests are made 17 -> 16, 18 -> 17.
31+
# Example 3:
32+
#
33+
# Input: [20,30,100,110,120]
34+
# Output:
35+
# Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
36+
#
37+
# Notes:
38+
# - 1 <= ages.length <= 20000.
39+
# - 1 <= ages[i] <= 120.
40+
41+
try:
42+
xrange # Python 2
43+
except NameError:
44+
xrange = range # Python 3
45+
46+
import collections
47+
48+
49+
class Solution(object):
50+
def numFriendRequests(self, ages):
51+
"""
52+
:type ages: List[int]
53+
:rtype: int
54+
"""
55+
def request(a, b):
56+
return 0.5*a+7 < b <= a
57+
58+
c = collections.Counter(ages)
59+
return sum(int(request(a, b)) * c[a]*(c[b]-int(a == b))
60+
for a in c
61+
for b in c)

0 commit comments

Comments
 (0)