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.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.

Input & Output

Example 1 — Basic Case
$ Input: s = "isawsquirrelnearmylaptop", a = "my", b = "squirrel", k = 15
Output: [16]
💡 Note: Pattern "my" found at index 16. Pattern "squirrel" found at index 8. Distance |8-16| = 8 ≤ 15, so index 16 is beautiful.
Example 2 — Multiple Matches
$ Input: s = "abcd", a = "a", b = "a", k = 4
Output: [0]
💡 Note: Pattern "a" found at index 0. Same pattern "a" also found at index 0. Distance |0-0| = 0 ≤ 4, so index 0 is beautiful.
Example 3 — No Beautiful Indices
$ Input: s = "abcd", a = "a", b = "d", k = 1
Output: []
💡 Note: Pattern "a" found at index 0. Pattern "d" found at index 3. Distance |3-0| = 3 > 1, so no beautiful indices exist.

Constraints

  • 1 ≤ s.length ≤ 5 × 105
  • 1 ≤ a.length, b.length ≤ s.length
  • 0 ≤ k ≤ s.length
  • s, a, and b consist only of lowercase English letters

Visualization

Tap to expand
Find Beautiful Indices: Pattern Matching with Distance ConstraintInput String:"isawsquirrelnearmylaptop"Pattern a = "my", Pattern b = "squirrel", k = 15squirrel at 8my at 16distance = 8Check: |16 - 8| = 8 ≤ 15 ✓Index 16 is beautiful!Output: [16]Beautiful indices are positions where pattern a occurs and pattern b is within distance k
Understanding the Visualization
1
Input
String s with patterns a, b and distance constraint k
2
Process
Find pattern matches and check distance constraints
3
Output
Indices where pattern a occurs and pattern b is within distance k
Key Takeaway
🎯 Key Insight: Separate pattern finding from distance checking for efficiency
Asked in
Google 25 Meta 18 Amazon 15
25.8K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen