You are given a 0-indexed string s, a string a, a string b, and an integer k.
An index i is beautiful if:
0 <= i <= s.length - a.length
s[i..(i + a.length - 1)] == a
There exists an index j such that:
0 <= j <= s.length - b.length
s[j..(j + b.length - 1)] == b
|j - i| <= k
Return the array that contains beautiful indices in sorted order from smallest to largest.
Example 1:
Input: s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15
Output: [16,33]
Explanation: There are 2 beautiful indices: [16,33].
- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.
- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.
Thus we return [16,33] as the result.
Example 2:
Input: s = "abcd", a = "a", b = "a", k = 4
Output: [0]
Explanation: There is 1 beautiful index: [0].
- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.
Thus we return [0] as the result.
Constraints:
1 <= k <= s.length <= 5 * 105
1 <= a.length, b.length <= 5 * 105
s, a, and b contain only lowercase English letters.
Problem summary: You are given a 0-indexed string s, a string a, a string b, and an integer k. An index i is beautiful if: 0 <= i <= s.length - a.length s[i..(i + a.length - 1)] == a There exists an index j such that: 0 <= j <= s.length - b.length s[j..(j + b.length - 1)] == b |j - i| <= k Return the array that contains beautiful indices in sorted order from smallest to largest.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers · Binary Search · String Matching
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3008: Find Beautiful Indices in the Given Array II
public class Solution {
public void computeLPS(String pattern, int[] lps) {
int M = pattern.length();
int len = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pattern.charAt(i) == pattern.charAt(len)) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
public List<Integer> KMP_codestorywithMIK(String pat, String txt) {
int N = txt.length();
int M = pat.length();
List<Integer> result = new ArrayList<>();
int[] lps = new int[M];
computeLPS(pat, lps);
int i = 0; // Index for text
int j = 0; // Index for pattern
while (i < N) {
if (pat.charAt(j) == txt.charAt(i)) {
i++;
j++;
}
if (j == M) {
result.add(i - j); // Pattern found at index i-j+1 (If you have to return 1 Based
// indexing, that's why added + 1)
j = lps[j - 1];
} else if (i < N && pat.charAt(j) != txt.charAt(i)) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return result;
}
private int lowerBound(List<Integer> list, int target) {
int left = 0, right = list.size() - 1, result = list.size();
while (left <= right) {
int mid = left + (right - left) / 2;
if (list.get(mid) >= target) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
public List<Integer> beautifulIndices(String s, String a, String b, int k) {
int n = s.length();
List<Integer> i_indices = KMP_codestorywithMIK(a, s);
List<Integer> j_indices = KMP_codestorywithMIK(b, s);
List<Integer> result = new ArrayList<>();
for (int i : i_indices) {
int left_limit = Math.max(0, i - k); // To avoid out of bound -> I used max(0, i-k)
int right_limit
= Math.min(n - 1, i + k); // To avoid out of bound -> I used min(n-1, i+k)
int lowerBoundIndex = lowerBound(j_indices, left_limit);
if (lowerBoundIndex < j_indices.size()
&& j_indices.get(lowerBoundIndex) <= right_limit) {
result.add(i);
}
}
return result;
}
}
// Accepted solution for LeetCode #3008: Find Beautiful Indices in the Given Array II
func beautifulIndices(s string, a string, b string, k int) []int {
s_len := len(s)
a_len := len(a)
b_len := len(b)
final := make([]int, 0)
lps_a := make([]int, a_len)
lps_b := make([]int, b_len)
a_index := make([]int, 0)
b_index := make([]int, 0)
var pat func(lps []int, s_l int, pattern string)
pat = func(lps []int, s_l int, pattern string) {
l := 0
lps[0] = 0
i := 1
for i < s_l {
if pattern[i] == pattern[l] {
l++
lps[i] = l
i++
} else {
if l != 0 {
l = lps[l-1]
} else {
lps[i] = l
i++
}
}
}
}
pat(lps_a, a_len, a)
pat(lps_b, b_len, b)
var kmp func(pat string, pat_l int, lps []int, index *[]int)
kmp = func(pat string, pat_l int, lps []int, index *[]int) {
i := 0
j := 0
for s_len-i >= pat_l-j {
if s[i] == pat[j] {
i++
j++
}
if j == pat_l {
*index = append(*index, i-pat_l)
j = lps[j-1]
} else if s[i] != pat[j] {
if j != 0 {
j = lps[j-1]
} else {
i++
}
}
}
}
kmp(a, a_len, lps_a, &a_index)
kmp(b, b_len, lps_b, &b_index)
// fmt.Println(a_index, b_index)
i := 0
j := 0
for i < len(a_index) && j < len(b_index) {
if a_index[i]+k >= b_index[j] && a_index[i]-k <= b_index[j] {
final = append(final, a_index[i])
i++
} else if a_index[i]-k > b_index[j] {
j++
} else {
i++
}
}
return final
}
# Accepted solution for LeetCode #3008: Find Beautiful Indices in the Given Array II
class Solution:
def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]:
def build_prefix_function(pattern):
prefix_function = [0] * len(pattern)
j = 0
for i in range(1, len(pattern)):
while j > 0 and pattern[i] != pattern[j]:
j = prefix_function[j - 1]
if pattern[i] == pattern[j]:
j += 1
prefix_function[i] = j
return prefix_function
def kmp_search(pattern, text, prefix_function):
occurrences = []
j = 0
for i in range(len(text)):
while j > 0 and text[i] != pattern[j]:
j = prefix_function[j - 1]
if text[i] == pattern[j]:
j += 1
if j == len(pattern):
occurrences.append(i - j + 1)
j = prefix_function[j - 1]
return occurrences
prefix_a = build_prefix_function(a)
prefix_b = build_prefix_function(b)
resa = kmp_search(a, s, prefix_a)
resb = kmp_search(b, s, prefix_b)
res = []
print(resa, resb)
i = 0
j = 0
while i < len(resa):
while j < len(resb):
if abs(resb[j] - resa[i]) <= k:
res.append(resa[i])
break
elif j + 1 < len(resb) and abs(resb[j + 1] - resa[i]) < abs(
resb[j] - resa[i]
):
j += 1
else:
break
i += 1
return res
// Accepted solution for LeetCode #3008: Find Beautiful Indices in the Given Array II
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3008: Find Beautiful Indices in the Given Array II
// public class Solution {
// public void computeLPS(String pattern, int[] lps) {
// int M = pattern.length();
// int len = 0;
//
// lps[0] = 0;
//
// int i = 1;
// while (i < M) {
// if (pattern.charAt(i) == pattern.charAt(len)) {
// len++;
// lps[i] = len;
// i++;
// } else {
// if (len != 0) {
// len = lps[len - 1];
// } else {
// lps[i] = 0;
// i++;
// }
// }
// }
// }
//
// public List<Integer> KMP_codestorywithMIK(String pat, String txt) {
// int N = txt.length();
// int M = pat.length();
// List<Integer> result = new ArrayList<>();
//
// int[] lps = new int[M];
// computeLPS(pat, lps);
//
// int i = 0; // Index for text
// int j = 0; // Index for pattern
//
// while (i < N) {
// if (pat.charAt(j) == txt.charAt(i)) {
// i++;
// j++;
// }
//
// if (j == M) {
// result.add(i - j); // Pattern found at index i-j+1 (If you have to return 1 Based
// // indexing, that's why added + 1)
// j = lps[j - 1];
// } else if (i < N && pat.charAt(j) != txt.charAt(i)) {
// if (j != 0) {
// j = lps[j - 1];
// } else {
// i++;
// }
// }
// }
//
// return result;
// }
//
// private int lowerBound(List<Integer> list, int target) {
// int left = 0, right = list.size() - 1, result = list.size();
//
// while (left <= right) {
// int mid = left + (right - left) / 2;
//
// if (list.get(mid) >= target) {
// result = mid;
// right = mid - 1;
// } else {
// left = mid + 1;
// }
// }
//
// return result;
// }
//
// public List<Integer> beautifulIndices(String s, String a, String b, int k) {
// int n = s.length();
//
// List<Integer> i_indices = KMP_codestorywithMIK(a, s);
// List<Integer> j_indices = KMP_codestorywithMIK(b, s);
//
// List<Integer> result = new ArrayList<>();
//
// for (int i : i_indices) {
//
// int left_limit = Math.max(0, i - k); // To avoid out of bound -> I used max(0, i-k)
// int right_limit
// = Math.min(n - 1, i + k); // To avoid out of bound -> I used min(n-1, i+k)
//
// int lowerBoundIndex = lowerBound(j_indices, left_limit);
//
// if (lowerBoundIndex < j_indices.size()
// && j_indices.get(lowerBoundIndex) <= right_limit) {
// result.add(i);
// }
// }
//
// return result;
// }
// }
// Accepted solution for LeetCode #3008: Find Beautiful Indices in the Given Array II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3008: Find Beautiful Indices in the Given Array II
// public class Solution {
// public void computeLPS(String pattern, int[] lps) {
// int M = pattern.length();
// int len = 0;
//
// lps[0] = 0;
//
// int i = 1;
// while (i < M) {
// if (pattern.charAt(i) == pattern.charAt(len)) {
// len++;
// lps[i] = len;
// i++;
// } else {
// if (len != 0) {
// len = lps[len - 1];
// } else {
// lps[i] = 0;
// i++;
// }
// }
// }
// }
//
// public List<Integer> KMP_codestorywithMIK(String pat, String txt) {
// int N = txt.length();
// int M = pat.length();
// List<Integer> result = new ArrayList<>();
//
// int[] lps = new int[M];
// computeLPS(pat, lps);
//
// int i = 0; // Index for text
// int j = 0; // Index for pattern
//
// while (i < N) {
// if (pat.charAt(j) == txt.charAt(i)) {
// i++;
// j++;
// }
//
// if (j == M) {
// result.add(i - j); // Pattern found at index i-j+1 (If you have to return 1 Based
// // indexing, that's why added + 1)
// j = lps[j - 1];
// } else if (i < N && pat.charAt(j) != txt.charAt(i)) {
// if (j != 0) {
// j = lps[j - 1];
// } else {
// i++;
// }
// }
// }
//
// return result;
// }
//
// private int lowerBound(List<Integer> list, int target) {
// int left = 0, right = list.size() - 1, result = list.size();
//
// while (left <= right) {
// int mid = left + (right - left) / 2;
//
// if (list.get(mid) >= target) {
// result = mid;
// right = mid - 1;
// } else {
// left = mid + 1;
// }
// }
//
// return result;
// }
//
// public List<Integer> beautifulIndices(String s, String a, String b, int k) {
// int n = s.length();
//
// List<Integer> i_indices = KMP_codestorywithMIK(a, s);
// List<Integer> j_indices = KMP_codestorywithMIK(b, s);
//
// List<Integer> result = new ArrayList<>();
//
// for (int i : i_indices) {
//
// int left_limit = Math.max(0, i - k); // To avoid out of bound -> I used max(0, i-k)
// int right_limit
// = Math.min(n - 1, i + k); // To avoid out of bound -> I used min(n-1, i+k)
//
// int lowerBoundIndex = lowerBound(j_indices, left_limit);
//
// if (lowerBoundIndex < j_indices.size()
// && j_indices.get(lowerBoundIndex) <= right_limit) {
// result.add(i);
// }
// }
//
// return result;
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(1)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Boundary update without `+1` / `-1`
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.