Solving Leetcode Interviews in Seconds with AI: Friends Of Appropriate Ages
Introduction
In this blog post, we will explore how to solve the LeetCode problem "825" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true: age[y] <= 0.5 age[x] + 7 age[y] > age[x] age[y] > 100 && age[x] < 100 Otherwise, x will send a friend request to y. Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself. Return the total number of friend requests made. Example 1: Input: ages = [16,16] Output: 2 Explanation: 2 people friend request each other. Example 2: Input: ages = [16,17,18] Output: 2 Explanation: Friend requests are made 17 -> 16, 18 -> 17. Example 3: Input: ages = [20,30,100,110,120] Output: 3 Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. Constraints: n == ages.length 1 <= n <= 2 104 1 <= ages[i] <= 120
Explanation
Here's the breakdown of the solution:
- Counting Ages: Since the age range is limited (1 to 120), we can efficiently count the frequency of each age using an array. This avoids sorting the entire array, which would be less efficient.
- Iterating and Checking Conditions: We iterate through all possible age pairs (x, y) and check if the friendship conditions are met. The key is to consider the counts of each age to determine how many friend requests are made.
Optimized Calculation: The conditions are checked and the valid requests are counted.
Runtime Complexity: O(N), where N is the range of ages (120), which is effectively constant. Storage Complexity: O(N) where N is the range of ages
Code
def numFriendRequests(ages):
"""
Calculates the number of friend requests that will be made based on age criteria.
Args:
ages: A list of integers representing the ages of people.
Returns:
The total number of friend requests made.
"""
counts = [0] * 121 # Initialize counts for ages 1 to 120
for age in ages:
counts[age] += 1
total_requests = 0
for age_x in range(1, 121):
count_x = counts[age_x]
if count_x == 0:
continue # No one with this age
for age_y in range(1, 121):
count_y = counts[age_y]
if count_y == 0:
continue # No one with this age
if age_y <= 0.5 * age_x + 7:
continue
if age_y > age_x:
continue
if age_y > 100 and age_x < 100:
continue
total_requests += count_x * count_y
# Subtract requests to self
for age in range(1, 121):
count = counts[age]
total_requests -= count
return total_requests