Skip to content

Commit 4ee42d6

Browse files
committed
Added problem.
1 parent bb9673f commit 4ee42d6

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Assessments/special-strings.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
2+
# SPECIAL STRINGS
3+
4+
# O(N * M) time and O(N * M) space
5+
def specialStrings(strings):
6+
# Write your code here.
7+
trie = Trie()
8+
for string in strings:
9+
trie.buildTrie(string)
10+
11+
specials = []
12+
for string in strings:
13+
if checkSpecial(string, trie.root, 0, 0, trie):
14+
specials.append(string)
15+
16+
return specials
17+
18+
def checkSpecial(string, node, index, count, trie):
19+
letter = string[index]
20+
if letter not in node:
21+
return False
22+
23+
if index == len(string) - 1:
24+
return trie.endSymbol in node[letter] and count > 0
25+
26+
if trie.endSymbol in node[letter]:
27+
remainingSpecial = checkSpecial(string, trie.root, index + 1, count + 1, trie)
28+
if remainingSpecial:
29+
return True
30+
31+
return checkSpecial(string, node[letter], index + 1, count, trie)
32+
33+
class Trie:
34+
def __init__(self):
35+
self.root = {}
36+
self.endSymbol = "*"
37+
38+
def buildTrie(self, string):
39+
current = self.root
40+
for letter in string:
41+
if letter not in current:
42+
current[letter] = {}
43+
current = current[letter]
44+
current[self.endSymbol] = True

0 commit comments

Comments
 (0)