#2306
Hard Algorithms Naming a company
Array Hash Table String Bit Manipulation Enumeration
46.5% acceptance
Feb 25, 2026
1966
74
You are given an array of strings ideas that represents a list of names to be used in naming a company.
The process of naming a company: Choose 2 distinct names, ideaA and ideaB. Swap the first letters.
If both new names are not found in the original ideas, then "ideaA ideaB" is a valid company name.
Return the number of distinct valid names for the company.
Solution
Rust
Time O(n²)
Space O(n)
use std::collections::HashSet;
impl Solution {
pub fn distinct_names(ideas: Vec<String>) -> i64 {
let mut suffix_sets: Vec<HashSet<String>> = vec![HashSet::new(); 26];
for idea in &ideas {
let idx = (idea.as_bytes()[0] - b'a') as usize;
suffix_sets[idx].insert(idea[1..].to_string());
}
let mut ans: i64 = 0;
for a in 0..26usize {
for b in (a + 1)..26usize {
let common = suffix_sets[a].intersection(&suffix_sets[b]).count() as i64;
let a_only = suffix_sets[a].len() as i64 - common;
let b_only = suffix_sets[b].len() as i64 - common;
ans += 2 * a_only * b_only;
}
}
ans
}
}