Skip to content

1408. String Matching in an Array 👍

Approach 1: Brute Force

  • Time: $O(|\texttt{words}|^2|\texttt{words[i]}|)$
  • Space: $O(|\texttt{words}|^2|\texttt{words[i]}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  vector<string> stringMatching(vector<string>& words) {
    vector<string> ans;
    for (const string& a : words)
      for (const string& b : words)
        if (a.length() < b.length() && b.find(a) != string::npos) {
          ans.push_back(a);
          break;
        }
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public List<String> stringMatching(String[] words) {
    List<String> ans = new ArrayList<>();
    for (final String a : words)
      for (final String b : words)
        if (a.length() < b.length() && b.indexOf(a) != -1) {
          ans.add(a);
          break;
        }
    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def stringMatching(self, words: list[str]) -> list[str]:
    ans = []
    for a in words:
      for b in words:
        if len(a) < len(b) and b.find(a) != -1:
          ans.append(a)
          break
    return ans

Approach 2: Trie w/ sort

  • Time: $O(|\texttt{words}||\texttt{words[i]}|^2)$
  • Space: $O(|\texttt{words}||\texttt{words[i]}|^2)$
 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
struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  TrieNode() : children(26) {}
};

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

  bool search(const string& word) {
    shared_ptr<TrieNode> node = root;
    for (const char c : word) {
      const int i = c - 'a';
      if (node->children[i] == nullptr)
        return false;
      node = node->children[i];
    }
    return true;
  }

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

class Solution {
 public:
  vector<string> stringMatching(vector<string>& words) {
    vector<string> ans;
    Trie trie;

    ranges::sort(words, ranges::greater{},
                 [](const string& word) { return word.length(); });

    for (const string& word : words) {
      if (trie.search(word))
        ans.push_back(word);
      for (int i = 0; i < word.length(); ++i)
        trie.insert(word.substr(i));
    }

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

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];
    }
  }

  public boolean search(String word) {
    TrieNode node = root;
    for (final char c : word.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        return false;
      node = node.children[i];
    }
    return true;
  }

  private TrieNode root = new TrieNode();
}

class Solution {
  public List<String> stringMatching(String[] words) {
    List<String> ans = new ArrayList<>();
    Trie trie = new Trie();

    Arrays.sort(words, (a, b) -> Integer.compare(b.length(), a.length()));

    for (final String word : words) {
      if (trie.search(word))
        ans.add(word);
      for (int i = 0; i < word.length(); ++i)
        trie.insert(word.substring(i));
    }

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


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())

  def search(self, word: str) -> bool:
    node: TrieNode = self.root
    for c in word:
      if c not in node.children:
        return False
      node = node.children[c]
    return True


class Solution:
  def stringMatching(self, words: list[str]) -> list[str]:
    ans = []
    trie = Trie()

    for word in sorted(words, key=lambda x: -len(x)):
      if trie.search(word):
        ans.append(word)
      for i in range(len(word)):
        trie.insert(word[i:])

    return ans

Approach 3: Trie w/o sort

  • Time: $O(|\texttt{words}||\texttt{words[i]}|^2)$
  • Space: $O(|\texttt{words}||\texttt{words[i]}|^2)$
 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
struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  int count = 0;
  TrieNode() : children(26) {}
};

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

  bool search(const string& word) {
    shared_ptr<TrieNode> node = root;
    for (const char c : word) {
      const int i = c - 'a';
      if (node->children[i] == nullptr)
        return false;
      node = node->children[i];
    }
    return node->count > 1;
  }

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

class Solution {
 public:
  vector<string> stringMatching(vector<string>& words) {
    vector<string> ans;
    Trie trie;

    for (const string& word : words)
      for (int i = 0; i < word.length(); ++i)
        trie.insert(word.substr(i));

    for (const string& word : words)
      if (trie.search(word))
        ans.push_back(word);

    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
class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public int count = 0;
}

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.count;
    }
  }

  public boolean search(String word) {
    TrieNode node = root;
    for (final char c : word.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        return false;
      node = node.children[i];
    }
    return node.count > 1;
  }

  private TrieNode root = new TrieNode();
}

class Solution {
  public List<String> stringMatching(String[] words) {
    List<String> ans = new ArrayList<>();
    Trie trie = new Trie();

    for (final String word : words)
      for (int i = 0; i < word.length(); ++i)
        trie.insert(word.substring(i));

    for (final String word : words)
      if (trie.search(word))
        ans.add(word);

    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
class TrieNode:
  def __init__(self):
    self.children: dict[str, TrieNode] = {}
    self.count = 0


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.count += 1

  def search(self, word: str) -> bool:
    node: TrieNode = self.root
    for c in word:
      if c not in node.children:
        return False
      node = node.children[c]
    return node.count > 1


class Solution:
  def stringMatching(self, words: list[str]) -> list[str]:
    trie = Trie()

    for word in words:
      for i in range(len(word)):
        trie.insert(word[i:])

    return [word for word in words if trie.search(word)]