Problem Description
Given a list of friend preferences and a set of pairings, determine the number of unhappy friends. A friend x is unhappy if there exists another friend u (paired with v) such that x prefers u over x’s paired friend y, and u also prefers x over u’s paired friend v.
Key Insights
- Create a quick lookup for each friend’s pair using a mapping.
- Precompute a ranking for each friend’s preferences to compare the ordering efficiently.
- For each friend x, iterate over the friends x prefers more than x’s paired friend.
- For each such friend u, check if u also favors x over u’s partner.
- Stop early for a friend once an unhappy condition is found.
Space and Time Complexity
Time Complexity: O(n^2), where n is the number of friends. We iterate through each friend’s preference list until their pair is encountered. Space Complexity: O(n^2) for storing the ranking of preferences for each friend.
Solution
We first create a dictionary (or array) pairMapping to quickly find a friend’s paired partner. Next, we build a ranking matrix (or dictionary) for each friend so that given any two friends, we can determine who is more preferred. For each friend x, we traverse x’s list of preferences up to the point where x’s pair appears. For every friend u in this loop, we check if u prefers x over u’s paired friend by comparing their ranking values. If both conditions are satisfied, friend x is marked as unhappy. Finally, we count and return the total number of unhappy friends.