Count Unhappy Friends

Solution For Count Unhappy Friends

The Count Unhappy Friends problem on LeetCode is a type of mathematical problem that requires you to count the number of unhappy friends in a group. In this problem, you are given a set of friends and their preferences for each other. You are also provided the pair of friends who are assigned to each other.

The problem statement is as follows:

There are n friends that are split into two groups: a and b. Each friend is assigned a unique ID starting from 0 to n-1. You are given an integer array preferences, which is of size n x n and represents the liking of the ith friend towards the jth friend, where preferences[i][j] = k means that the ith friend likes the jth friend the most if k == 0, the ith friend likes the jth friend the least if k == n-1, otherwise, the ith friend likes the jth friend a little bit more each time k moves towards n-1. A friend x is unhappy if x is assigned to a group that he/she dislikes the most.

Return the number of unhappy friends.

Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]] Output: 2
Explanation:
Friend 1 is unhappy because he is assigned to be with friend 2 whom he dislikes the most.
Friend 3 is unhappy because he is assigned to be with friend 0 whom he dislikes the most.

Solution:

To solve the Count Unhappy Friends problem, we need to first understand the problem statement and the requirements. We have two sets of friends, a and b, and each friend has a unique ID. We are given preferences of friends, which represents the liking of each friend towards each other. The integer array preferences is of size n x n and stores the liking of the ith friend towards the jth friend.

We also have a pair of friends who are assigned to each other. We need to find the number of unhappy friends who are assigned to a group they dislike the most.

We can begin by iterating over each pair of friends and checking if they are unhappy. If a friend is unhappy, we can count the number of unhappy friends.

To check if a friend is unhappy, we can compare their preferences with the friend they are assigned to. If the assigned friend is not the one the current friend likes the most, they are unhappy.

Here’s the implementation of the solution in Python:

def unhappyFriends(n, preferences, pairs):
# Store the preference of each friend
pref = [[0] * n for _ in range(n)] for i in range(n):
for j in range(n-1):
pref[i][preferences[i][j]] = j

# Store the pair of friends
pair = {}
for p in pairs:
    pair[p[0]] = p[1]
    pair[p[1]] = p[0]

unhappy = 0
for i in range(n):
    j = pair[i]
    for k in range(n):
        if k == i or k == j:
            continue
        if pref[i][k] < pref[i][j] and pref[k][i] < pref[k][pair[k]]:
            unhappy += 1
            break

return unhappy

In this implementation, we first store the preference of each friend in a 2D array pref. We then store the pair of friends in a dictionary pair.

We then iterate over each friend and check if they are unhappy. If a friend is unhappy, we increase the count of unhappy friends.

We check if a friend is unhappy by comparing their preferences with the friend they are assigned to. If the assigned friend is not the one the current friend likes the most, they are unhappy. We break the loop once we find an unhappy friend.

We return the count of unhappy friends as the result.

The time complexity of this solution is O(n^2) and the space complexity is O(n^2).

Step by Step Implementation For Count Unhappy Friends

class Solution {
    public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
        // We will use an array to keep track of how unhappy each person is.
        // A person is unhappy if they are paired with someone they don't like.
        int[] unhappyCount = new int[n];
        
        // We will loop through each pair and check if the two people in the pair
        // are unhappy. If they are, we will increment the count for each person.
        for (int i = 0; i < pairs.length; i++) {
            int person1 = pairs[i][0];
            int person2 = pairs[i][1];
            
            // Check if person1 likes person2
            if (preferences[person1][person2] != 1) {
                unhappyCount[person1]++;
            }
            
            // Check if person2 likes person1
            if (preferences[person2][person1] != 1) {
                unhappyCount[person2]++;
            }
        }
        
        // We will keep track of the total number of unhappy people.
        int unhappyTotal = 0;
        
        // We will loop through each person and check if they are unhappy.
        // If they are, we will check if there is someone else they would rather be paired with.
        // If so, we will increment the unhappy count.
        for (int i = 0; i < n; i++) {
            // Check if the person is unhappy.
            if (unhappyCount[i] > 0) {
                // The person is unhappy, so we will loop through their preferences.
                for (int j = 0; j < n - 1; j++) {
                    // Get the person they prefer at this index.
                    int person = preferences[i][j];
                    
                    // Get the person that person is currently paired with.
                    int pairedWith = -1;
                    for (int k = 0; k < pairs.length; k++) {
                        if (pairs[k][0] == person || pairs[k][1] == person) {
                            pairedWith = pairs[k][0] == person ? pairs[k][1] : pairs[k][0];
                            break;
                        }
                    }
                    
                    // Check if the person prefers the current person over the person they are paired with.
                    // If so, we have found an unhappy person, so we will increment the count and break out of the loop.
                    if (preferences[person][i] < preferences[person][pairedWith]) {
                        unhappyTotal++;
                        break;
                    }
                }
            }
        }
        
        return unhappyTotal;
    }
}
def count_unhappy_friends(n, preferences, pairs):
    # n: number of friends
    # preferences: 2D array of friend preferences
    # pairs: 2D array of friend pairs
    
    # Create a list of all friends
    friends = [i for i in range(n)]
    
    # Create a dictionary of all friend pairs
    pairs_dict = {}
    for pair in pairs:
        pairs_dict[pair[0]] = pair[1]
        pairs_dict[pair[1]] = pair[0]
        
    # Iterate through all friends
    count = 0
    for friend in friends:
        
        # Iterate through all other friends
        for other_friend in friends:
            
            # Check if other_friend is not friend's partner and that friend prefers other_friend to friend's partner
            if other_friend != pairs_dict[friend] and preferences[friend][other_friend] < preferences[friend][pairs_dict[friend]]:
                
                # Iterate through all other_friend's preferences
                for other_friend_preference in preferences[other_friend]:
                    
                    # Check if other_friend prefers friend's partner to friend
                    if other_friend_preference == pairs_dict[friend] and preferences[other_friend][friend] < preferences[other_friend][other_friend_preference]:
                        count += 1
                        break
                    
    return count
var countUnhappyFriends = function(n, preferences, pairs) {
    // create a hashmap of each person and their respective friends
    let map = {};
    for (let i = 0; i < n; i++) {
        map[i] = {};
        map[i].friends = [];
        for (let j = 0; j < n - 1; j++) {
            if (preferences[i][j] === 1) {
                map[i].friends.push(j);
            }
        }
    }
    
    // create a hashmap of each person and their respective pairs
    let pairMap = {};
    for (let i = 0; i < pairs.length; i++) {
        let person1 = pairs[i][0];
        let person2 = pairs[i][1];
        pairMap[person1] = person2;
        pairMap[person2] = person1;
    }
    
    // iterate through each person and check if they are unhappy
    let unhappyCount = 0;
    for (let person in map) {
        let friends = map[person].friends;
        let currentPair = pairMap[person];
        for (let i = 0; i < friends.length; i++) {
            let friend = friends[i];
            if (friend === currentPair) continue;
            // check if the person's friend is happier with someone else
            if (preferences[friend][person] < preferences[friend][currentPair]) {
                unhappyCount++;
                break;
            }
        }
    }
    
    return unhappyCount;
};
There are two possible solutions for this problem:

1) Use a hash map to keep track of the number of times each person is unhappy. Iterate through the list of friends and check if each person is unhappy. If they are, increment the count for that person in the hash map. Finally, return the count of unhappy people.

2) Use a set to keep track of the people who are unhappy. Iterate through the list of friends and check if each person is unhappy. If they are, add them to the set. Finally, return the size of the set.
using System; 

public class Solution { 

public int CountUnhappyFriends(int n, int[][] preferences, int[][] pairs) { 

// n is the number of friends 
// preferences is a 2D array where preferences[i][j] is the ith person's preference for the jth person 
// pairs is a 2D array where pairs[i][0] is the ith person's partner and pairs[i][1] is the jth person's partner 

// initialize an empty array to keep track of unhappy friends 
int[] unhappyFriends = new int[n]; 

// iterate through each person 
for (int i = 0; i < n; i++) { 

// iterate through each person's preferences 
for (int j = 0; j < n - 1; j++) { 

// if the ith person's preference for the jth person is lower than their partner's preference for that person 
if (preferences[i][j] < preferences[i][pairs[i][0]] && preferences[pairs[i][1]][j] < preferences[pairs[i][1]][i]) { 

// increment the number of unhappy friends for that person 
unhappyFriends[i]++; 
} 
} 
} 

// return the number of unhappy friends 
return unhappyFriends; 
} 
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]