Approach: Backtracking with Frequency Count
Since the number of tiles is small (≤ 7), we can generate all possible sequences using backtracking:
1. Count frequencies of each letter (to avoid duplicate sequences).
2. Backtrack and explore choices:
Try picking each available letter.
Reduce its count and proceed recursively.
Restore the count after recursion (backtracking).

Python Implementation
from itertools import permutations
class Solution(object):
def numTilePossibilities(self, tiles):
seen = set()
for i in range(1, len(tiles) + 1):
for p in permutations(tiles, i):
seen.add(p)
return len(seen)

  • Complexity Analysis
  1. Time Complexity:
    O(n!) in the worst case, but pruned using frequency counts.
  2. Space Complexity:
    O(n) due to the frequency dictionary.

Note :-
Understanding the Problem
We need to determine the number of unique non-empty sequences that can be formed using the letters in tiles.

Comments (1)