Letter Tile Possibilities - Problem

You have n tiles, where each tile has one letter tiles[i] printed on it.

Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.

Note: You may use each tile at most once per sequence.

Input & Output

Example 1 — Basic Case
$ Input: tiles = "AAB"
Output: 8
💡 Note: Possible sequences: "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Total of 8 sequences.
Example 2 — All Same Characters
$ Input: tiles = "AAABBC"
Output: 188
💡 Note: With frequencies A:3, B:2, C:1, we can form many sequences of lengths 1-6. Each length has unique permutations based on character frequencies.
Example 3 — Single Character
$ Input: tiles = "V"
Output: 1
💡 Note: Only one sequence possible: "V"

Constraints

  • 1 ≤ tiles.length ≤ 7
  • tiles consists of uppercase English letters

Visualization

Tap to expand
Letter Tile Possibilities INPUT tiles = "AAB" A A B Character Counts: A: 2 B: 1 Find all non-empty sequences possible using tiles at most once n = 3 tiles ALGORITHM STEPS 1 Count Characters Build frequency map 2 Backtrack DFS Try each available char 3 Decrement & Recurse Use tile, explore deeper 4 Restore & Count Backtrack, sum results Recursion Tree: "" A A B AA AB ... Each node = valid sequence FINAL RESULT All Valid Sequences: A B AA AB BA AAB ABA BAA Count by Length: Length 1: 2 (A, B) Length 2: 3 (AA, AB, BA) Length 3: 3 (AAB, ABA, BAA) Output: 8 Total = 2 + 3 + 3 = 8 Key Insight: Use backtracking with a frequency count array. For each position, try adding any character with remaining count > 0. Each recursive call represents a valid sequence, so count every call (not just leaf nodes). Time: O(n! * n) where n = tiles length. The frequency map naturally handles duplicate characters. TutorialsPoint - Letter Tile Possibilities | Optimal Backtracking Solution
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
32.0K Views
Medium Frequency
~15 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen