Problem 1452

Abstract / Summary

Find people whose favorite companies are not completely included in another person's list of favorites.

Note

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

Python 1452.py

class Solution:
    def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
        likes = defaultdict(set)
        for i, favs in enumerate(favoriteCompanies):
            for f in favs:
                likes[f].add(i)

        for i, favs in enumerate(favoriteCompanies):
            same  = set()
            first = True
            for f in favs:
                if first:
                    same  = likes[f].copy()
                    first = False
                else:
                    same &= likes[f]

            if len(same) == 1:
                yield i
19 lines | 609 bytes | submitted November 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • String
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 provided implementation defines a Solution class with a single method peopleIndexes. The method receives a list of lists, where each inner list contains the names of companies favored by a particular person. It constructs a reverse index that maps each company to the set of people who listed it, then iterates through each person to determine whether any other person shares all of the same favorite companies. If no other person does, the method yields that person’s index. The use of a generator (yield) makes the result lazy, allowing callers to consume indices one at a time without materializing the entire list.

Construction of the reverse index

likes = defaultdict(set)
for i, favs in enumerate(favoriteCompanies):
    for f in favs:
        likes[f].add(i)

In this phase the code builds a dictionary (likes) where each key is a company name and the corresponding value is a set of person indices that include the company in their favorites. The defaultdict(set) eliminates the need for explicit existence checks, and the nested loops populate the mapping in a single pass over the input data.

Determining uniqueness of a person’s favorite set

for i, favs in enumerate(favoriteCompanies):
    same  = set()
    first = True
    for f in favs:
        if first:
            same  = likes[f].copy()
            first = False
        else:
            same &= likes[f]

For each person, the algorithm starts with an empty placeholder set (same) and a flag (first). The inner loop processes each company in the current person’s list:

  • On the first company, a copy of the set of people who like that company is stored in same. Copying preserves the original set in likes for later reuse.
  • For subsequent companies, the code performs an in-place intersection (&=) between same and the set of people who like the current company. This progressively narrows same to those individuals who share all companies seen so far.

The intersection operation is highly efficient because it works directly on hash-based sets, discarding non-matching indices at each step.

Yielding the qualifying indices

if len(same) == 1:
    yield i

After processing all companies for a person, same contains exactly those indices that have every company in the current list. If the size of same is one, the only element is the person being examined (i). This condition confirms that no other person’s favorite list is a superset of the current list, and the index is emitted via yield.

Edge-case handling

  • Empty input list - When favoriteCompanies is empty, the outer enumeration produces no iterations, and the generator yields nothing, which is a natural and safe outcome.
  • Person with an empty favorite list - The inner loop over favs is skipped, leaving same as an empty set and first unchanged. Consequently len(same) is zero, so the index is not yielded. This correctly excludes people who have no favorite companies from the result.
  • Company appearing only once - If a company is listed by a single person, its entry in likes is a singleton set. During intersection, this singleton quickly reduces same to that single index, guaranteeing that the person will be yielded unless another person also shares all the same companies.
  • All persons sharing a common company - When many people like the same company, the initial copy of likes[f] may be large, but subsequent intersections with other companies rapidly shrink the set, preventing unnecessary work.

Performance-related choices

  • Reverse indexing - By mapping companies to the people who like them, the algorithm avoids repeated scans of the entire input when checking for shared favorites. Each intersection works on pre-computed sets rather than recomputing membership on the fly.
  • Set copying only once per person - The first company’s set is copied, while later companies are intersected in place. This avoids mutating the original sets stored in likes, preserving them for other persons’ calculations.
  • In-place intersection (&=) - Using the in-place operator modifies the existing set rather than creating a new temporary set at each step, reducing allocation overhead.
  • Lazy result generation - The use of yield means that indices are produced as they are discovered, which can be advantageous when the caller only needs a subset of results or wishes to process them incrementally.

Overall, the code leverages Python’s built-in set operations and a reverse index to efficiently identify people whose list of favorite companies is not completely covered by any other person.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a group of friends who each have a list of their favorite toy stores. Some people might like the same stores as others. The goal is to find the people who have a unique combination of favorite stores because nobody else has the exact same collection of favorites as them.

First, the code creates a giant map to keep track of who likes which store. It looks at every name on every list and writes down the number of the person who likes that store. This makes it easy to see which people like a specific shop.

Next, it visits each person one by one to look at the list of stores they enjoy. It picks a starting point by taking all the people who like the first store on the list. Then, it looks at the other stores those people like and compares the lists. It keeps shrinking the group of potential matches until it finds everyone who likes all the same stores as that person. If there is only one person in that final group, it means the person is special and unique because nobody else has those exact favorites. That person gets a gold star.

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 | μ = 5.93 | σ = 1.76

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++ Java Python TS
WalkCCC Python
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC Python
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
23 links | 14 authors | 7 languages

Videos

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

Solved On The Same Day

10 solutions   November 13, 2023

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