#2306

Naming a Company

Hard
ArrayHash TableStringBit ManipulationEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach groups ideas by their suffixes (everything except the first letter) and counts how many ideas share the same suffix. This allows us to quickly determine valid pairs without checking every combination.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a map to count the number of ideas for each suffix.
  2. 2Step 2: Loop through each idea and populate the suffix count map.
  3. 3Step 3: For each unique first letter, calculate valid pairs using the counts from the suffix map.
  4. 4Step 4: For each pair of different first letters, multiply the counts of their suffixes to get valid combinations.
  5. 5Step 5: Return the total valid combinations.
solution.py12 lines
1def distinctNames(ideas):
2    from collections import defaultdict
3    suffix_count = defaultdict(int)
4    for idea in ideas:
5        suffix_count[idea[1:]] += 1
6    valid_names_count = 0
7    first_letters = set(idea[0] for idea in ideas)
8    for letter_a in first_letters:
9        for letter_b in first_letters:
10            if letter_a != letter_b:
11                valid_names_count += (len(ideas) - suffix_count[letter_a]) * (len(ideas) - suffix_count[letter_b])
12    return valid_names_count

Complexity note: The time complexity is O(n) because we only loop through the list a couple of times. The space complexity is O(n) due to the suffix count map storing counts for each unique suffix.

  • 1Grouping ideas by suffixes allows for efficient counting of valid pairs.
  • 2Swapping first letters only matters if the resulting names are not in the original list.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.