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' 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
INPUTALGORITHMRESULTString s:"isawsquirrelnearmylaptop"Pattern a = "my"Pattern b = "squirrel"Distance k = 15"my" at 16"squirrel" at 4Check: |16 - 4| = 1212 <= 15 ✓1Find Pattern PositionsScan string for "my" and "squirrel"2Check DistancesFor each "my", find nearby "squirrel"3Validate Constraint|position_a - position_b| <= k4Collect ResultsAdd valid indices to output arrayBeautiful Indices[16]Index 16 is beautiful because:• "my" found at position 16• "squirrel" found at position 4• Distance |16-4| = 12 <= 15Key Insight:Pre-compute all pattern positions, then use binary search for efficient range queries within distance kTutorialsPoint - Find Beautiful Indices in the Given Array II | Binary Search Approach
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
247 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