In LeetCode 1079: Letter Tile Possibilities, we must count every distinct non-empty sequence of uppercase letters that can be formed from a multiset of up to seven physical tiles. By replacing naive string permutation generation and hash-set deduplication with a stack-allocated 26-bucket character frequency Depth-First Search (DFS), we eliminate heap churn and achieve optimal execution in both C++20 and TypeScript.
Problem Statement & Combinatorial Framing
You are given a string tiles of length n, where each character tiles[i] is an uppercase English letter between 'A' and 'Z'. Return the total number of distinct non-empty sequences of lengths 1 through n that can be assembled using the available tiles, where each physical tile index may be used at most once per sequence.
Formal Constraints: 1 ≤ tiles.length ≤ 7, and tiles contains only uppercase ASCII letters (65 ≤ charCode ≤ 90). Unlike fixed-length permutation problems that only score leaves at depth n, every intermediate prefix of length 1 ≤ k ≤ n counts as a valid distinct sequence.
Worked Examples & Subtree Symmetry
- Example 1:
tiles = "AAB"→ Output: 8. The valid non-empty sequences are length-1 ("A","B"), length-2 ("AA","AB","BA"), and length-3 ("AAB","ABA","BAA"). - Example 2:
tiles = "AAABBC"→ Output: 188 across lengths 1 through 6. - Example 3:
tiles = "V"→ Output: 1 (only"V").
Why Frequency-Map Backtracking Beats Hash-Set Permutations
A brute-force implementation tracks a boolean used[n] mask over indices and inserts every constructed prefix into a std::unordered_set<std::string>. When tiles = "AAAAAAA", an index-based recursion explores 7 + 42 + 210 + 840 + 2520 + 5040 + 5040 = 13,699 branches only to collapse them into 7 unique strings. Worse, every node hashes and allocates dynamic string buffers.
Grouping identical letters into a 26-slot frequency table prunes isomorphic branches before they are ever entered. At any recursion depth, picking the first 'A' tile or the second 'A' tile leaves the exact same multiset of remaining characters. Branching once per distinct character with a non-zero remaining count guarantees that every visited node in the recursion tree corresponds one-to-one with a unique output sequence.
Approach 1: Stack-Allocated 26-Element Frequency DFS in C++20
Because the alphabet size is fixed at 26 uppercase ASCII characters, a stack-allocated std::array<int, 26> fits inside a single 128-byte L1 cache linepair with zero dynamic allocations:
#include <array>
#include <string_view>
class Solution {
public:
int numTilePossibilities(std::string_view tiles) const noexcept {
std::array<int, 26> freq{};
for (char c : tiles) {
++freq[static_cast<std::size_t>(c - 'A')];
}
return countSubtreeSequences(freq);
}
private:
int countSubtreeSequences(std::array<int, 26>& freq) const noexcept {
int totalSequences = 0;
for (std::size_t i = 0; i < 26; ++i) {
if (freq[i] == 0) {
continue;
}
// Appending character ('A' + i) forms one new valid non-empty prefix
++totalSequences;
--freq[i];
// Count all longer extensions branching from this prefix
totalSequences += countSubtreeSequences(freq);
// Restore multiset state for sibling letter choices
++freq[i];
}
return totalSequences;
}
};
Approach 2: Zero-Allocation V8 TypedArray Backtracking in TypeScript
In Node.js and browser V8 runtimes, mutating a pre-allocated Int32Array(26) inside a closure avoids creating intermediate strings or boxed array elements during traversal:
export function numTilePossibilities(tiles: string): number {
const freq = new Int32Array(26);
const ASCII_A = 65;
for (let i = 0; i < tiles.length; i++) {
freq[tiles.charCodeAt(i) - ASCII_A]++;
}
// Extract only present character frequencies so inner loop skips unused letters
const activeCounts: number[] = [];
for (let i = 0; i < 26; i++) {
if (freq[i] > 0) {
activeCounts.push(freq[i]);
}
}
const compact = Int32Array.from(activeCounts);
const distinct = compact.length;
function dfs(): number {
let total = 0;
for (let i = 0; i < distinct; i++) {
if (compact[i] === 0) continue;
total++;
compact[i]--;
total += dfs();
compact[i]++;
}
return total;
}
return dfs();
}
Compacting the 26-bucket histogram down to compact (at most 7 non-zero buckets because tiles.length ≤ 7) cuts inner-loop iterations by more than 70% on every recursive frame.
Approach 3: Multinomial Dynamic Programming for Larger Tile Pools
What if production constraints scaled from n = 7 to n = 100 where enumerating every valid sequence would exceed time limits? Let dp[len] denote the number of distinct sequences of exact length len formed using the character types processed so far. When incorporating a character with multiplicity c, we choose k copies (1 ≤ k ≤ c) and interleave them among len existing slots in C(len + k, k) ways. That polynomial DP runs in O(26 · n2) time even when total sequences reach 1050.
Algorithmic Complexity & Memory Comparison
| Strategy | Time Complexity | Auxiliary Space | Runtime & Memory Profile |
|---|---|---|---|
| Index Permutations + Hash Set | O(n · n!) |
O(n · n!) |
Severe heap allocator pressure and redundant string hashing on repeated letters. |
| Compacted Frequency Array DFS | O(UniqueSequences) |
O(n) call stack |
At most 13,699 integer ops for n = 7; zero heap allocations inside recursion. |
| Multinomial Binomial DP | O(|Σ| · n2) |
O(n2) Pascal table |
Scales cleanly when n > 15 and exponential enumeration becomes infeasible. |
Production Systems Applications
- Combinatorial Feature-Flag Test Matrices: Generating unique multi-stage rollout permutations across environment cohorts without repeating indistinguishable state transitions.
- Query Rewrite & Token Expansion Engines: Bounding lexical token reorderings in search autocomplete pipelines when user queries contain repeated stems.
- Cryptographic Keyspace & Entropy Estimators: Evaluating exact effective keyspace cardinality when passphrases draw from constrained character multisets via multinomial combinatorics.
