Skip to content

Commit 30deb93

Browse files
authored
Create find-smallest-common-element-in-all-rows.py
1 parent 9a3d82d commit 30deb93

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Time: O(m * n)
2+
# Space: O(m)
3+
4+
class Solution(object):
5+
def smallestCommonElement(self, mat):
6+
"""
7+
:type mat: List[List[int]]
8+
:rtype: int
9+
"""
10+
# values could be duplicated in each row
11+
intersections = set(mat[0])
12+
for i in xrange(1, len(mat)):
13+
intersections &= set(mat[i])
14+
return min(intersections or [-1])
15+
16+
17+
# Time: O(m * n)
18+
# Space: O(m)
19+
import collections
20+
21+
22+
class Solution2(object):
23+
def smallestCommonElement(self, mat):
24+
"""
25+
:type mat: List[List[int]]
26+
:rtype: int
27+
"""
28+
# assumed value is unique in each row
29+
counter = collections.Counter()
30+
for row in mat:
31+
for c in row:
32+
counter[c] += 1
33+
if counter[c] == len(mat):
34+
return c
35+
return -1

0 commit comments

Comments
 (0)