LeetCode Problem

How to Solve Count Unhappy Friends

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.

GhostInterview Help

Need help with Count Unhappy Friends without spending extra time grinding it?

GhostInterview can read Count Unhappy Friends from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #1583Array plus SimulationReviewed 2026-03-08
Difficulty
Medium
Primary pattern
Array plus Simulation
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

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

MetricValue
TimeDepends on the final approach
SpaceDepends 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.

How GhostInterview Helps

  • GhostInterview identifies the core Array plus Simulation pattern and constructs the rank matrix efficiently.
  • It flags common errors like forgetting the mutual preference requirement in unhappiness checks.
  • It optimizes iteration over friend pairs to minimize redundant checks and ensure correctness.

Topic Pages

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.

GhostInterview Solver

Need direct help with Count Unhappy Friends instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Count Unhappy Friends from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.