Letter Tile Possibilities — LeetCode 1079 Python Solution

MediumHash TableStringBacktrackingCounting
Problem
#1079
Reading time
3 min

The 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.

Example

Input
tiles = "AAB"
Output
8
Explanation
The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

Python solution

Python
class Solution:
    def numTilePossibilities(self, tiles: str) -> int:
        def dfs(cnt: Counter) -> int:
            ans = 0
            for i, x in cnt.items():
                if x > 0:
                    ans += 1
                    cnt[i] -= 1
                    ans += dfs(cnt)
                    cnt[i] += 1
            return ans

        cnt = Counter(tiles)
        return dfs(cnt)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1079. Letter Tile Possibilities is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1079. Letter Tile Possibilities?
LeetCode 1079. Letter Tile Possibilities is rated Medium on LeetCode.
What is the time complexity of LeetCode 1079. Letter Tile Possibilities?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1079. Letter Tile Possibilities?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1079. Letter Tile Possibilities cover?
LeetCode 1079. Letter Tile Possibilities is tagged Hash Table, String, Backtracking and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview