Extra Characters in a String — LeetCode 2707 Python Solution

MediumTrieArrayHash TableStringDynamic Programming
Problem
#2707
Pattern
Trie
Reading time
2 min

The problem

You are given a 0-indexed string s and a dictionary of words dictionary. You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary.

Example

Input
s = "leetscode", dictionary = ["leet","code","leetcode"]
Output
1
Explanation
We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1.

Python solution

Python
class Solution:
    def minExtraChar(self, s: str, dictionary: List[str]) -> int:
        ss = set(dictionary)
        n = len(s)
        f = [0] * (n + 1)
        for i in range(1, n + 1):
            f[i] = f[i - 1] + 1
            for j in range(i):
                if s[j:i] in ss and f[j] < f[i]:
                    f[i] = f[j]
        return f[n]

Complexity

MeasureComplexity
TimeO(n^3 + L)
SpaceO(n + L) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 2707. Extra Characters in a String is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2707. Extra Characters in a String?
LeetCode 2707. Extra Characters in a String is rated Medium on LeetCode.
What is the time complexity of LeetCode 2707. Extra Characters in a String?
The Python solution on this page runs in O(n^3 + L).
What is the space complexity of LeetCode 2707. Extra Characters in a String?
The Python solution on this page uses O(n + L) auxiliary space.
What topics does LeetCode 2707. Extra Characters in a String cover?
LeetCode 2707. Extra Characters in a String is tagged Trie, Array, Hash Table, String and Dynamic Programming 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