Count Unhappy Friends
The problem is about finding the number of unhappy friends based on the given preferences and pairings. We will create a solution by following these steps:
Create a Mapping of Pairs: We’ll create a mapping for each friend to their paired partner using the given pairs.
Determine Preferences: We’ll utilize the preferences array to determine how each friend ranks their other friends.
Check Unhappiness: For each friend, we’ll check if there exists a friend they prefer over their paired partner and whether that preferred friend also prefers them over their paired partner.
Count Unhappy Friends: We’ll maintain a count of unhappy friends, according to the conditions specified in the problem statement.
Here’s the code:


The rank
matrix helps to quickly determine how each person ranks their friends. The outer loop iterates through each friend, while the inner loop checks the preferences of that friend. If the conditions for unhappiness are met, we increment the count and move to the next friend.
The given code snippet handles the constraints provided and should return the correct number of unhappy friends for the given input.