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 in Array INPUT String s: isawsquirrelnearmylaptop 0 4 12 16 20 squirrel idx 4-11 my idx 16-17 a = "my" b = "squirrel" k = 15 Index Line (0-23) j=4 i=16 |16-4| = 12 12 <= 15 (k) Beautiful Index Condition: s[i..] matches a AND exists j where s[j..] matches b ALGORITHM STEPS 1 Find all indices of 'a' Search "my" in string a_idx=[16] 2 Find all indices of 'b' Search "squirrel" in string b_idx=[4] 3 Check distance |j-i| For each i, find j where |j - i| <= k i=16, j=4 |4-16| = 12 <= 15 OK - Valid! 4 Collect beautiful indices Add i=16 to result Optimization: Use binary search to find closest j in range [i-k, i+k] FINAL RESULT Beautiful Indices Found: [16] Verification for i=16: 1. 0 <= 16 <= 24-2 = 22 OK 2. s[16..17] = "my" == a OK 3. j=4 exists, s[4..11]="squirrel" OK 4. |4-16|=12 <= 15 OK Index 16 is Beautiful! Output: [16] Key Insight: Use string matching to find all occurrences of 'a' and 'b'. For each index i where 'a' matches, use binary search to efficiently check if any index j (where 'b' matches) exists within distance k. This reduces time complexity from O(n*m) to O(n*log(m)) where n and m are occurrence counts. TutorialsPoint - Find Beautiful Indices in the Given Array I | Optimal Solution
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