People Whose List of Favorite Companies Is Not a Subset of Another List — LeetCode 1452 Python Solution
- Problem
- #1452
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0). Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies.
Example
- Input
- favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
- Output
- [0,1,4]
- Explanation
- Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0.
Python solution
class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
idx = 0
d = {}
n = len(favoriteCompanies)
nums = [set() for _ in range(n)]
for i, ss in enumerate(favoriteCompanies):
for s in ss:
if s not in d:
d[s] = idx
idx += 1
nums[i].add(d[s])
ans = []
for i in range(n):
if not any(i != j and (nums[i] & nums[j]) == nums[i] for j in range(n)):
ans.append(i)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | (n \times m \times k + n^2 \times m) |
| Space | O(n \times m) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1452. People Whose List of Favorite Companies Is Not a Subset of Another List is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1452. People Whose List of Favorite Companies Is Not a Subset of Another List?
- LeetCode 1452. People Whose List of Favorite Companies Is Not a Subset of Another List is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1452. People Whose List of Favorite Companies Is Not a Subset of Another List?
- The Python solution on this page runs in (n \times m \times k + n^2 \times m).
- What is the space complexity of LeetCode 1452. People Whose List of Favorite Companies Is Not a Subset of Another List?
- The Python solution on this page uses O(n \times m) auxiliary space.
- What topics does LeetCode 1452. People Whose List of Favorite Companies Is Not a Subset of Another List cover?
- LeetCode 1452. People Whose List of Favorite Companies Is Not a Subset of Another List is tagged Array, Hash Table and String on LeetCode.