Skip to content

Practice Count Unhappy Friends

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#1583
LeetCode Problem

Count Unhappy Friends

Problem Statement

Each preferences[i] lists every other person from most to least preferred, and pairs matches all n people into disjoint pairs. A person x paired with y is unhappy if some person u paired with v prefers x to v and x prefers u to y. Return the number of unhappy people, counting each person only once.

Source: Count Unhappy Friends on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Output
2

# Example 2

Input
n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
Output
0

# Example 3

Input
n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
Output
4

Constraints

2 <= n <= 500
n is even.
preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i] does not contain i.
All values in preferences[i] are unique.
pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
Each person is contained in exactly one pair.

Related LeetCode Problems

Practice more problems similar to Count Unhappy Friends.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.