Leetcode 825: Friends Of Appropriate Ages

grid47
grid47
Exploring patterns and algorithms
Aug 16, 2024 6 min read

You are given an integer array ages, where each element represents the age of a person on a social media platform. A person will not send a friend request to another person if any of the following conditions are true:

  1. The recipient’s age is less than or equal to half of the sender’s age plus 7.
  2. The recipient’s age is greater than the sender’s age.
  3. The recipient’s age is greater than 100 and the sender’s age is less than 100.

Otherwise, the sender can send a friend request. Return the total number of friend requests made between people.

Problem
Approach
Steps
Complexity
Input: The input consists of a single integer array `ages` of length `n` (the number of people). Each element represents the age of a person.
Example: Input: ages = [18, 20, 30, 40]
Constraints:
• 1 <= n <= 2 * 10^4
• 1 <= ages[i] <= 120
Output: The output should be an integer representing the total number of valid friend requests made according to the given conditions.
Example: Output: 4
Constraints:
• The output must be an integer representing the number of friend requests.
Goal: The goal is to compute the total number of friend requests by checking each pair of people in the `ages` array and applying the given conditions.
Steps:
• Step 1: Create a frequency map of the ages.
• Step 2: For each pair of distinct ages, check if they meet the conditions for sending a friend request.
• Step 3: If a valid request is possible, add the appropriate number of requests to the result.
Goal: Ensure that the input adheres to the problem constraints and that the logic handles all edge cases correctly.
Steps:
• All elements of `ages` must be within the range of 1 to 120.
Assumptions:
• There are no people with ages less than 1 or greater than 120.
• The problem guarantees that the input array will not be empty.
Input: Input: ages = [18, 20, 30, 40]
Explanation: The person with age 20 will send a request to 18, 30, and 40. The person with age 30 will send a request to 40. This results in a total of 4 requests.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus