Python Program To Find Length Of The Longest Substring Without Repeating Characters
Last Updated :
20 Dec, 2021
Given a string str, find the length of the longest substring without repeating characters.
- For “ABDEFGABEF”, the longest substring are “BDEFGA” and “DEFGAB”, with length 6.
- For “BBBB” the longest substring is “B”, with length 1.
- For “GEEKSFORGEEKS”, there are two longest substrings shown in the below diagrams, with length 7
The desired time complexity is O(n) where n is the length of the string.
Method 1 (Simple : O(n3)): We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substring contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3).
Python3
def areDistinct(strr, i, j):
visited = [ 0 ] * ( 26 )
for k in range (i, j + 1 ):
if (visited[ ord (strr[k]) -
ord ( 'a' )] = = True ):
return False
visited[ ord (strr[k]) -
ord ( 'a' )] = True
return True
def longestUniqueSubsttr(strr):
n = len (strr)
res = 0
for i in range (n):
for j in range (i, n):
if (areDistinct(strr, i, j)):
res = max (res, j - i + 1 )
return res
if __name__ = = '__main__' :
strr = "geeksforgeeks"
print ( "The input is " , strr)
len = longestUniqueSubsttr(strr)
print ( "The length of the longest "
"non-repeating character substring is " , len )
|
Output
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Method 2 (Better : O(n2)) The idea is to use window sliding. Whenever we see repetition, we remove the previous occurrence and slide the window.
Python3
def longestUniqueSubsttr( str ):
n = len ( str )
res = 0
for i in range (n):
visited = [ 0 ] * 256
for j in range (i, n):
if (visited[ ord ( str [j])] = = True ):
break
else :
res = max (res, j - i + 1 )
visited[ ord ( str [j])] = True
visited[ ord ( str [i])] = False
return res
str = "geeksforgeeks"
print ( "The input is " , str )
len = longestUniqueSubsttr( str )
print ( "The length of the longest "
"non-repeating character substring is " , len )
|
Output
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Method 4 (Linear Time): Let us talk about the linear time solution now. This solution uses extra space to store the last indexes of already visited characters. The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring seen so far in res. When we traverse the string, to know the length of current window we need two indexes.
1) Ending index ( j ) : We consider current index as ending index.
2) Starting index ( i ) : It is same as previous window if current character was not present in the previous window. To check if the current character was present in the previous window or not, we store last index of every character in an array lasIndex[]. If lastIndex[str[j]] + 1 is more than previous start, then we updated the start index i. Else we keep same i.
Below is the implementation of the above approach :
Python3
def longestUniqueSubsttr(string):
last_idx = {}
max_len = 0
start_idx = 0
for i in range ( 0 , len (string)):
if string[i] in last_idx:
start_idx = max (start_idx, last_idx[string[i]] + 1 )
max_len = max (max_len, i - start_idx + 1 )
last_idx[string[i]] = i
return max_len
string = "geeksforgeeks"
print ( "The input string is " + string)
length = longestUniqueSubsttr(string)
print ( "The length of the longest non-repeating character" +
" substring is " + str (length))
|
Output
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26.
Auxiliary Space: O(d)
Alternate Implementation :
Python
def longestUniqueSubsttr(string):
seen = {}
maximum_length = 0
start = 0
for end in range ( len (string)):
if string[end] in seen:
start = max (start, seen[string[end]] + 1 )
seen[string[end]] = end
maximum_length = max (maximum_length, end - start + 1 )
return maximum_length
string = "geeksforgeeks"
print ( "The input string is" , string)
length = longestUniqueSubsttr(string)
print ( "The length of the longest non-repeating character substring is" , length)
|
Output
The input String is geeksforgeeks
The length of the longest non-repeating character substring is 7
As an exercise, try the modified version of the above problem where you need to print the maximum length NRCS also (the above program only prints the length of it).
Please refer complete article on Length of the longest substring without repeating characters for more details!
Share your thoughts in the comments
Please Login to comment...