Leetcode #1583: Count Unhappy Friends
In this guide, we solve Leetcode #1583 Count Unhappy Friends in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Simulation
Intuition
The rules are explicit, so simulating the process step by step is safest.
Careful state updates prevent subtle bugs.
Approach
Translate the rules into state updates and apply them in order.
Track the final state or aggregate as required.
Steps:
- Translate rules into state updates.
- Iterate for each step.
- Return the final state.
Example
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:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
Python Solution
class Solution:
def unhappyFriends(
self, n: int, preferences: List[List[int]], pairs: List[List[int]]
) -> int:
d = [{x: j for j, x in enumerate(p)} for p in preferences]
p = {}
for x, y in pairs:
p[x] = y
p[y] = x
ans = 0
for x in range(n):
y = p[x]
for i in range(d[x][y]):
u = preferences[x][i]
v = p[u]
if d[u][x] < d[u][v]:
ans += 1
break
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.