#1583

Count Unhappy Friends

Medium
ArraySimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a ranking matrix to quickly determine preferences, allowing us to check unhappiness in constant time. This significantly reduces the number of comparisons needed.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a rank matrix where rank[i][j] indicates the preference rank of friend j for friend i.
  2. 2Step 2: For each pair in pairs, check if either friend is unhappy by using the rank matrix.
  3. 3Step 3: Count the number of unhappy friends based on the conditions provided.
solution.py12 lines
1def countUnhappyFriends(n, preferences, pairs):
2    rank = [[0] * n for _ in range(n)]
3    for i in range(n):
4        for j, friend in enumerate(preferences[i]):
5            rank[i][friend] = j
6    unhappy_count = 0
7    for x, y in pairs:
8        for u, v in pairs:
9            if x != u and rank[x][u] < rank[x][y] and rank[u][x] < rank[u][v]:
10                unhappy_count += 1
11                break
12    return unhappy_count

Complexity note: The optimal approach runs in linear time due to the use of a pre-computed ranking matrix, allowing for constant time checks for unhappiness.

  • 1Using a ranking matrix allows for efficient preference comparisons.
  • 2Understanding the conditions for unhappiness is crucial for implementing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.