Naming a Company
Count the company names you can make by swapping the first letters of two ideas.
You are given an array ideasideas
Example 1
Output: 6
Explanation: the valid names are "coffee donuts", "donuts coffee", "donuts time", "donuts toffee", "time donuts" and "toffee donuts". "coffee time" is not valid, because the swap gives "toffee", which is already an idea.
Example 2
Output: 0
The Idea
Picture a list of ideas for a company name: coffee, donuts, time and toffee. To make a name, you take two ideas and swap their first letters. Coffee and donuts become doffee and conuts. Neither of those is on the list, so "coffee donuts" is a valid name. "donuts coffee" is a different name, and it is valid too.
Now try coffee and time. The swap gives toffee and cime, and toffee is already on the list, so this name fails. With four ideas you can check all 12 ordered choices one by one. With 50,000 ideas there are about 2.5 billion. So what really decides whether a swap lands on an idea that already exists?
Split each idea into its first letter and the rest, which we will call its suffix. Coffee is c + offee, and toffee is t + offee. Swapping coffee with any idea that starts with t puts offee behind t, and toffee comes out. So the failure has nothing to do with time itself. Whether a swap works depends only on the two first letters and the two suffixes.
That suggests sorting the suffixes into groups, one group per first letter. Look at the picture below.
The top row shows the four ideas, each split into its letter and its suffix. Below them, group c holds offee, group d holds onuts, and group t holds ime and offee. The suffix offee, in orange, sits in both group c and group t.
Now count one pair of letters at a time. Groups d and t share nothing, so onuts can go with ime or with offee: 1 × 2 = 2 choices, donuts with time and donuts with toffee. Each choice gives two names, one in each order, so that is 4 names. Groups c and t share offee, which can never move between them, so group c has nothing left to offer: 0 names. Groups c and d share nothing either: 1 × 1 choice, so 2 names. The total is 4 + 0 + 2 = 6, the answer of Example 1.
So the count comes from pairs of letters, not pairs of ideas. There are only 26 letters, so at most 325 pairs of different letters, however many ideas there are.
Solution Approach
Turning that idea into code means settling four things: how to store the groups, how to count the names for one pair of letters, how to go through the pairs of letters, and how big the count can get.
Storing the suffixes by first letter
Why not simply try every pair of ideas? For each ordered pair, build the two swapped words and look them up in a set of all ideas. That is correct, but 50,000 ideas give about 2.5 billion pairs to check.
Instead, keep an array of 26 sets, one per letter: the set at position 0 holds the suffixes of ideas that start with a, position 1 those that start with b, and so on. A HashSet
Counting the names for one pair of letters
Take two letters, a and b. Which suffixes can be used? A suffix that is in both groups never can: moving it to the other letter rebuilds an idea that already exists. Every other suffix of group a works with every other suffix of group b.
To see why, take a suffix x found only under a and a suffix y found only under b. The swap gives b + x and a + y. The word b + x would exist only if x were in group b, and a + y only if y were in group a, and neither is. So with sharedsharedshared
Example 2 shows the other side. Lack and back both have the suffix ack, so it is shared by groups l and b. Each group has nothing left, 0 × 0, and the answer is 0.
Going through the pairs of letters
What about two ideas with the same first letter? Swapping equal letters changes nothing, so both words are the ideas themselves, which already exist. Only pairs of different letters can give names.
Each pair of letters is visited once, with the second letter after the first in the alphabet: 26 × 25 / 2 = 325 pairs. Every usable choice then gives two names, "A B" and "B A", so the count for a pair of letters is doubled.
How big the count can get
Can the total be too big for an intintintlonglong
Java Solution
The method distinctNames
- First, build the groups:
is an array of 26suffixes s, one per letter. For each idea,HashSet turns its first letter into a position from 0 to 25, andidea.charAt(0) - 'a' , the suffix, goes into the set at that position.idea.substring(1) - Go through the pairs of letters with two loops, one inside the other. The outer loop moves
over the 26 positions, and the inner loop movesa over the positions afterb , so each pair comes once and the two letters always differ.a - For each pair, count
: go through the suffixes in groupshared and check whether groupa contains each one.b - Work out
andonlyA , the sizes of the two groups minusonlyB , asshared values, and addlong to the count2 * onlyA * onlyB .names - When both loops are done, return
.names
The main
import java.util.HashSet;
import java.util.Set;
public class NamingACompany {
public static long distinctNames(String[] ideas) {
// suffixes[c]: the rest of every idea that starts with letter c
@SuppressWarnings("unchecked")
Set<String>[] suffixes = new HashSet[26];
for (int c = 0; c < 26; c++) {
suffixes[c] = new HashSet<>();
}
for (String idea : ideas) {
suffixes[idea.charAt(0) - 'a'].add(idea.substring(1));
}
long names = 0;
for (int a = 0; a < 26; a++) {
for (int b = a + 1; b < 26; b++) { // b > a: each letter pair once
int shared = 0;
for (String s : suffixes[a]) {
if (suffixes[b].contains(s)) {
shared++; // this suffix is under both letters
}
}
long onlyA = suffixes[a].size() - shared;
long onlyB = suffixes[b].size() - shared;
names += 2 * onlyA * onlyB; // "A B" and "B A" are different names
}
}
return names;
}
public static void main(String[] args) {
System.out.println(distinctNames(new String[] {"coffee", "donuts", "time", "toffee"}));
System.out.println(distinctNames(new String[] {"lack", "back"}));
System.out.println(distinctNames(new String[] {"apple", "angle", "axe"}));
String[] many = new String[26 * 2000]; // 2,000 ideas for every letter
int k = 0;
for (char c = 'a'; c <= 'z'; c++) {
for (int i = 0; i < 2000; i++) {
many[k++] = "" + c + c + i; // "aa0", "aa1", ..., "zz1999"
}
}
System.out.println(distinctNames(many));
}
}
Running it prints:
6
0
0
2600000000
The first two lines, 60
Look at the last line: 2,600,000,000, the total worked out above. Each idea like "aa0" has the suffix "a0", which starts with the idea's own letter, so no two groups share a suffix. The same method with intlong
The original implementation,
Complexity
The work is putting each idea into its group, plus one pass over a group for every pair of letters.
- Time: O(n × L), where n is the number of ideas and L the length of the longest one. Building the groups reads each idea once. Then each suffix of group
is looked up in at most 25 other groups, a fixed number. Each lookup computes the suffix's hash code, which reads every character, so it costs O(L).a - Space: O(n × L). The 26 sets together hold one suffix of up to L characters for each idea.
Sorting words into groups by a key is also how