Find All Good Strings — LeetCode 1397 Python Solution

HardStringDynamic ProgrammingString Matching
Problem
#1397
Reading time
2 min

The problem

Given the strings s1 and s2 of size n and the string evil, return the number of good strings. A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring.

Example

Input
n = 2, s1 = "aa", s2 = "da", evil = "b"
Output
51
Explanation
There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da".

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1397. Find All Good Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1397. Find All Good Strings?
LeetCode 1397. Find All Good Strings is rated Hard on LeetCode.
What topics does LeetCode 1397. Find All Good Strings cover?
LeetCode 1397. Find All Good Strings is tagged String, Dynamic Programming and String Matching 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