Letter Case Permutation

Return every string you can make by switching each letter of a string between lowercase and uppercase.

Given a string s of letters and digits, you may switch each letter to lowercase or uppercase, every letter on its own. Return every string you can create this way, in any order.

Example 1
Input: s = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Example 2
Input: s = "3z4"
Output: ["3z4", "3Z4"]
Solution

The Idea

Picture typing a1b2 on a keyboard. For each letter you may hold Shift or not, and the digits come out the same either way. That gives two Shift decisions, each with two outcomes, so there are 2 ร— 2 = 4 strings, the four in Example 1. In Example 2, 3z4 has one letter and two results.

With two letters the four strings are easy to list by hand. With five letters there are 32, and with ten there are 1,024. How do we produce all of them, for any string, without missing one or listing one twice?

Decide one character at a time, from left to right, and write the decisions down as a tree. Look at the picture below.

The choice tree for a1b2. At position 0 the letter a splits into lowercase a and uppercase A. Position 1 keeps the digit 1. At position 2 the letter b splits into lowercase b and uppercase B. Position 3 keeps the digit 2. The four paths end at a1b2, a1B2, A1b2 and A1B2.

The top box, in the row labelled start, holds the string before any decision. In the row labelled "position 0: a", the tree splits in two: one branch keeps lowercase a, the other makes it uppercase A. The orange character in each box is the one just decided.

The rows labelled "position 1: 1" and "position 3: 2" have one arrow per box, marked "keep 1" and "keep 2", because a digit has no other case. The row labelled "position 2: b" splits every box in two again. Each path from the top to a teal box at the bottom is one finished string, and the four paths give exactly the four strings of Example 1.

So every letter doubles the number of paths and every digit leaves it unchanged. A string with L letters has 2L results, one per path through its tree.

How do we visit every path? Go down the left-most path to a1b2 and record it. Then step back up to the last split, at position 2, take the other branch, and record a1B2. Both branches there are used now, so step back further, to position 0, and switch a to A for the right half of the tree. Following one path to its end, then stepping back to the most recent split with an untried branch, is called backtracking.

Solution Approach

Turning the tree into code means settling four things: how to walk the tree, where to keep the string being built, what to do at the end of a path, and how to change a letter's case.

Walking the tree with a method that calls itself

How does the code go down a path and come back? A method build handles one position, given by index, and then calls itself for index + 1 to handle the next one. For a letter it calls itself twice, once per branch. For a digit it calls itself once.

When one of these calls returns, the code is back at the split it came from, ready to try the other branch. So stepping back up the tree needs no extra work: it is simply a call returning. A method like build, where the work for position 0 is done by asking the same method about position 1, is called recursive.

One char array, changed and put back

Where does the string being built live? A simple way is to pass a new String down each branch, but that makes a fresh copy at every box of the tree. Instead, build works on one char[] array, made once from s, and changes it in place.

At a letter, build writes the lowercase form at index and goes down that branch. Then it writes the uppercase form and goes down the second branch. Last, it writes the original character back, so the array is the same as before the call. Each call cleans up after itself, and its caller can trust the array it gets back.

The end of a path

How does build know a string is finished? When index equals the length of the array, every position has been decided, which is a teal box in the picture. The array will keep changing as other paths are tried, so new String(chars) takes a copy of it, and that copy goes into the result list.

Changing a letter's case

How do we tell a letter from a digit and switch its case? Character.isLetter(c) answers the first question. Character.toLowerCase(c) and Character.toUpperCase(c) give the two forms, whatever case the letter had in the input, so an input such as "Ab" works the same as "ab".

As an option, a bit trick does the switch for the English letters a to z. Their codes differ from the uppercase ones by exactly 32: 'a' is 97 and 'A' is 65. So (char) (c ^ 32) turns 'b' into 'B' and 'B' into 'b'. The library calls are easier to read and also handle letters outside a to z.

Java Solution

The method letterCasePermutation and its helper build work in these steps:

  1. First, letterCasePermutation creates an empty list result, turns s into a char[] array with s.toCharArray(), and calls build with that array and index 0.
  2. In build, if index equals chars.length, every position has been decided: add new String(chars) to result and return.
  3. Otherwise, read the character at index into c. If it is a letter, write its lowercase form and call build for index + 1. Then write its uppercase form and call build for index + 1 again. Finally, put c back.
  4. If c is a digit, leave it as it is and call build for index + 1 once.
  5. When the first call to build returns, every path has been walked, and letterCasePermutation returns result.

The main method runs both examples, "Ab" with an uppercase letter in the input, "2024" with no letters at all, and prints only the number of results for "abc".

Java
import java.util.ArrayList;
import java.util.List;

public class LetterCasePermutation {

    public static List<String> letterCasePermutation(String s) {
        List<String> result = new ArrayList<>();
        build(s.toCharArray(), 0, result);
        return result;
    }

    private static void build(char[] chars, int index, List<String> result) {
        if (index == chars.length) {
            result.add(new String(chars));        // every position decided: one answer
            return;
        }
        char c = chars[index];
        if (Character.isLetter(c)) {
            chars[index] = Character.toLowerCase(c);   // first choice: lowercase
            build(chars, index + 1, result);
            chars[index] = Character.toUpperCase(c);   // second choice: uppercase
            build(chars, index + 1, result);
            chars[index] = c;                          // put the original back
        } else {
            build(chars, index + 1, result);           // a digit stays as it is
        }
    }

    public static void main(String[] args) {
        System.out.println(letterCasePermutation("a1b2"));
        System.out.println(letterCasePermutation("3z4"));
        System.out.println(letterCasePermutation("Ab"));
        System.out.println(letterCasePermutation("2024"));
        System.out.println(letterCasePermutation("abc").size());
    }
}

Running it prints:

Output
[a1b2, a1B2, A1b2, A1B2]
[3z4, 3Z4]
[ab, aB, Ab, AB]
[2024]
8

Look at the first line: a1b2, a1B2, A1b2, A1B2 is the order of the four teal boxes in the picture, from left to right. build always tries lowercase first, so the left branch of every split is walked before the right one.

The third line starts with ab, although the input was "Ab": the first branch turned the A into a. The case a letter has in the input does not matter, and Ab itself appears third, like any other path. "2024" has no letters, so its tree is a single path and the list holds just the input. The last line, 8, is 23 for the three letters of "abc".

Complexity

The work is one call of build per box of the choice tree, plus a copy of every finished string.

  • Time: O(2L ยท n) for a string of n characters with L letters, because each of the 2L paths makes at most n + 1 calls and copies n characters into a new String.
  • Space: O(n) besides the output, because the calls go at most n + 1 deep and they all share one char[] array of n characters.