LeetCode 1583: Count Unhappy Friends
LeetCode 1583 Solution 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)
:
LeetCode 1583 Solutions in Java, C++, Python
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;
}
}
Interactive Code Editor for LeetCode 1583
Improve Your LeetCode 1583 Solution
Use the editor below to refine the provided solution for LeetCode 1583. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...