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:

  1. Create a Mapping of Pairs: We’ll create a mapping for each friend to their paired partner using the given pairs.

  2. Determine Preferences: We’ll utilize the preferences array to determine how each friend ranks their other friends.

  3. 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.

  4. Count Unhappy Friends: We’ll maintain a count of unhappy friends, according to the conditions specified in the problem statement.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
    def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
        # Create a mapping of pairs
        paired_with = {}
        for pair in pairs:
            paired_with[pair[0]] = pair[1]
            paired_with[pair[1]] = pair[0]

        # Create a matrix to store the rank of each friend for each person
        rank = [[0] * n for _ in range(n)]
        for i in range(n):
            for j in range(n-1):
                rank[i][preferences[i][j]] = j

        # Count of unhappy friends
        unhappy_count = 0

        # Check unhappiness for each friend
        for x in range(n):
            y = paired_with[x]
            for u in preferences[x]:
                # Stop when reaching the current paired partner
                if u == y:
                    break
                v = paired_with[u]
                # Check if x prefers u over y, and u prefers x over v
                if rank[x][u] < rank[x][y] and rank[u][x] < rank[u][v]:
                    unhappy_count += 1
                    break

        return unhappy_count

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.