Problem 1583

Abstract / Summary

Given pairs of friends and their preferences, count how many friends end up with someone they did not prefer most after pairing.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1583.py

class Solution:
    def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
        result = 0

        # important constraint: "each person is contained in exactly one pair"

        good = {}
        for x, y in pairs:
            # better friends (those who might be potentially unhappy)
            better  = preferences[x].index(y)
            good[x] = preferences[x][ : better]

            # and the other way 'round
            better  = preferences[y].index(x)
            good[y] = preferences[y][ : better]

        # check inverse relation
        for x in good:
            for y in good[x]:
                if x in good[y]:
                    result += 1
                    break

        return result
24 lines | 783 bytes | submitted August 2, 2024 | GitHub   26% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (50k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation determines how many individuals in a group of n people are unhappy with their assigned partner. Unhappiness is defined by a mutual preference condition: a person x prefers some other person y over their current partner, and y also prefers x over their own partner. The algorithm proceeds in two phases - constructing a reduced preference view for each person and then scanning for the mutual condition.

Key Steps

Building Preference Prefixes

For every pair (x, y) the code locates the position of the partner inside each person’s full preference list. The slice up to (but not including) that position represents all friends that are better than the current partner. These slices are stored in a dictionary good keyed by the person’s index.

good = {}
for x, y in pairs:
    better = preferences[x].index(y)
    good[x] = preferences[x][:better]

    better = preferences[y].index(x)
    good[y] = preferences[y][:better]

The use of list.index directly yields the rank of the partner, and the slice operation creates a compact list containing only those candidates that could trigger unhappiness. If a partner is already the top choice, the slice is empty, correctly representing that the person has no better friends.

Checking Mutual Preference

The second loop iterates over each person x and their list of better friends good[x]. For each candidate y in that list, the algorithm checks whether x also appears in y’s better-friend list good[y]. The moment such a reciprocal relationship is found, the result counter is incremented and the inner loop terminates for that x, because a single qualifying friend is sufficient to mark x as unhappy.

result = 0
for x in good:
    for y in good[x]:
        if x in good[y]:
            result += 1
            break

The break statement prevents unnecessary further checks for the same x, ensuring that each person contributes at most one to the final count.

Edge Cases Handled

When a person’s partner is their most preferred friend, the slice preferences[x][:better] becomes an empty list. The subsequent inner loop simply does not execute, meaning the person cannot be unhappy, which aligns with the problem definition.

If the input contains only a single pair, the dictionary good will hold two entries, each with an empty list (assuming both partners are each other’s top choice). The double loop will iterate over two empty lists, leaving result at zero, correctly indicating no unhappy friends.

The algorithm also gracefully handles the situation where multiple people share the same rank ordering but are paired differently; the dictionary lookup x in good[y] works regardless of list length or content.

Performance Optimizations

The code leverages direct indexing (list.index) to find the partner’s rank in O(k) time where k is the length of the individual’s preference list, but this work is performed only once per person. By storing only the prefix of better friends, the algorithm reduces the amount of data examined during the mutual-preference check, avoiding repeated scans of the full preference lists.

The dictionary good provides constant-time access to any person’s better-friend list, enabling the inner condition x in good[y] to be evaluated quickly. Moreover, the early break after detecting a qualifying friend eliminates further unnecessary comparisons for that person, which can significantly cut down the number of membership tests in dense preference scenarios.

Overall, the design balances the cost of building concise preference slices with the benefit of faster lookups during the mutual-preference verification phase.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big playground where all the children are paired up to play a game. Some children have a list of who they would rather play with, ranked from their absolute favorite down to the one they like the least.

The code starts by looking at every pair of friends on the playground. For each child, the code checks their list to see which friends they like more than the person they are currently playing with. These preferred friends are put into a special group for each child.

Once every child has a group of friends they secretly wish they were playing with, the code goes through the groups to see if there is a problem. It checks if there are two children who both prefer playing with each other instead of their current partners. If the code finds a pair like that, it means someone is feeling a little bit unhappy. It keeps track of every time this happens by counting up until it is finished checking everyone.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.81 | σ = 1.19

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
fsq C++
JoshCrozier JS
keineahnung2345 C++
suxrobGM C#
trung-hn Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
suxrobGM C#
trung-hn Python
23 links | 11 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 solutions   August 2, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality