LeetCode Problem Workspace

Count Unhappy Friends

Determine the number of unhappy friends in paired arrangements using array-based simulation for preference violations.

category

2

Topics

code_blocks

6

Code langs

hub

3

Related

Practice Focus

Medium · Array plus Simulation

bolt

Answer-first summary

Determine the number of unhappy friends in paired arrangements using array-based simulation for preference violations.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Array plus Simulation

Try AiBox Copilotarrow_forward

This problem requires calculating unhappy friends by analyzing each friend's preferences against their current pairings. Use an array-based simulation to quickly rank preferences and check for violations where a friend prefers someone else who also prefers them. Efficiently handling comparisons with a precomputed ranking matrix ensures O(1) checks for each friend pairing and avoids redundant iterations.

Problem Statement

You are given n friends labeled from 0 to n-1, where n is always even. Each friend has a list of preferences indicating other friends in order of most to least preferred. All friends are grouped into pairs provided in the list pairs, where each pair consists of two friends.

A friend x is considered unhappy if there exists another friend u such that x prefers u over their current partner y, and u also prefers x over their current partner v. The goal is to compute the total number of unhappy friends in the given pairings according to these preference rules.

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

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.

Example 2

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

Output: 0

Both friends 0 and 1 are happy.

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

Example details omitted.

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.

Solution Approach

Precompute Preference Ranks

Create a rank matrix where rank[i][j] indicates the preference order of friend j for friend i. This allows O(1) lookup to determine if a friend prefers someone over their current partner.

Iterate Over Pairs

For each friend x, check every other friend u to see if x prefers u over their pair and if u prefers x over their own pair. Count x as unhappy if both conditions hold.

Aggregate Unhappy Counts

Use a boolean array to mark unhappy friends while iterating. Finally, sum all marked friends to get the total number of unhappy friends, ensuring no double counting and respecting the array simulation structure.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Time complexity is O(n^2) due to checking each friend against all others using the precomputed rank matrix. Space complexity is O(n^2) for the rank matrix and O(n) for the boolean tracking array.

What Interviewers Usually Probe

  • Asks about handling preference violations efficiently using arrays.
  • Checks if candidate recognizes the need for O(1) preference lookups via a rank matrix.
  • Probes understanding of double counting avoidance in simulation loops.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to check mutual preference condition when determining unhappiness.
  • Iterating over pairs inefficiently instead of using rank matrix for O(1) comparisons.
  • Double counting unhappy friends by not tracking marked status properly.

Follow-up variants

  • Changing pairings dynamically and recomputing unhappy friends.
  • Adding weighted preferences to compute most unhappy friends.
  • Extending to n being odd with a single unpaired friend and adjusting rules accordingly.

FAQ

What is the best approach for Count Unhappy Friends?

Use an array-based simulation with a rank matrix to allow O(1) preference comparisons between friends.

Can this be solved without a rank matrix?

Yes, but checking preferences each time would increase time complexity to O(n^3), which is inefficient.

How do you avoid counting a friend twice as unhappy?

Use a boolean array to mark each unhappy friend and sum marked entries at the end.

Is this problem only about array simulation?

Yes, the primary pattern is Array plus Simulation to efficiently evaluate preference violations among pairs.

What are common mistakes in implementing Count Unhappy Friends?

Forgetting mutual preference checks, inefficiently iterating over all friends, or double counting unhappy friends.

terminal

Solution

Solution 1: Enumeration

We use an array $\textit{d}$ to record the closeness between each pair of friends, where $\textit{d}[i][j]$ represents the closeness of friend $i$ to friend $j$ (the smaller the value, the closer they are). Additionally, we use an array $\textit{p}$ to record the paired friend for each friend.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
Count Unhappy Friends Solution: Array plus Simulation | LeetCode #1583 Medium