Find Beautiful Indices in the Given Array II - Problem
You're tasked with finding beautiful indices in a string - a fascinating pattern matching challenge!
Given a string s, two pattern strings a and b, and an integer k, an index i is considered beautiful if:
- Pattern Match: The substring starting at index
imatches patterna - Proximity Condition: There exists another index
jwhere patternbappears, and the distance betweeniandjis at mostk
Your goal is to return all beautiful indices in sorted order.
Example: If s = "isawsquirrelsaw", a = "saw", b = "sq", and k = 6, then index 2 is beautiful because "saw" appears at index 2, "sq" appears at index 5, and |2-5| = 3 โค 6.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "isawsquirrelsaw", a = "saw", b = "sq", k = 6
โบ
Output:
[2, 11]
๐ก Note:
Pattern 'saw' appears at indices 2 and 11. Pattern 'sq' appears at index 5. For index 2: |2-5| = 3 โค 6, so it's beautiful. For index 11: |11-5| = 6 โค 6, so it's also beautiful.
example_2.py โ No Beautiful Indices
$
Input:
s = "abcd", a = "a", b = "a", k = 4
โบ
Output:
[0]
๐ก Note:
Pattern 'a' appears only at index 0. Since both patterns are the same, the distance is |0-0| = 0 โค 4, making index 0 beautiful.
example_3.py โ Distance Constraint
$
Input:
s = "aba", a = "a", b = "a", k = 1
โบ
Output:
[0, 2]
๐ก Note:
Pattern 'a' appears at indices 0 and 2. For index 0: distance to index 2 is |0-2| = 2 > 1, but distance to itself is 0 โค 1. For index 2: distance to index 0 is 2 > 1, but distance to itself is 0 โค 1. Both are beautiful.
Visualization
Tap to expand
Understanding the Visualization
1
Scan for Primary Patterns
Find all occurrences of pattern 'a' in the string - these are potential beautiful indices
2
Locate Secondary Patterns
Find all occurrences of pattern 'b' - these provide the proximity validation
3
Check Proximity Constraint
For each pattern 'a' occurrence, verify if any pattern 'b' is within distance k
4
Collect Beautiful Indices
Indices that satisfy both pattern match and proximity constraints are beautiful
Key Takeaway
๐ฏ Key Insight: The algorithm transforms a quadratic proximity search into efficient pattern preprocessing plus logarithmic lookups, making it scalable for large inputs while maintaining correctness.
Time & Space Complexity
Time Complexity
O(n + m + p)
O(n) pattern finding + O(m + p) two-pointer traversal where m,p are pattern occurrence counts
โ Linear Growth
Space Complexity
O(m + p)
Space to store pattern occurrences
โ Linear Space
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
- Pattern lengths are much smaller than string length
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code