15% off all plans & roadmaps Use code
See plansFind Beautiful Indices in the Given Array II
- LeetCode 3008
- Hard
- String Manipulation Patterns
- Naive / KMP / Rabin-Karp
Updated
TL;DR: Find every start of `a` in `s`, then keep the starts that have a start of `b` within distance `k`. KMP lists all starts in linear time, and prefix counts answer each window check in constant time.
Problem
You are given a 0-indexed string s, two strings a and b, and an integer k.
An index i is beautiful when both of these hold:
astarts ati, sos[i..i + a.length - 1]equalsa. The match must fit insides.- Some index
jexists wheres[j..j + b.length - 1]equalsb, and the distance|j - i|is at mostk.
Return the beautiful indices as an array, sorted from smallest to largest.
Example 1
Input: s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15 Output: [16,33] Explanation: Index 16 is beautiful because s[16..17] is "my" and s[4..11] is "squirrel", with |16 - 4| <= 15. Index 33 is beautiful because s[33..34] is "my" and s[18..25] is "squirrel", with |33 - 18| <= 15. The answer is [16,33].
Example 2
Input: s = "abcd", a = "a", b = "a", k = 4 Output: [0] Explanation: Index 0 is beautiful because s[0..0] is "a", and index 0 also holds "a" with |0 - 0| <= 4. The answer is [0].
Constraints
1 <= k <= s.length <= 5 * 10^51 <= a.length, b.length <= 5 * 10^5s,a, andbuse only lowercase English letters.
Constraints that matter
- n up to 5 * 10^5 rules out checking every pair of positions, which is about 2.5 * 10^11 comparisons in the worst case.
- The distance limit k can be as large as n, so a window check must cost O(1) or O(log n), not a scan of the window.
- Patterns can be as long as s, and occurrences can overlap, so matching must not restart from scratch after each mismatch.
- Only lowercase letters appear, so you can compare characters directly without normalising anything.
Hints
Hint 1
The problem asks for every occurrence of two fixed patterns inside one text.
Hint 2
Try every start i for a.
Solution
Intuition
The problem asks for every occurrence of two fixed patterns inside one text. A naive scan throws away what it learned after each mismatch and starts over. The Knuth-Morris-Pratt (KMP) algorithm reuses that knowledge through a failure table, so it finds every occurrence in one linear pass.
Picture a row of mailboxes, one per position in the text, with a flag dropped in each box where b starts. The prefix array is a running tally written on each box, so a window check is one subtraction.
The second question is about ranges. For each start i of a, you need to know whether any start of b lies between i - k and i + k. Mark every start of b on an array of 0s and 1s. Then a range question becomes a count, and prefix sums answer any count with one subtraction.
Together these two tools solve the problem. KMP produces the occurrence lists, and prefix sums turn each window into a constant-time check. The output comes out sorted because you scan s from left to right.
Worked example
Input: s = "abcd", a = "a", b = "a", k = 4 Output: [0] Explanation: The only start of a is index 0. The only start of b is also index 0, and the distance between them is 0, which is within k = 4. So index 0 is the single beautiful index.
Approach 1: Brute force
Try every start i for a. When a matches at i, try every start j for b and accept i as soon as one j is close enough and matches. Each candidate i rescans the whole string, and nothing learned from one position carries over to the next.
Steps
- Loop
iover every start whereafits insides. - Skip
iunlessscontainsaat positioni. - For a matching
i, loopjover every start wherebfits insides. - If
|i - j| <= kandscontainsbatj, recordiand stop the inner loop. - Return the recorded indices. They are already in increasing order.
Dry run
Take s = "abcd", a = "a", b = "a", k = 4. The outer loop checks i = 0 first, and s[0] is "a", so the inner loop starts.
The inner loop tries j = 0. The distance |0 - 0| is 0, which is within 4, and s[0] is "a". So it records 0 and stops.
The outer loop then tries i = 1, 2 and 3. Each one fails the check for a. The result is [0].
Complexity
| Time | O(n^2 * m) |
|---|---|
| Space | O(1) extra, not counting the output list |
Let n be the length of s and m the length of b. The outer loop tries up to n starts, and each matching start runs an inner loop over up to n starts. Each inner check compares up to m characters, so the worst case is O(n * n * m). Only a few integers are stored besides the output, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]:
res = []
for i in range(len(s) - len(a) + 1):
if s[i:i + len(a)] != a:
continue
for j in range(len(s) - len(b) + 1):
if abs(i - j) <= k and s[j:j + len(b)] == b:
res.append(i)
break
return resThe Naive / KMP / Rabin-Karp infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Naive / KMP / Rabin-Karp
Part of String Manipulation Patterns
Approach 2: KMP occurrences + prefix countsOptimalNaive / KMP / Rabin-Karp
What's slow: the brute force rescans s for every candidate i and every j. What's slow: each window check walks many positions of b.
The insight that fixes the first problem: KMP lists every occurrence of a pattern in one left-to-right pass, so s is read a fixed number of times.
The insight that fixes the second problem: mark each start of b on an array and build prefix counts. Then the question "is there a start of b in [lo, hi]?" becomes one subtraction.
Why it is correct. KMP keeps the length of the longest prefix of the pattern that ends at the current position of s. The failure table gives the next longest such prefix after a mismatch, so no occurrence is skipped. Prefix sums count every start of b exactly, so the range test over [lo, hi] is exact too.
Steps
- Run KMP on
swith patternb, and mark each startjat slotj + 1of an arraypreof length n + 2. - Replace
prewith its prefix sums, sopre[x]counts starts ofbbelowx. - Run KMP on
swith patternato get every starti. - For each
i, setlo = max(0, i - k)andhi = min(n - |b|, i + k). - If
lo <= hiandpre[hi + 1] - pre[lo] > 0, keepi. - Return the kept indices in the order they were found.
Dry run
Take s = "abcd", a = "a", b = "a", k = 4. Here n = 4, so pre has length 6.
| Step | Action | State |
|---|---|---|
| 1 | KMP for b = "a" in "abcd" | starts of b = [0], so pre becomes [0, 1, 1, 1, 1, 1] after prefix sums |
| 2 | KMP for a = "a" in "abcd" | starts of a = [0] |
| 3 | i = 0: lo = max(0, -4) = 0, hi = min(3, 4) = 3 | pre[4] - pre[0] = 1 - 0 = 1 |
| 4 | Count is 1 > 0, so keep 0 | result = [0] |
The result is [0], which matches the expected output.
Complexity
| Time | O(n + |a| + |b|) |
|---|---|
| Space | O(n) |
Let n be the length of s, A the length of a, and B the length of b. Building each failure table costs O(A) or O(B), and each KMP scan of s takes O(n) because the pointer rises by at most one per character and every fall is paid for by an earlier rise. The prefix array and the filter loop each take O(n), since there are at most n occurrences. The total is O(n + A + B), and the arrays use O(n) space.
PythonTested in our runner
from typing import List, Optional
class Solution:
def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]:
def occurrences(text: str, pat: str) -> List[int]:
m = len(pat)
lps = [0] * m
length, i = 0, 1
while i < m:
if pat[i] == pat[length]:
length += 1
lps[i] = length
i += 1
elif length:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
res, q = [], 0
for pos, ch in enumerate(text):
while q and ch != pat[q]:
q = lps[q - 1]
if ch == pat[q]:
q += 1
if q == m:
res.append(pos - m + 1)
q = lps[q - 1]
return res
n, m = len(s), len(b)
pre = [0] * (n + 2)
for j in occurrences(s, b):
pre[j + 1] += 1
for x in range(1, n + 2):
pre[x] += pre[x - 1]
res = []
for i in occurrences(s, a):
lo = max(0, i - k)
hi = min(n - m, i + k)
if lo <= hi and pre[hi + 1] - pre[lo] > 0:
res.append(i)
return resCommon mistakes
- Writing
hi = i + kwith no clamp ton - |b|. The indexhi + 1then runs past the end ofpre. Clamphiton - |b|first. - Reading
pre[hi]instead ofpre[hi + 1]. That drops a start ofbsitting exactly athi, so a distance-k match at the right edge is missed. - Computing
lo = i - kwithout a floor at 0. A negative index wraps in Python and reads the wrong slot in other languages. Clamploto 0. - Setting
q = 0after a full KMP match. That misses overlapping occurrences such as "aa" inside "aaa". Setq = lps[q - 1]instead. - Testing
abs(i - j) < k. The statement allows distance exactly k, so the test must use<=.
Edge cases
bis longer thans: there are no starts ofb, so the answer is [].ais longer thans: there are no starts ofa, so the answer is [].k = 0: only an index whereaandbstart at the same position qualifies.s = "aaaa",a = "aa",b = "a",k = 1: the starts ofaoverlap at 0, 1 and 2, and each has abwithin distance 1, so the answer is [0,1,2].kat leastnwithbpresent once: every occurrence ofaqualifies, so the answer is all starts ofain order.- An occurrence of
anear the end ofswithbnear the start: the clamp onhimust still let the distance check succeed or fail correctly.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Find Beautiful Indices in the Given Array II, with how to answer them.
Unlock the follow-upsFind Beautiful Indices in the Given Array II FAQ
What is the time complexity of Find Beautiful Indices in the Given Array II?
The KMP approach runs in O(n + |a| + |b|) time, where n is the length of s. The brute force takes O(n^2 * |b|) time in the worst case. Both bounds are proven in the complexity sections above.
Why use KMP for Find Beautiful Indices in the Given Array II?
Each pattern must be found many times in s, and naive matching restarts after every mismatch. KMP keeps the text pointer moving forward and reuses matched prefixes through the failure table.
Can Find Beautiful Indices in the Given Array II be solved in O(1) extra space?
Not with this layout. The prefix array has n + 2 entries, and the occurrence lists can hold up to n indices, for example when s is all one letter. The output list grows with the answer in any case.
Does the result need sorting at the end?
No. You scan s from left to right, so the starts of a already come in increasing order, and the kept indices keep that order.
Why does the brute force time out here?
With n up to 5 * 10^5, n^2 is about 2.5 * 10^11 comparisons in the worst case. That is far beyond what a one-second limit allows. The prefix counts remove the inner scan entirely.
Asked at
See which companies ask this — Pro
Related problems
- Shortest Palindrome · same technique: Naive / KMP / Rabin-Karp
- Repeated String Match · same technique: Naive / KMP / Rabin-Karp
- Longest Common Prefix · same technique: Naive / KMP / Rabin-Karp
- Find the Index of the First Occurrence in a String · same technique: Naive / KMP / Rabin-Karp
- Rotate String · same technique: Naive / KMP / Rabin-Karp
- Group Anagrams · same pattern: String Manipulation Patterns
- Multiply Strings · same pattern: String Manipulation Patterns
- Integer to Roman · same pattern: String Manipulation Patterns
- String to Integer (atoi) · same pattern: String Manipulation Patterns
- Valid Anagram · same pattern: String Manipulation Patterns