Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions javascript/2306-naming-a-company.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* @param {string[]} ideas
* @return {number}
*/

// Time complexity: O(n^2 * m)
// Space complexity: O(n * m)

var distinctNames = function (ideas) {
const wordMap = new Map();
let count = 0;

for (const word of ideas) {
const ch = word.charAt(0);
const substr = word.slice(1);
const set = wordMap.get(ch) ?? new Set();
set.add(substr);
wordMap.set(ch, set);
}

for (const [ch1, set1] of wordMap) {
for (const [ch2, set2] of wordMap) {
if (ch1 === ch2) {
continue;
}

const intersect = getIntersection(set1, set2);
const distinct1 = set1.size - intersect;
const distinct2 = set2.size - intersect;
count += distinct1 * distinct2;
}
}

return count;
};

const getIntersection = (set1, set2) =>
[...set1].filter((word) => set2.has(word)).length;
28 changes: 28 additions & 0 deletions python/2306-naming-a-company.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Time complexity: O(n^2 * m)
# Space complexity: O(n * m)

from typing import List
from collections import defaultdict


class Solution:
def distinctNames(self, ideas: List[str]) -> int:
word_map = defaultdict(set)
count = 0

for word in ideas:
word_map[word[0]].add(word[1:])

for ch1 in word_map:
for ch2 in word_map:
if ch1 == ch2:
continue
intersect = 0
for word in word_map[ch1]:
if word in word_map[ch2]:
intersect += 1
distinct1 = len(word_map[ch1]) - intersect
distinct2 = len(word_map[ch2]) - intersect
count += distinct1 * distinct2

return count
35 changes: 35 additions & 0 deletions typescript/2306-naming-a-company.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Time complexity: O(n^2 * m)
// Space complexity: O(n * m)

function distinctNames(ideas: string[]): number {
const wordMap: Map<string, Set<string>> = new Map();
let count = 0;

for (const word of ideas) {
const ch = word.charAt(0);
const substr = word.slice(1);
const set = wordMap.get(ch) ?? new Set();
set.add(substr);
wordMap.set(ch, set);
}

for (const [ch1, set1] of wordMap.entries()) {
for (const [ch2, set2] of wordMap.entries()) {
if (ch1 === ch2) {
continue;
}

const intersect = getIntersection(set1, set2);

const distinct1 = set1.size - intersect;
const distinct2 = set2.size - intersect;
count += distinct1 * distinct2;
}
}

return count;
}

const getIntersection = <T>(set1: Set<T>, set2: Set<T>): number => {
return [...set1].filter((word) => set2.has(word)).length;
};