[LeetCode] Count Unhappy Friends

1583. Count Unhappy Friends

You are given a list of preferences for n friends, where n is always even.

For each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.

All the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.

However, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:

  • x prefers u over y, and
  • u prefers x over v.

Return the number of unhappy friends.

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
class Solution {
bool helper(int me, int matched, int target, vector<int>& A) {
for(auto& a : A) {
if(a == matched) return true;
if(a == target) return false;
}
return false;
}
public:
int unhappyFriends(int n, vector<vector<int>>& A, vector<vector<int>>& B) {
int res = 0;
vector<int> match(n);
for(auto& b : B) {
match[b[0]] = b[1];
match[b[1]] = b[0];
}
for(int i = 0; i < n; i++) {
bool happy = true;
for(auto& pref : A[i]) {
if(pref == match[i]) break;
if(!happy) break;
happy = helper(pref, match[pref], i, A[pref]);
}
res += !happy;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/15/PS/LeetCode/count-unhappy-friends/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.