Letter Tile Possibilities (LeetCode 1079): Solution and Explanation

Medium
Hash table
String
Backtracking
Counting

You hold a set of lettered tiles, possibly with repeated letters. Count how many different non-empty strings you can spell by laying some or all of the tiles in a row.

Intuition

If every tile had a different letter, the answer would be the number of ordered selections of 1 to n tiles. The difficulty is repeated letters: with tiles "AAB", taking the first A then B spells the same word as taking the second A then B, and it must only be counted once.

The fix is to stop thinking about tiles and think about letters. Keep a count of how many tiles of each letter remain. At each position choose a letter, not a tile. Since the two A tiles are now one choice with a count of 2, the same word can never be built along two different paths.

Every time a letter is placed, the row spells a new distinct sequence, so the count goes up by one right there. Then the recursion tries to extend that sequence with any letter still on the rack, and afterwards the tile goes back so the next choice starts from the same rack.

Approach: Backtracking on a letter count

  1. Count the tiles of each letter.
  2. Define dfs() returning how many non-empty sequences can be appended to the current prefix.
  3. In dfs, loop over the letters. Skip a letter whose count is 0.
  4. Otherwise take one tile of that letter (count - 1). That placement forms one new sequence, so add 1 + dfs() to the total.
  5. Put the tile back (count + 1) and continue with the next letter. Return the total; the answer is dfs() from the empty prefix.

Step-by-step example

tiles = "AAB"
  1. Counts: A = 2, B = 1.
  2. Take A: "A" (1). Extend: take A again, "AA" (2), then B, "AAB" (3). Back up to "A" and take B: "AB" (4), then A, "ABA" (5).
  3. Back to the empty prefix. Take B: "B" (6). Extend with A: "BA" (7), then A again: "BAA" (8).
  4. Every branch is exhausted, so the answer is 8.

Code: Python, Java, C++

1class Solution:
2    def numTilePossibilities(self, tiles: str) -> int:
3        count = Counter(tiles)
4
5        def dfs():
6            total = 0
7            for ch in count:
8                if count[ch] == 0:
9                    continue
10                count[ch] -= 1
11                total += 1 + dfs()
12                count[ch] += 1
13            return total
14
15        return dfs()
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * n!)

In the worst case all letters are distinct and the search visits every ordered selection, which is on the order of n!, with an O(n) letter loop at each node. With n at most 7 this is only a few thousand nodes.

Space

O(n)

The recursion is at most n deep, plus the count table, which has at most 26 entries.

Other approaches

Generate and deduplicate (time O(n * n!), space O(n * n!))

Generate every ordered selection of tiles and put the resulting strings into a set. It is easy to get right but does all the duplicate work and stores every string.

Combinatorics per multiset (time O(product of (count + 1) * n), space O(n))

For each choice of how many tiles of each letter to use, the number of distinct arrangements is the multinomial (total)! / (c1! c2! ...). Sum this over all non-empty choices. It is faster for large inputs but harder to write without mistakes.

Common mistakes

  • Branching on tile positions instead of letters, which counts "AB" twice for tiles "AAB".
  • Forgetting to put the tile back after the recursive call, so later branches see a smaller rack.
  • Counting only full-length sequences. Every prefix you build is a valid answer too, which is why each placement adds 1.
  • Counting the empty sequence. The total starts at 0 and only grows when a tile is placed.

Frequently asked questions

Why does adding 1 at each placement count every sequence exactly once?

Each distinct string corresponds to exactly one path of letter choices in the search, and the +1 happens when that path ends at the string's last letter. Different paths spell different strings because they differ in some letter choice.

Does the order in which letters are tried matter?

No. Any fixed order visits the same set of strings. The order only changes the sequence in which they are discovered.

How is this different from Permutations II?

Permutations II lists only full-length arrangements of a multiset. Here every prefix length from 1 to n counts, and only the number is needed, not the list.