class Solution:
def distinctNames(self, ideas: List[str]) -> int:
n = len(ideas)
res = set()
ideasSet = set(ideas)
for i in range(n):
for j in range(i + 1, n):
A, B = ideas[j][0] + ideas[i][1:], ideas[i][0] + ideas[j][1:]
if A not in ideasSet and B not in ideasSet:
res.add(A + ' ' + B)
res.add(B + ' ' + A)
return len(res)Where is the size of the array and is the average length of the strings.
class Solution:
def distinctNames(self, ideas: List[str]) -> int:
wordMap = collections.defaultdict(set)
for w in ideas:
wordMap[w[0]].add(w[1:])
res = 0
for char1 in wordMap:
for char2 in wordMap:
if char1 == char2:
continue
intersect = sum(1 for w in wordMap[char1] if w in wordMap[char2])
distinct1 = len(wordMap[char1]) - intersect
distinct2 = len(wordMap[char2]) - intersect
res += distinct1 * distinct2
return resWhere is the size of the array and is the average length of the strings.
class Solution:
def distinctNames(self, ideas: List[str]) -> int:
suffixes = [set() for _ in range(26)]
for w in ideas:
suffixes[ord(w[0]) - ord('a')].add(w[1:])
res = 0
for i in range(26):
for j in range(i + 1, 26):
intersect = len(suffixes[i] & suffixes[j])
res += 2 * (len(suffixes[i]) - intersect) * (len(suffixes[j]) - intersect)
return resWhere is the size of the array and is the average length of the strings.
class Solution:
def distinctNames(self, ideas: List[str]) -> int:
mp = defaultdict(lambda: [False] * 26)
count = [[0] * 26 for _ in range(26)]
res = 0
for s in ideas:
first_char = ord(s[0]) - ord('a')
suffix = s[1:]
mp[suffix][first_char] = True
for suffix, arr in mp.items():
for i in range(26):
if arr[i]:
for j in range(26):
if not arr[j]:
count[i][j] += 1
res += count[j][i]
return 2 * resWhere is the size of the array and is the average length of the strings.