#3008
Find Beautiful Indices in the Given Array II
HardTwo PointersStringBinary SearchRolling HashString MatchingHash FunctionString MatchingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using efficient string searching techniques like the KMP algorithm allows us to find all occurrences of 'a' and 'b' in linear time. This reduces the need for nested loops and significantly speeds up the process.
⚙️
Algorithm
3 steps- 1Step 1: Use KMP or a similar algorithm to find all starting indices of substring 'a' in 's'.
- 2Step 2: Use KMP or a similar algorithm to find all starting indices of substring 'b' in 's'.
- 3Step 3: Use a two-pointer technique to check for each index of 'a' if there exists an index of 'b' such that the absolute difference is less than or equal to 'k'.
solution.py44 lines
1def kmp_search(s, pattern):
2 m, n = len(pattern), len(s)
3 lps = [0] * m
4 j = 0
5 i = 1
6 while i < m:
7 if pattern[i] == pattern[j]:
8 j += 1
9 lps[i] = j
10 i += 1
11 else:
12 if j != 0:
13 j = lps[j - 1]
14 else:
15 lps[i] = 0
16 i += 1
17 indices = []
18 i = 0
19 j = 0
20 while i < n:
21 if pattern[j] == s[i]:
22 i += 1
23 j += 1
24 if j == m:
25 indices.append(i - j)
26 j = lps[j - 1]
27 elif i < n and pattern[j] != s[i]:
28 if j != 0:
29 j = lps[j - 1]
30 else:
31 i += 1
32 return indices
33
34def beautiful_indices(s, a, b, k):
35 indices_a = kmp_search(s, a)
36 indices_b = kmp_search(s, b)
37 beautiful = []
38 j = 0
39 for i in indices_a:
40 while j < len(indices_b) and indices_b[j] < i - k:
41 j += 1
42 if j < len(indices_b) and abs(indices_b[j] - i) <= k:
43 beautiful.append(i)
44 return sorted(set(beautiful))ℹ
Complexity note: The time complexity is O(n) because we efficiently find all occurrences of 'a' and 'b' using KMP, and then we only traverse the lists of indices once.
- 1Using efficient string matching algorithms like KMP can drastically reduce the time complexity.
- 2The two-pointer technique helps in efficiently checking the distance condition without unnecessary comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.