Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e1f74e7

Browse files
author
Khanh Do
committed
Reduce i,j loops
1 parent 73a1bfe commit e1f74e7

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

1452-people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,25 @@ def people_indexes(favorite_companies):
77
Time: O(n^2) -- nested loops to compare current list with all other lists
88
Space: O(n) -- all lists may be disjoint with one another
99
"""
10+
n = len(favorite_companies)
1011
elim_indexes = set()
1112

12-
for i, u in enumerate(favorite_companies):
13-
for j, v in enumerate(favorite_companies):
14-
if j != i: # Exclude self-comparison
15-
if set(u).issubset(set(v)):
16-
elim_indexes.add(i)
13+
for i in range(n):
14+
for j in range(i+1, n):
15+
u = set(favorite_companies[i])
16+
v = set(favorite_companies[j])
17+
if u.issubset(v):
18+
elim_indexes.add(i)
19+
if v.issubset(u):
20+
elim_indexes.add(j)
1721

18-
all_indexes = set(range(len(favorite_companies)))
22+
all_indexes = set(range(n))
1923
return list(all_indexes - elim_indexes)
2024

2125

2226
def main():
2327
example_cases = [
28+
# Example 1
2429
(
2530
[
2631
['leetcode', 'google', 'facebook'],
@@ -29,7 +34,9 @@ def main():
2934
['google'],
3035
['amazon'],
3136
],
32-
[0, 1, 4]),
37+
[0, 1, 4]
38+
),
39+
# Example 2
3340
(
3441
[
3542
['leetcode', 'google', 'facebook'],
@@ -38,6 +45,7 @@ def main():
3845
],
3946
[0, 1]
4047
),
48+
# Example 3
4149
(
4250
[
4351
['leetcode'],

0 commit comments

Comments
 (0)