Question on Leetcode - Easy
My approach to this question was use a set to break down each string into a set and store their occurence to a hashmap. Then, I compare the values of each character to the length of the array.
For example, if a
appears three times in the array and the length of the array is four, a
is not going to be included in the result
printed.
Any edge cases thought of? Nope. Not yet.
Algoexpert
def commonCharacters(strings):
char = {}
for i in strings:
unique = set(i)
for chars in unique:
if chars not in char:
char[chars] = 0
char[chars] += 1
finalchar = []
for k, v in char.items():
if v == len(strings):
finalchar.append(k)
return finalchar
from collections import defaultdict
class Solution:
def commonChars(self, words: List[str]) -> List[str]:
res = []
d = defaultdict(lambda: 0)
for x in words[0]:
d[x] += 1
for key in d:
for word in words[1:]:
if not key in word:
d[key] = 0
else:
if d[key] > 1:
d[key] = min(d[key], word.count(key))
for key, value in d.items():
if value > 0:
for i in range(value):
res.append(key)
return res
- Time complexity: O(n x m)
- Space complexity: O(c) - Total number of unique characters