Skip to content

2781. Length of the Longest Valid Substring 👍

Approach 1: Hash Set

  • Time: $O(100n) = O(n)$
  • Space: $O(|\texttt{forbidden})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int longestValidSubstring(string word, vector<string>& forbidden) {
    int ans = 0;
    unordered_set<string> forbiddenSet{forbidden.begin(), forbidden.end()};

    // r is the rightmost index to make word[l..r] a valid substring.
    int r = word.length() - 1;
    for (int l = word.length() - 1; l >= 0; --l) {
      for (int end = l; end < min(l + 10, r + 1); ++end)
        if (forbiddenSet.contains(word.substr(l, end - l + 1))) {
          r = end - 1;
          break;
        }
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int longestValidSubstring(String word, List<String> forbidden) {
    int ans = 0;
    Set<String> forbiddenSet = new HashSet<>(forbidden);

    // r is the rightmost index to make word[l..r] a valid substring.
    int r = word.length() - 1;
    for (int l = word.length() - 1; l >= 0; --l) {
      for (int end = l; end < Math.min(l + 10, r + 1); ++end)
        if (forbiddenSet.contains(word.substring(l, end + 1))) {
          r = end - 1;
          break;
        }
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def longestValidSubstring(self, word: str, forbidden: list[str]) -> int:
    forbiddenSet = set(forbidden)
    ans = 0
    r = len(word) - 1  # rightmost index of the valid substring

    for l in range(len(word) - 1, -1, -1):
      for end in range(l, min(l + 10, r + 1)):
        if word[l:end + 1] in forbiddenSet:
          r = end - 1
          break
      ans = max(ans, r - l + 1)

    return ans

Approach 2: Trie

  • Time: $O(10n) = O(n)$
  • Space: $O(|\texttt{forbidden})$
 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
struct TrieNode {
 public:
  unordered_map<char, shared_ptr<TrieNode>> children;
  bool isWord = false;
};

class Trie {
 public:
  void insert(const string& word) {
    shared_ptr<TrieNode> node = root;
    for (const char c : word) {
      if (node->children[c] == nullptr)
        node->children[c] = make_shared<TrieNode>();
      node = node->children[c];
    }
    node->isWord = true;
  }

  bool search(const string& word, int l, int r) {
    shared_ptr<TrieNode> node = root;
    for (int j = l; j <= r; ++j) {
      const char c = word[j];
      if (node->children[c] == nullptr)
        return false;
      node = node->children[c];
    }
    return node->isWord;
  }

 private:
  shared_ptr<TrieNode> root = make_shared<TrieNode>();
};

class Solution {
 public:
  int longestValidSubstring(string word, vector<string>& forbidden) {
    int ans = 0;
    Trie trie;

    for (const string& s : forbidden)
      trie.insert(s);

    // r is the rightmost index to make word[l..r] a valid substring.
    int r = word.length() - 1;
    for (int l = word.length() - 1; l >= 0; --l) {
      for (int end = l; end < min(l + 10, r + 1); ++end)
        if (trie.search(word, l, end)) {
          r = end - 1;
          break;
        }
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 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
class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public boolean isWord = false;
}

class Trie {
  public void insert(String word) {
    TrieNode node = root;
    for (final char c : word.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        node.children[i] = new TrieNode();
      node = node.children[i];
    }
    node.isWord = true;
  }

  public boolean search(String word, int l, int r) {
    TrieNode node = root;
    for (int j = l; j <= r; ++j) {
      final int i = word.charAt(j) - 'a';
      if (node.children[i] == null)
        return false;
      node = node.children[i];
    }
    return node.isWord;
  }

  private TrieNode root = new TrieNode();
}

class Solution {
  public int longestValidSubstring(String word, List<String> forbidden) {
    int ans = 0;
    Trie trie = new Trie();

    for (final String s : forbidden)
      trie.insert(s);

    // r is the rightmost index to make word[l..r] a valid substring.
    int r = word.length() - 1;
    for (int l = word.length() - 1; l >= 0; --l) {
      for (int end = l; end < Math.min(l + 10, r + 1); ++end)
        if (trie.search(word, l, end)) {
          r = end - 1;
          break;
        }
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 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
class TrieNode:
  def __init__(self):
    self.children: dict[str, TrieNode] = {}
    self.isWord = False


class Trie:
  def __init__(self):
    self.root = TrieNode()

  def insert(self, word: str) -> None:
    node: TrieNode = self.root
    for c in word:
      node = node.children.setdefault(c, TrieNode())
    node.isWord = True

  def search(self, word: str, l: int, r: int) -> bool:
    node: TrieNode = self.root
    for i in range(l, r):
      if word[i] not in node.children:
        return False
      node = node.children[word[i]]
    return node.isWord


class Solution:
  def longestValidSubstring(self, word: str, forbidden: list[str]) -> int:
    ans = 0
    trie = Trie()

    for s in forbidden:
      trie.insert(s)

    # r is the rightmost index to make word[l..r] a valid substring.
    r = len(word) - 1
    for l in range(len(word) - 1, -1, -1):
      for end in range(l, min(l + 10, r + 1)):
        if trie.search(word, l, end + 1):
          r = end - 1
          break
      ans = max(ans, r - l + 1)

    return ans