Leetcode Problem 2306. Naming a Company

2306. Naming a Company

Leetcode Solutions

Group words by their initials

  1. Initialize an array of sets, initial_group, with a length of 26 to group words by their first letter.
  2. Iterate over the ideas array and add the suffix of each word (excluding the first letter) to the corresponding set in initial_group.
  3. Initialize answer as 0 to store the count of valid names.
  4. Iterate over every pair of distinct initial letters i and j.
  5. For each pair, calculate the number of mutual suffixes num_of_mutual that appear in both groups i and j.
  6. Increment answer by 2 * (len(group[i]) - num_of_mutual) * (len(group[j]) - num_of_mutual) to account for all valid swaps between the two groups.
  7. Return answer as the total count of distinct valid company names.
UML Thumbnail

Brute Force with Optimization

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...