Skip to content

3008. Find Beautiful Indices in the Given Array II 👍

  • Time: $O(|\texttt{s}| + |\texttt{a}| + |\texttt{b}|)$
  • Space: $O(|\texttt{s}| + |\texttt{a}| + |\texttt{b}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution {
 public:
  // Same as 3006. Find Beautiful Indices in the Given Array I
  vector<int> beautifulIndices(string s, string a, string b, int k) {
    vector<int> ans;
    const vector<int> indicesA = kmp(s, a);
    const vector<int> indicesB = kmp(s, b);
    int indicesBIndex = 0;  // indicesB's index

    for (const int i : indicesA) {
      // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move
      // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex].
      while (indicesBIndex < indicesB.size() &&
             indicesB[indicesBIndex] - i < -k)
        ++indicesBIndex;
      if (indicesBIndex < indicesB.size() && indicesB[indicesBIndex] - i <= k)
        ans.push_back(i);
    }

    return ans;
  }

 private:
  // Returns the starting indices of all occurrences of the pattern in `s`.
  vector<int> kmp(const string& s, const string& pattern) {
    vector<int> res;
    const vector<int> lps = getLPS(pattern);
    int i = 0;  // s' index
    int j = 0;  // pattern's index
    while (i < s.length()) {
      if (s[i] == pattern[j]) {
        ++i;
        ++j;
        if (j == pattern.length()) {
          res.push_back(i - j);
          j = lps[j - 1];
        }
      }
      // Mismatch after j matches.
      else if (j > 0) {
        // Don't match lps[0..lps[j - 1]] since they will match anyway.
        j = lps[j - 1];
      } else {
        ++i;
      }
    }
    return res;
  }

  // Returns the lps array, where lps[i] is the length of the longest prefix of
  // pattern[0..i] which is also a suffix of this substring.
  vector<int> getLPS(const string& pattern) {
    vector<int> lps(pattern.length());
    for (int i = 1, j = 0; i < pattern.length(); ++i) {
      while (j > 0 && pattern[j] != pattern[i])
        j = lps[j - 1];
      if (pattern[i] == pattern[j])
        lps[i] = ++j;
    }
    return lps;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
  // Same as 3006. Find Beautiful Indices in the Given Array I
  public List<Integer> beautifulIndices(String s, String a, String b, int k) {
    List<Integer> ans = new ArrayList<>();
    List<Integer> indicesA = kmp(s, a);
    List<Integer> indicesB = kmp(s, b);
    int indicesBIndex = 0; // indicesB' index

    for (final int i : indicesA) {
      // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move
      // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex].
      while (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i < -k)
        ++indicesBIndex;
      if (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i <= k)
        ans.add(i);
    }

    return ans;
  }

  // Returns the starting indices of all occurrences of the pattern in `s`.
  private List<Integer> kmp(final String s, final String pattern) {
    List<Integer> res = new ArrayList<>();
    int[] lps = getLPS(pattern);
    int i = 0; // s' index
    int j = 0; // pattern's index
    while (i < s.length()) {
      if (s.charAt(i) == pattern.charAt(j)) {
        ++i;
        ++j;
        if (j == pattern.length()) {
          res.add(i - j);
          j = lps[j - 1];
        }
      }
      // Mismatch after j matches.
      else if (j != 0) {
        // Don't match lps[0..lps[j - 1]] since they will match anyway.
        j = lps[j - 1];
      } else {
        ++i;
      }
    }
    return res;
  }

  // Returns the lps array, where lps[i] is the length of the longest prefix of
  // pattern[0..i] which is also a suffix of this substring.
  private int[] getLPS(final String pattern) {
    int[] lps = new int[pattern.length()];
    for (int i = 1, j = 0; i < pattern.length(); ++i) {
      while (j > 0 && pattern.charAt(j) != pattern.charAt(i))
        j = lps[j - 1];
      if (pattern.charAt(i) == pattern.charAt(j))
        lps[i] = ++j;
    }
    return lps;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution:
  # Same as 3006. Find Beautiful Indices in the Given Array I
  def beautifulIndices(self, s: str, a: str, b: str, k: int) -> list[int]:
    ans = []
    indicesA = self._kmp(s, a)
    indicesB = self._kmp(s, b)
    indicesBIndex = 0  # indicesB' index

    for i in indicesA:
      # The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move
      # `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex].
      while indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i < -k:
        indicesBIndex += 1
      if indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i <= k:
        ans.append(i)

    return ans

  def _kmp(self, s: str, pattern: str) -> list[int]:
    """Returns the starting indices of all occurrences of the pattern in `s`."""

    def getLPS(pattern: str) -> list[int]:
      """
      Returns the lps array, where lps[i] is the length of the longest prefix of
      pattern[0..i] which is also a suffix of this substring.
      """
      lps = [0] * len(pattern)
      j = 0
      for i in range(1, len(pattern)):
        while j > 0 and pattern[j] != pattern[i]:
          j = lps[j - 1]
        if pattern[i] == pattern[j]:
          lps[i] = j + 1
          j += 1
      return lps

    lps = getLPS(pattern)
    res = []
    i = 0  # s' index
    j = 0  # pattern's index
    while i < len(s):
      if s[i] == pattern[j]:
        i += 1
        j += 1
        if j == len(pattern):
          res.append(i - j)
          j = lps[j - 1]
      # Mismatch after j matches.
      elif j != 0:
          # Don't match lps[0..lps[j - 1]] since they will match anyway.
        j = lps[j - 1]
      else:
        i += 1
    return res