Naming a Company Problem
Description
LeetCode Problem 2306.
You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
- Choose 2 distinct names from
ideas, call themidea_Aandidea_B. - Swap the first letters of
idea_Aandidea_Bwith each other. - If both of the new names are not found in the original
ideas, then the nameidea_A idea_B(the concatenation ofidea_Aandidea_B, separated by a space) is a valid company name. - Otherwise, it is not a valid name.
Return the number of distinct valid names for the company.
Example 1:
Input: ideas = ["coffee","donuts","time","toffee"]
Output: 6
Explanation: The following selections are valid:
- ("coffee", "donuts"): The company name created is "doffee conuts".
- ("donuts", "coffee"): The company name created is "conuts doffee".
- ("donuts", "time"): The company name created is "tonuts dime".
- ("donuts", "toffee"): The company name created is "tonuts doffee".
- ("time", "donuts"): The company name created is "dime tonuts".
- ("toffee", "donuts"): The company name created is "doffee tonuts".
Therefore, there are a total of 6 distinct company names.
The following are some examples of invalid selections:
- ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array.
- ("time", "toffee"): Both names are still the same after swapping and exist in the original array.
- ("coffee", "toffee"): Both names formed after swapping already exist in the original array.
Example 2:
Input: ideas = ["lack","back"]
Output: 0
Explanation: There are no valid selections. Therefore, 0 is returned.
Constraints:
2 <= ideas.length <= 5 * 10^41 <= ideas[i].length <= 10ideas[i]consists of lowercase English letters.- All the strings in
ideasare unique.
Solution
Approach: Counting by First Letter
Two ideas can be swapped into a valid name only if each new word is not in ideas. Let f[i][j] count the ideas starting with letter i whose version with first letter j is not in ideas. Then for each idea starting with i and each letter j where its swapped version is absent, add f[j][i]: the ideas of the other letter that can swap back. Summing gives the number of ordered valid pairs, which is the answer.
Complexity: O(n * m * 26) time and O(26^2) extra space, where n is the number of ideas and m the maximum word length.
class Solution:
def distinctNames(self, ideas: List[str]) -> int:
s = set(ideas)
f = [[0] * 26 for _ in range(26)]
for v in ideas:
i = ord(v[0]) - ord('a')
t = list(v)
for j in range(26):
t[0] = chr(ord('a') + j)
if ''.join(t) not in s:
f[i][j] += 1
ans = 0
for v in ideas:
i = ord(v[0]) - ord('a')
t = list(v)
for j in range(26):
t[0] = chr(ord('a') + j)
if ''.join(t) not in s:
ans += f[j][i]
return ans