Count Unhappy Friends in a Pairing Given Ranked Preference Lists
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Given each friend's ranked preference list and a fixed pairing, count how many friends would rather be with someone who also prefers them over their own partner. It tests turning a two-sided preference condition into fast rank comparisons and counting each person only once.
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
- 0 <= x_i, y_i <= n - 1
- Each person is contained in exactly one pair.
Examples
Input: (4, [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], [[0, 1], [2, 3]])
Expected Output: 2
Explanation: Source example 1: friends 1 and 3 prefer each other over partners 0 and 2, while 0 and 2 have their first choice.
Input: (2, [[1], [0]], [[1, 0]])
Expected Output: 0
Explanation: Minimum valid size from the source: n = 2, the single pair lists the larger member first, and each friend's only choice is the partner.
Hints
- Record each friend's partner first. A pair may list either member first, so store the pairing in both directions.
- For a friend x paired with y, only the friends that x places ahead of y can satisfy the first condition.
- Once any single u makes x unhappy, x is counted, and the remaining choices for x cannot change the answer.