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
Difficulty
and has an acceptance rate of about 61% (50k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
AI Disclaimer
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.
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 inlikesfor later reuse. - For subsequent companies, the code performs an in-place intersection (
&=) betweensameand the set of people who like the current company. This progressively narrowssameto 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
favoriteCompaniesis 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
favsis skipped, leavingsameas an empty set andfirstunchanged. Consequentlylen(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
likesis a singleton set. During intersection, this singleton quickly reducessameto 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
yieldmeans 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 1436: Destination City
- problem 1446: Consecutive Characters
- problem 1450: Number of Students Doing Homework at a Given Time
- problem 1423: Maximum Points You Can Obtain from Cards
- problem 1432: Max Difference You Can Get From Changing an Integer
- problem 1433: Check If a String Can Break Another String
- problem 1447: Simplified Fractions
- problem 1451: Rearrange Words in a Sentence
- problem 1483: Kth Ancestor of a Tree Node
Extra
- 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