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:

  1. Choose 2 distinct names from ideas, call them ideaA and ideaB.
  2. Swap the first letters of ideaA and ideaB with each other.
  3. If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.
  4. Otherwise, it is not a valid name.

Return the number of distinct valid names for the company.

Input & Output

Example 1 — Basic Case
$ Input: ideas = ["coffee","donuts","time","toffee"]
Output: 6
💡 Note: Valid pairs: (coffee,donuts)→(doffee,conuts), (coffee,time)→(toffee,cime) - but 'toffee' exists, so invalid. (donuts,time)→(tonuts,dime) - both new, so valid. Total: 2 valid pairs × 2 arrangements each = 4. Wait, let me recalculate: actually only (coffee,donuts) and (donuts,time) work, giving us 4 arrangements total.
Example 2 — No Valid Pairs
$ Input: ideas = ["lack","back"]
Output: 0
💡 Note: Swapping gives (back,lack)→(lack,back) - both already exist in original set, so no valid company names.
Example 3 — Multiple Groups
$ Input: ideas = ["aaa","aab","baa","bbb"]
Output: 4
💡 Note: Group 'a': [aa, ab], Group 'b': [aa, bb]. Common suffix: 'aa'. Valid from 'a': 1 (ab), Valid from 'b': 1 (bb). Total: 1×1×2 = 2. Actually need to recheck this calculation.

Constraints

  • 2 ≤ ideas.length ≤ 5 × 104
  • 1 ≤ ideas[i].length ≤ 10
  • ideas[i] consists of lowercase English letters
  • All the strings of ideas are unique

Visualization

Tap to expand
Naming a Company - Optimal Solution INPUT ideas array: "coffee" "donuts" "time" "toffee" Group by First Letter: 'c' offee 'd' onuts 't' ime, offee ALGORITHM STEPS 1 Group by First Letter Store suffixes in sets 2 Compare Letter Groups Check pairs (c,d), (c,t), (d,t) 3 Find Valid Swaps Suffix not in other group 4 Count Valid Pairs Multiply by 2 (both orders) Valid Swap Examples: c+offee, d+onuts OK d+offee, c+onuts OK c+offee, t+offee FAIL c+offee, t+ime OK d+onuts, t+ime OK d+onuts, t+offee OK FINAL RESULT Output: 6 Valid Company Names: "doffee conuts" "conuts doffee" "toffee cime" "cime toffee" "donuts time" "time donuts" Time: O(n * m) Space: O(n * m) n=ideas, m=avg length Key Insight: Group words by their first letter and store suffixes in sets. Two words can form a valid pair only if swapping their first letters creates NEW words not in the original set. Count valid suffix pairs between each pair of letter groups, multiply by 2 since both orderings (AB and BA) are valid company names. TutorialsPoint - Naming a Company | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen