Find Beautiful Indices in the Given Array I - 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" occurs at index 16. Pattern "squirrel" occurs at index 5. Distance |16-5| = 11 ≤ 15, so index 16 is beautiful.
Example 2 — Multiple Matches
$ Input: s = "abcd", a = "a", b = "a", k = 4
Output: [0]
💡 Note: Pattern "a" occurs at index 0. The same pattern also serves as pattern b at the same position. Distance |0-0| = 0 ≤ 4, so index 0 is beautiful.
Example 3 — No Match
$ Input: s = "aaaa", a = "aa", b = "bb", k = 1
Output: []
💡 Note: Pattern "aa" occurs at indices 0, 1, 2, but pattern "bb" never occurs in the string, so no indices are beautiful.

Constraints

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

Visualization

Tap to expand
Beautiful Indices: Pattern Matching with Distance ConstraintInput: s = "isawsquirrelnearmylaptop"Pattern a = "my", Pattern b = "squirrel", k = 15i s a w s q u i r r e l n e a r m y l a p t o psquirrel (j=5)my(i=16)Distance = |16-5| = 11Beautiful Index Found!11 ≤ 15 ✓Output: [16]
Understanding the Visualization
1
Input String
Given string s with patterns a and b, and maximum distance k
2
Find Patterns
Locate all occurrences of pattern a and pattern b in the string
3
Check Distances
For each pattern a position, verify if any pattern b position is within distance k
Key Takeaway
🎯 Key Insight: Use binary search to efficiently find pattern matches within the distance constraint
Asked in
Google 12 Microsoft 8 Amazon 6
23.4K Views
Medium Frequency
~25 min Avg. Time
847 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