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: Swap First LettersInput Ideas:coffeedonutstimeSwap Process:c|offeed|onutsResult:doffeeconutsValid! ✓Company Names: "doffee conuts" + "conuts doffee"Count all valid letter-swap combinations
Understanding the Visualization
1
Input
Array of idea words
2
Process
Swap first letters between pairs
3
Output
Count of valid company names
Key Takeaway
🎯 Key Insight: Group words by first letter - only different groups can create valid pairs
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