Find Beautiful Indices in the Given Array II - Problem
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.lengths[i..(i + a.length - 1)] == a- There exists an index
jsuch that:0 <= j <= s.length - b.lengths[j..(j + b.length - 1)] == b|j - i| <= k
Return the array that contains beautiful indices in sorted order from smallest to largest.
Input & Output
Example 1 — Basic Case
$
Input:
s = "isawsquirrelnearmylaptop", a = "my", b = "squirrel", k = 15
›
Output:
[16]
💡 Note:
Pattern 'my' appears at index 16. Pattern 'squirrel' appears at index 4. Distance |16-4| = 12 <= 15, so index 16 is beautiful.
Example 2 — Multiple Matches
$
Input:
s = "abababab", a = "ab", b = "ba", k = 1
›
Output:
[0,2,4]
💡 Note:
Pattern 'ab' at indices [0,2,4,6]. Pattern 'ba' at indices [1,3,5]. Valid pairs: (0,1), (2,1), (2,3), (4,3), (4,5), (6,5). Beautiful indices: [0,2,4,6]. But 6 is not within k=1 of any 'ba', so result is [0,2,4].
Example 3 — No Valid Pairs
$
Input:
s = "abcd", a = "a", b = "d", k = 2
›
Output:
[]
💡 Note:
Pattern 'a' at index 0, pattern 'd' at index 3. Distance |3-0| = 3 > 2, so no beautiful indices exist.
Constraints
- 1 ≤ s.length ≤ 105
- 1 ≤ a.length, b.length ≤ 10
- 0 ≤ k ≤ s.length
- s, a, and b consist only of lowercase English letters.
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code