#1079
Letter Tile Possibilities
MediumHash TableStringBacktrackingCountingBacktrackingHash Map
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n!) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n!)Space O(n)
The optimal solution uses backtracking with a frequency count of each character to avoid generating duplicate sequences. This significantly reduces the number of recursive calls and ensures we only consider unique characters.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in the tiles.
- 2Step 2: Use a backtracking function that builds sequences based on the frequency count.
- 3Step 3: For each character, if it can be used (frequency > 0), decrease its frequency, add it to the current sequence, and recurse. Restore the frequency after recursion.
solution.py13 lines
1from collections import Counter
2
3def numTilePossibilities(tiles):
4 def backtrack(counter):
5 total = 0
6 for char in counter:
7 if counter[char] > 0:
8 counter[char] -= 1
9 total += 1 + backtrack(counter)
10 counter[char] += 1
11 return total
12
13 return backtrack(Counter(tiles))ℹ
Complexity note: The time complexity is O(n!) because we explore all permutations of the characters, but we avoid duplicates by using a frequency count.
- 1Using a frequency count helps avoid duplicates.
- 2Backtracking allows us to explore all combinations efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.