Naming a Company

Count the company names you can make by swapping the first letters of two ideas.

You are given an array ideas of different words in lowercase letters. A company name is made from two different ideas, A and B: swap their first letters to get two new words. If neither new word is in ideas, then "A B", the two original ideas with a space between them, is a valid company name. Return how many different valid company names there are.

Example 1
Input: ideas = ["coffee", "donuts", "time", "toffee"]
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
Input: ideas = ["lack", "back"]
Output: 0
Solution

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 ideas coffee, donuts, time and toffee split into first letter and suffix, then grouped by letter: c holds offee, d holds onuts, t holds ime and offee. The suffix offee is in group c and in group t.

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 answers "is this suffix in the group?" in one step on average, however big the group is.

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 shared suffixes in both groups, the number of usable choices is (size of group a - shared) × (size of group b - shared).

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 int? A Java int holds values up to 2,147,483,647. Take 2,000 ideas for each of the 26 letters, with no suffix shared between letters. Each of the 325 pairs of letters gives 2,000 × 2,000 × 2 = 8,000,000 names, 2,600,000,000 in total. An int that goes past its largest value continues from the most negative values, which is called overflow. A long holds far bigger values, so the count is kept in a long.

Java Solution

The method distinctNames works in these steps:

  1. First, build the groups: suffixes is an array of 26 HashSets, one per letter. For each idea, idea.charAt(0) - 'a' turns its first letter into a position from 0 to 25, and idea.substring(1), the suffix, goes into the set at that position.
  2. Go through the pairs of letters with two loops, one inside the other. The outer loop moves a over the 26 positions, and the inner loop moves b over the positions after a, so each pair comes once and the two letters always differ.
  3. For each pair, count shared: go through the suffixes in group a and check whether group b contains each one.
  4. Work out onlyA and onlyB, the sizes of the two groups minus shared, as long values, and add 2 * onlyA * onlyB to the count names.
  5. When both loops are done, return names.

The main method runs both examples, three ideas that all start with a, and 52,000 ideas, 2,000 for each letter, with no suffix shared between letters.

Java
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:

Output
6
0
0
2600000000

The first two lines, 6 and 0, answer the two examples. The third line is 0 because apple, angle and axe all sit in group a, and every other group is empty, so no pair of letters has anything to offer.

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 int in place of long prints -1,694,967,296 for this input, which is the overflow at work.

The original implementation, NamingACompany.java, is on GitHub.

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 a 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).
  • 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 Group Anagrams works.