LeetCode 1583: Count Unhappy Friends Solution
Master LeetCode problem 1583 (Count Unhappy Friends), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1583. Count Unhappy Friends
Problem Explanation
Explanation:
To solve this problem, we need to iterate through each pair of friends and check if they are unhappy based on the given preferences. We can create a map to store the preferences of each friend for quick lookups. Then, we iterate through each pair, compare the preferences of the friends in the pair, and count the number of unhappy friends accordingly.
- Create a map to store the preferences of each friend.
- Iterate through each pair of friends.
- Check if the pair is unhappy based on the preferences.
- Count the number of unhappy friends.
Time Complexity: O(n^2) where n is the number of friends
Space Complexity: O(n)
:
Solution Code
class Solution {
public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
int[] pairMap = new int[n];
int[][] prefMap = new int[n][n];
for (int i = 0; i < n; i++) {
pairMap[pairs[i][0]] = pairs[i][1];
pairMap[pairs[i][1]] = pairs[i][0];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
prefMap[i][preferences[i][j]] = j;
}
}
int count = 0;
for (int i = 0; i < n; i++) {
int pair = pairMap[i];
int pairPref = prefMap[i][pair];
for (int j = 0; j < pairPref; j++) {
int other = preferences[i][j];
int otherPair = pairMap[other];
if (prefMap[other][i] < prefMap[other][otherPair]) {
count++;
break;
}
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1583 (Count Unhappy Friends)?
This page provides optimized solutions for LeetCode problem 1583 (Count Unhappy Friends) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1583 (Count Unhappy Friends)?
The time complexity for LeetCode 1583 (Count Unhappy Friends) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1583 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1583 in Java, C++, or Python.