Skip to content

Commit

Permalink
Update 04. Number of Distinct Substrings in a String.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb authored Jul 9, 2022
1 parent 69b63ec commit 22c219a
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions 10_Trie/04. Number of Distinct Substrings in a String.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
# https://www.codingninjas.com/codestudio/problems/count-distinct-substrings_985292
# https://youtu.be/RV0QeTyHZxo

class TrieNode:
def __init__(self):
self.children = {}

def countDistinctSubstrings(s):
root = TrieNode()
res = 0
for i in range(len(s)):
cur = root
for j in range(i, len(s)):
if s[j] not in cur.children:
cur.children[s[j]] = TrieNode()
res += 1
cur = cur.children[s[j]]
return res + 1

'''
class TrieNode:
def __init__(self):
self.children = {}
Expand All @@ -21,9 +39,9 @@ def solve(self, s):
def countDistinctSubstrings(s):
trie = Trie()
return trie.solve(s)

'''

# Time: O(N^2)
# Space: It is hard to predict spcace taken tries. It depends on the distinct elements of s. But as we are using only necessary keys in trie hashmap not all 26 keys so at max space can be N^2
# Space: in worst case O(N^2)


0 comments on commit 22c219a

Please sign in to comment.