15% off all plans & roadmaps Use code

See plans

Find Beautiful Indices in the Given Array II

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:

  • a starts at i, so s[i..i + a.length - 1] equals a. The match must fit inside s.
  • Some index j exists where s[j..j + b.length - 1] equals b, and the distance |j - i| is at most k.

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^5
  • 1 <= a.length, b.length <= 5 * 10^5
  • s, a, and b use 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Loop i over every start where a fits inside s.
  2. Skip i unless s contains a at position i.
  3. For a matching i, loop j over every start where b fits inside s.
  4. If |i - j| <= k and s contains b at j, record i and stop the inner loop.
  5. 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

TimeO(n^2 * m)
SpaceO(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 res

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

Solution 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

  1. Run KMP on s with pattern b, and mark each start j at slot j + 1 of an array pre of length n + 2.
  2. Replace pre with its prefix sums, so pre[x] counts starts of b below x.
  3. Run KMP on s with pattern a to get every start i.
  4. For each i, set lo = max(0, i - k) and hi = min(n - |b|, i + k).
  5. If lo <= hi and pre[hi + 1] - pre[lo] > 0, keep i.
  6. 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.

StepActionState
1KMP for b = "a" in "abcd"starts of b = [0], so pre becomes [0, 1, 1, 1, 1, 1] after prefix sums
2KMP for a = "a" in "abcd"starts of a = [0]
3i = 0: lo = max(0, -4) = 0, hi = min(3, 4) = 3pre[4] - pre[0] = 1 - 0 = 1
4Count is 1 > 0, so keep 0result = [0]

The result is [0], which matches the expected output.

Complexity

TimeO(n + |a| + |b|)
SpaceO(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 res

Common mistakes

  • Writing hi = i + k with no clamp to n - |b|. The index hi + 1 then runs past the end of pre. Clamp hi to n - |b| first.
  • Reading pre[hi] instead of pre[hi + 1]. That drops a start of b sitting exactly at hi, so a distance-k match at the right edge is missed.
  • Computing lo = i - k without a floor at 0. A negative index wraps in Python and reads the wrong slot in other languages. Clamp lo to 0.
  • Setting q = 0 after a full KMP match. That misses overlapping occurrences such as "aa" inside "aaa". Set q = lps[q - 1] instead.
  • Testing abs(i - j) < k. The statement allows distance exactly k, so the test must use <=.

Edge cases

  • b is longer than s: there are no starts of b, so the answer is [].
  • a is longer than s: there are no starts of a, so the answer is [].
  • k = 0: only an index where a and b start at the same position qualifies.
  • s = "aaaa", a = "aa", b = "a", k = 1: the starts of a overlap at 0, 1 and 2, and each has a b within distance 1, so the answer is [0,1,2].
  • k at least n with b present once: every occurrence of a qualifies, so the answer is all starts of a in order.
  • An occurrence of a near the end of s with b near the start: the clamp on hi must 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-ups

Find 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

Practise it