The Find Beautiful Indices in the Given Array II coding problem is the optimized version of the previous challenge. The constraints are much larger, making naive string matching (indexOf) or repeated searching too slow. You still need to find indices of pattern a that are within distance k of pattern b, but the string length can be up to .
This "Hard" problem is used by Google and Palantir to evaluate a candidate's mastery of high-performance string algorithms. It evaluation your knowledge of the KMP (Knuth-Morris-Pratt) algorithm or Rolling Hash interview pattern. It tests whether you can implement a linear-time string matcher and then efficiently merge the resulting index lists.
The solution combines KMP Algorithm and Two Pointers.
a and b in time.pos_a and pos_b are already sorted:
pos_a and find if any j in pos_b satisfies the distance constraint.i in pos_a, move the pos_b pointer to the first element . If that element is also , then i is beautiful.String: "...a...b...a...b...", .
pos_a = [10, 100, 500] and pos_b = [12, 400].string.substr() or indexOf in a loop, which is .KMP is a "must-know" for Hard string problems. Practice writing the getLPS function until it becomes second nature. It's the most common way to achieve linear time in pattern matching.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Beautiful Indices in the Given Array I | Medium | Solve | |
| Sum of Scores of Built Strings | Hard | Solve | |
| Longest Happy Prefix | Hard | Solve | |
| Shortest Palindrome | Hard | Solve | |
| Minimum Time to Revert Word to Initial State II | Hard | Solve |