# Program to find out number of distinct substrings in a given string in python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose, we are given a substring denoted by 's'. We have to find out the unique substrings and return the number of these substrings as output.

So, if the input is like s = 'prrstvt', then the output will be 26.

The distinct substrings will be −

'pr', 'rrs', 'st', 'rr', 'tv', 'rstv', 'stvt', 'prrstv', 'prrstvt', 'rrstvt', 's', 'prrst', 'stv', 'rrstv', 'rst', 'v', 'tvt', 'rstvt', 'r', 'rs', 'vt', 't', 'prr', 'p', 'rrst', and 'prrs'.

To solve this, we will follow these steps −

• visited := a new map
• for each index ind, and value let in s, do
• temp := a new set
• if ind-1 is present in visited, then
• for each has_let in visited[ind-1], do
• add(has_let + let) to list temp
• add(let) to list temp
• visited[ind] := temp
• res := a new set
• for each sets in visited, do
• add(visited[sets]) to res
• return size of res

## Example

Let us see the following implementation to get better understanding −

def solve(s):
visited = dict()
for ind, let in enumerate(s):
temp = set()
if ind-1 in visited:
for has_let in visited[ind-1]:
visited[ind] = temp
res = set()
for sets in visited:
res.update(visited[sets])
return len(res)

print(solve('prrstvt'))

## Input

'prrstvt'

## Output

26