The Find Beautiful Indices in the Given Array I interview question asks you to find all "beautiful" indices i in a string s. An index i is beautiful if:
s[i...i+a.length()-1] == aj such that s[j...j+b.length()-1] == b and .
Basically, you need to find all occurrences of pattern a that have at least one occurrence of pattern b within distance k.Companies like Palantir and Samsara use this problem to test your string matching and search optimization skills. It evaluation whether you can efficiently find patterns and then coordinate the results of two different searches. While the "I" version allows for less optimal solutions, the String Matching interview pattern is a core part of many data analysis and log processing tasks.
This problem is solved using String Matching and Binary Search (or Two Pointers).
a appears in s. Store them in a sorted list pos_a.b appears in s. Store them in a sorted list pos_b.i in pos_a:
j in pos_b such that i - k <= j <= i + k.lower_bound or bisect_left) on the sorted list pos_b.s = "isabcdeisabf", a = "ab", b = "is", k = 4
pos_a: [2, 9] (occurrences of "ab").pos_b: [0, 7] (occurrences of "is").pos_a:
j in pos_b s.t. ? Yes, works. 2 is beautiful.pos_a:
j in pos_b s.t. ? Yes, works. 9 is beautiful.
Result: [2, 9].a with every occurrence of b without using binary search or two pointers.When coordinating two sets of indices, always sort them first. Once sorted, you can use binary search to check for existence in logarithmic time, which is a standard way to optimize nested loops.