#3076

Shortest Uncommon Substring in an Array

Medium
ArrayHash TableStringTrieHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m), where n is the number of strings and m is the average length of the strings.
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m), where n is the number of strings and m is the average length of the strings.Space O(n * m)

By using a Trie (prefix tree), we can efficiently store and check for the existence of substrings across all strings. This allows us to quickly find the shortest uncommon substring without generating all possible substrings explicitly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build a Trie from all strings in the array to store all substrings.
  2. 2Step 2: For each string, traverse the Trie to find the shortest substring that is not present in any other string.
  3. 3Step 3: Return the results based on the findings.
solution.py38 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.count = 0
5
6class Trie:
7    def __init__(self):
8        self.root = TrieNode()
9
10    def insert(self, word):
11        node = self.root
12        for char in word:
13            if char not in node.children:
14                node.children[char] = TrieNode()
15            node = node.children[char]
16            node.count += 1
17
18    def search_shortest_uncommon(self, word):
19        node = self.root
20        shortest = ''
21        for char in word:
22            node = node.children[char]
23            if node.count == 1:
24                shortest += char
25                return shortest
26            shortest += char
27        return ''
28
29def shortestUncommonSubstring(arr):
30    trie = Trie()
31    for s in arr:
32        for i in range(len(s)):
33            trie.insert(s[i:])
34
35    answer = []
36    for s in arr:
37        answer.append(trie.search_shortest_uncommon(s))
38    return answer

Complexity note: The time complexity is O(n * m) because we insert each substring into the Trie, which can take linear time relative to the length of the string. The space complexity is also O(n * m) due to the storage of all substrings in the Trie.

  • 1Using a Trie allows efficient substring checks.
  • 2Lexicographical order can be maintained during substring checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.