Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to count number of unhappy friends in Python
In this problem, we need to count unhappy friends based on their preferences and pairings. A friend is unhappy if they are paired with someone but prefer another person who also prefers them back over their current partners.
Problem Definition
Given preferences and pairs, a friend x is unhappy if:
- x is paired with y
- There exists a friend u (paired with v) such that:
- x prefers u over y, and
- u prefers x over v
Algorithm Steps
We solve this by building a preference graph:
- Create a graph where graph[person][preferred] = 1 means person prefers 'preferred' over their current partner
- For each pair, record all friends preferred over the current partner
- Check if any preferred friend also prefers the person back
Example
Let's understand with the given example where preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]] and pairs = [[0, 1], [2, 3]]:
from collections import defaultdict
def solve(preferences, pairs):
graph = defaultdict(dict)
# Build preference graph
for start, end in pairs:
# For start person, record all friends preferred over end
for pref in preferences[start]:
if pref == end:
break
graph[start][pref] = 1
# For end person, record all friends preferred over start
for pref in preferences[end]:
if pref == start:
break
graph[end][pref] = 1
unhappy = 0
# Count unhappy friends
for start, end in pairs:
# Check if start is unhappy
for pref in graph[start]:
if graph[pref].get(start, None):
unhappy += 1
break
# Check if end is unhappy
for pref in graph[end]:
if graph[pref].get(end, None):
unhappy += 1
break
return unhappy
preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]]
pairs = [[0, 1], [2, 3]]
print(solve(preferences, pairs))
2
How It Works
In the example:
- Person 0 is paired with 1 but prefers 3 over 1, and person 3 prefers 0 over their partner 2 ? unhappy
- Person 1 is paired with 0 and prefers 3 over 0, but person 3 doesn't prefer 1 over 2 ? happy
- Person 2 is paired with 3 and has no one preferred over 3 ? happy
- Person 3 is paired with 2 but prefers 1 over 2, and person 1 prefers 3 over their partner 0 ? unhappy
Conclusion
This solution uses a preference graph to efficiently identify mutual preferences between friends. The algorithm has O(n²) time complexity where n is the number of friends.
Advertisements
