Given a string str, find the length of the longest substring without repeating characters.
Example:
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


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.
C++
#include <bits/stdc++.h>
using namespace std;
bool areDistinct(string str, int i, int j)
{
vector< bool > visited(26);
for ( int k = i; k <= j; k++) {
if (visited[str[k] - 'a' ] == true )
return false ;
visited[str[k] - 'a' ] = true ;
}
return true ;
}
int longestUniqueSubsttr(string str)
{
int n = str.size();
int res = 0;
for ( int i = 0; i < n; i++)
for ( int j = i; j < n; j++)
if (areDistinct(str, i, j))
res = max(res, j - i + 1);
return res;
}
int main()
{
string str = "geeksforgeeks" ;
cout << "The input string is " << str << endl;
int len = longestUniqueSubsttr(str);
cout << "The length of the longest non-repeating "
"character substring is "
<< len;
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
int max( int num1, int num2)
{
return (num1 > num2) ? num1 : num2;
}
bool areDistinct( char str[], int i, int j)
{
bool visited[26];
for ( int i=0;i<26;i++)
visited[i]=0;
for ( int k = i; k <= j; k++) {
if (visited[str[k] - 'a' ] == true )
return false ;
visited[str[k] - 'a' ] = true ;
}
return true ;
}
int longestUniqueSubsttr( char str[])
{
int n = strlen (str);
int res = 0;
for ( int i = 0; i < n; i++)
for ( int j = i; j < n; j++)
if (areDistinct(str, i, j))
res = max(res, j - i + 1);
return res;
}
int main()
{
char str[] = "geeksforgeeks" ;
printf ( "The input string is %s \n" , str);
int len = longestUniqueSubsttr(str);
printf ( "The length of the longest non-repeating "
"character substring is %d" ,
len);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
public static Boolean areDistinct(String str,
int i, int j)
{
boolean [] visited = new boolean [ 26 ];
for ( int k = i; k <= j; k++)
{
if (visited[str.charAt(k) - 'a' ] == true )
return false ;
visited[str.charAt(k) - 'a' ] = true ;
}
return true ;
}
public static int longestUniqueSubsttr(String str)
{
int n = str.length();
int res = 0 ;
for ( int i = 0 ; i < n; i++)
for ( int j = i; j < n; j++)
if (areDistinct(str, i, j))
res = Math.max(res, j - i + 1 );
return res;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.println( "The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println( "The length of the longest " +
"non-repeating character " +
"substring is " + len);
}
}
|
Python3
def areDistinct( str , i, j):
visited = [ 0 ] * ( 26 )
for k in range (i, j + 1 ):
if (visited[ ord ( str [k]) -
ord ( 'a' )] = = True ):
return False
visited[ ord ( str [k]) -
ord ( 'a' )] = True
return True
def longestUniqueSubsttr( str ):
n = len ( str )
res = 0
for i in range (n):
for j in range (i, n):
if (areDistinct( str , i, j)):
res = max (res, j - i + 1 )
return res
if __name__ = = '__main__' :
str = "geeksforgeeks"
print ( "The input is " , str )
len = longestUniqueSubsttr( str )
print ( "The length of the longest "
"non-repeating character substring is " , len )
|
C#
using System;
class GFG{
public static bool areDistinct( string str,
int i, int j)
{
bool [] visited = new bool [26];
for ( int k = i; k <= j; k++)
{
if (visited[str[k] - 'a' ] == true )
return false ;
visited[str[k] - 'a' ] = true ;
}
return true ;
}
public static int longestUniqueSubsttr( string str)
{
int n = str.Length;
int res = 0;
for ( int i = 0; i < n; i++)
for ( int j = i; j < n; j++)
if (areDistinct(str, i, j))
res = Math.Max(res, j - i + 1);
return res;
}
public static void Main()
{
string str = "geeksforgeeks" ;
Console.WriteLine( "The input string is " + str);
int len = longestUniqueSubsttr(str);
Console.WriteLine( "The length of the longest " +
"non-repeating character " +
"substring is " + len);
}
}
|
Javascript
<script>
function areDistinct(str, i, j)
{
var visited = new [26];
for ( var k = i; k <= j; k++)
{
if (visited[str.charAt(k) - 'a' ] == true )
return false ;
visited[str.charAt(k) - 'a' ] = true ;
}
return true ;
}
function longestUniqueSubsttr(str)
{
var n = str.length();
var res = 0;
for ( var i = 0; i < n; i++)
for ( var j = i; j < n; j++)
if (areDistinct(str, i, j))
res = Math.max(res, j - i + 1);
return res;
}
var str = "geeksforgeeks" ;
document.write( "The input string is " + str);
var len = longestUniqueSubsttr(str);
document.write( "The length of the longest " +
"non-repeating character " +
"substring is " + len);
</script>
|
Output
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Time Complexity: O(n^3) since we are processing n^2 substrings with maximum length n.
Auxiliary Space: O(1)
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.
C++
#include <bits/stdc++.h>
using namespace std;
int longestUniqueSubsttr(string str)
{
int n = str.size();
int res = 0;
for ( int i = 0; i < n; i++) {
vector< bool > visited(256);
for ( int j = i; j < n; j++) {
if (visited[str[j]] == true )
break ;
else {
res = max(res, j - i + 1);
visited[str[j]] = true ;
}
}
visited[str[i]] = false ;
}
return res;
}
int main()
{
string str = "geeksforgeeks" ;
cout << "The input string is " << str << endl;
int len = longestUniqueSubsttr(str);
cout << "The length of the longest non-repeating "
"character substring is "
<< len;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
public static int longestUniqueSubsttr(String str)
{
int n = str.length();
int res = 0 ;
for ( int i = 0 ; i < n; i++)
{
boolean [] visited = new boolean [ 256 ];
for ( int j = i; j < n; j++)
{
if (visited[str.charAt(j)] == true )
break ;
else
{
res = Math.max(res, j - i + 1 );
visited[str.charAt(j)] = true ;
}
}
visited[str.charAt(i)] = false ;
}
return res;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.println( "The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println( "The length of the longest " +
"non-repeating character " +
"substring is " + len);
}
}
|
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 )
|
C#
using System;
class GFG{
static int longestUniqueSubsttr( string str)
{
int n = str.Length;
int res = 0;
for ( int i = 0; i < n; i++)
{
bool [] visited = new bool [256];
for ( int j = i; j < n; j++)
{
if (visited[str[j]] == true )
break ;
else
{
res = Math.Max(res, j - i + 1);
visited[str[j]] = true ;
}
}
visited[str[i]] = false ;
}
return res;
}
static void Main()
{
string str = "geeksforgeeks" ;
Console.WriteLine( "The input string is " + str);
int len = longestUniqueSubsttr(str);
Console.WriteLine( "The length of the longest " +
"non-repeating character " +
"substring is " + len );
}
}
|
Javascript
<script>
function longestUniqueSubsttr(str)
{
var n = str.length;
var res = 0;
for ( var i = 0; i < n; i++)
{
var visited = new Array(256);
for ( var j = i; j < n; j++)
{
if (visited[str.charCodeAt(j)] == true )
break ;
else
{
res = Math.max(res, j - i + 1);
visited[str.charCodeAt(j)] = true ;
}
}
}
return res;
}
var str = "geeksforgeeks" ;
document.write( "The input string is " + str);
var len = longestUniqueSubsttr(str);
document.write( "The length of the longest " +
"non-repeating character " +
"substring is " + len);
</script>
|
Output
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Time Complexity: O(n^2) since we are traversing each window to remove all repetitions.
Auxiliary Space: O(1)
Method 3 ( Linear Time ): Using this solution the problem can be solved in linear time using the window sliding technique. Whenever we see repetition, we remove the window till the repeated string.
C++
#include <iostream>
#include <string>
using namespace std;
int longestUniqueSubsttr(string str)
{
if (str.length() == 0)
return 0;
if (str.length() == 1)
return 1;
int maxLength = 0;
bool visited[256] = { false };
int left = 0, right = 0;
for (; right < str.length(); right++) {
if (visited[str[right]] == false )
visited[str[right]] = true ;
else {
maxLength = max(maxLength, (right - left));
while (left < right) {
if (str[left] != str[right])
visited[str[left]] = false ;
else {
left++;
break ;
}
left++;
}
}
}
maxLength = max(maxLength, (right - left));
return maxLength;
}
int main()
{
string s = "GeeksForGeeks!" ;
cout << longestUniqueSubsttr(s) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int longestUniqueSubsttr(String str)
{
String test = "" ;
int maxLength = - 1 ;
if (str.isEmpty()) {
return 0 ;
}
else if (str.length() == 1 ) {
return 1 ;
}
for ( char c : str.toCharArray()) {
String current = String.valueOf(c);
if (test.contains(current)) {
test = test.substring(test.indexOf(current)
+ 1 );
}
test = test + String.valueOf(c);
maxLength = Math.max(test.length(), maxLength);
}
return maxLength;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.println( "The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println( "The length of the longest "
+ "non-repeating character "
+ "substring is " + len);
}
}
|
Python3
import math
def longestUniqueSubsttr( str ):
test = ""
maxLength = - 1
if ( len ( str ) = = 0 ):
return 0
elif ( len ( str ) = = 1 ):
return 1
for c in list ( str ):
current = "".join(c)
if (current in test):
test = test[test.index(current) + 1 :]
test = test + "".join(c)
maxLength = max ( len (test), maxLength)
return maxLength
string = "geeksforgeeks"
print ( "The input string is" , string)
length = longestUniqueSubsttr(string)
print ( "The length of the longest non-repeating character substring is" , length)
|
C#
using System;
public class GFG
{
public static int longestUniqueSubsttr(String str)
{
var test = "" ;
var maxLength = -1;
if (str.Length == 0)
{
return 0;
}
else if (str.Length == 1)
{
return 1;
}
foreach ( char c in str.ToCharArray())
{
var current = c+ "" ;
if (test.Contains(current))
{
test = test.Substring(test.IndexOf(current) + 1);
}
test = test + c;
maxLength = Math.Max(test.Length,maxLength);
}
return maxLength;
}
public static void Main(String[] args)
{
var str = "geeksforgeeks" ;
Console.WriteLine( "The input string is " + str);
var len = GFG.longestUniqueSubsttr(str);
Console.WriteLine( "The length of the longest " + "non-repeating character " + "substring is " + len.ToString());
}
}
|
Javascript
function longestUniqueSubsttr( str)
{
if (str.length == 0)
return 0;
if (str.length == 1)
return 1;
let maxLength = 0;
let visited=[];
for (let i=0;i<256;i++)
visited.push( false );
let left = 0, right = 0;
for (; right < str.length; right++) {
if (visited[str.charCodeAt(right)] == false )
visited[str.charCodeAt(right)] = true ;
else {
maxLength = Math.max(maxLength, (right - left));
while (left < right) {
if (str.charCodeAt(left) != str.charCodeAt(right))
visited[str.charCodeAt(left)] = false ;
else {
left++;
break ;
}
left++;
}
}
}
maxLength = Math.max(maxLength, (right - left));
return maxLength;
}
let s = "GeeksForGeeks!" ;
console.log(longestUniqueSubsttr(s));
|
Time Complexity: O(n) since we slide the window whenever we see any repetitions.
Auxiliary Space: O(1)
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 :
C++
#include <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
int longestUniqueSubsttr(string str)
{
int n = str.size();
int res = 0;
vector< int > lastIndex(NO_OF_CHARS, -1);
int i = 0;
for ( int j = 0; j < n; j++) {
i = max(i, lastIndex[str[j]] + 1);
res = max(res, j - i + 1);
lastIndex[str[j]] = j;
}
return res;
}
int main()
{
string str = "geeksforgeeks" ;
cout << "The input string is " << str << endl;
int len = longestUniqueSubsttr(str);
cout << "The length of the longest non-repeating "
"character substring is "
<< len;
return 0;
}
|
Java
import java.util.*;
public class GFG {
static final int NO_OF_CHARS = 256 ;
static int longestUniqueSubsttr(String str)
{
int n = str.length();
int res = 0 ;
int [] lastIndex = new int [NO_OF_CHARS];
Arrays.fill(lastIndex, - 1 );
int i = 0 ;
for ( int j = 0 ; j < n; j++) {
i = Math.max(i, lastIndex[str.charAt(j)] + 1 );
res = Math.max(res, j - i + 1 );
lastIndex[str.charAt(j)] = j;
}
return res;
}
public static void main(String[] args)
{
String str = "geeksforgeeks" ;
System.out.println( "The input string is " + str);
int len = longestUniqueSubsttr(str);
System.out.println( "The length of "
+ "the longest non repeating character is " + len);
}
}
|
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))
|
C#
using System;
public class GFG
{
static int NO_OF_CHARS = 256;
static int longestUniqueSubsttr( string str)
{
int n = str.Length;
int res = 0;
int [] lastIndex = new int [NO_OF_CHARS];
Array.Fill(lastIndex, -1);
int i = 0;
for ( int j = 0; j < n; j++)
{
i = Math.Max(i, lastIndex[str[j]] + 1);
res = Math.Max(res, j - i + 1);
lastIndex[str[j]] = j;
}
return res;
}
static public void Main ()
{
string str = "geeksforgeeks" ;
Console.WriteLine( "The input string is " + str);
int len = longestUniqueSubsttr(str);
Console.WriteLine( "The length of " +
"the longest non repeating character is " +
len);
}
}
|
Javascript
<script>
var NO_OF_CHARS = 256;
function longestUniqueSubsttr(str)
{
var n = str.length();
var res = 0;
var lastIndex = new [NO_OF_CHARS];
Arrays.fill(lastIndex, -1);
var i = 0;
for ( var j = 0; j < n; j++) {
i = Math.max(i, lastIndex[str.charAt(j)] + 1);
res = Math.max(res, j - i + 1);
lastIndex[str.charAt(j)] = j;
}
return res;
}
var str = "geeksforgeeks" ;
document.write( "The input string is " + str);
var len = longestUniqueSubsttr(str);
document.write( "The length of the longest non repeating character is " + len);
</script>
|
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 :
C++
#include <bits/stdc++.h>
using namespace std;
int longestUniqueSubsttr(string s)
{
map< char , int > seen ;
int maximum_length = 0;
int start = 0;
for ( int end = 0; end < s.length(); end++)
{
if (seen.find(s[end]) != seen.end())
{
start = max(start, seen[s[end]] + 1);
}
seen[s[end]] = end;
maximum_length = max(maximum_length,
end - start + 1);
}
return maximum_length;
}
int main()
{
string s = "geeksforgeeks" ;
cout << "The input String is " << s << endl;
int length = longestUniqueSubsttr(s);
cout<< "The length of the longest non-repeating character "
<< "substring is "
<< length;
}
|
Java
import java.util.*;
class GFG {
static int longestUniqueSubsttr(String s)
{
HashMap<Character, Integer> seen = new HashMap<>();
int maximum_length = 0 ;
int start = 0 ;
for ( int end = 0 ; end < s.length(); end++)
{
if (seen.containsKey(s.charAt(end)))
{
start = Math.max(start, seen.get(s.charAt(end)) + 1 );
}
seen.put(s.charAt(end), end);
maximum_length = Math.max(maximum_length, end-start + 1 );
}
return maximum_length;
}
public static void main(String []args)
{
String s = "geeksforgeeks" ;
System.out.println( "The input String is " + s);
int length = longestUniqueSubsttr(s);
System.out.println( "The length of the longest non-repeating character substring is " + length);
}
}
|
Python3
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)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int longestUniqueSubsttr( string s)
{
Dictionary< char , int > seen = new Dictionary< char , int >();
int maximum_length = 0;
int start = 0;
for ( int end = 0; end < s.Length; end++)
{
if (seen.ContainsKey(s[end]))
{
start = Math.Max(start, seen[s[end]] + 1);
}
seen[s[end]] = end;
maximum_length = Math.Max(maximum_length, end-start + 1);
}
return maximum_length;
}
static void Main() {
string s = "geeksforgeeks" ;
Console.WriteLine( "The input string is " + s);
int length = longestUniqueSubsttr(s);
Console.WriteLine( "The length of the longest non-repeating character substring is " + length);
}
}
|
Javascript
<script>
function longestUniqueSubsttr(s)
{
let seen = new Map();
let maximum_length = 0;
let start = 0;
for (let end = 0; end < s.length; end++)
{
if (seen.has(s[end]))
{
start = Math.max(start, seen.get(s[end]) + 1);
}
seen.set(s[end],end)
maximum_length = Math.max(maximum_length, end - start + 1);
}
return maximum_length;
}
let s = "geeksforgeeks"
document.write(`The input String is ${s}`)
let length = longestUniqueSubsttr(s);
document.write(`The length of the longest non-repeating character substring is ${length}`)
</script>
|
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)
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).
Method 5 (Linear time): In this method we will apply KMP Algorithm technique, to solve the problem. We maintain an Unordered Set to keep track of the maximum non repeating char sub string (Instead of standard LPS array of KMP). When ever we find a repeating char, then we clear the Set and reset len to zero. Rest everything is almost similar to KMP.
C++
#include <bits/stdc++.h>
using namespace std;
int longestSubstrDistinctChars(string s)
{
if (s.length() == 0)
return 0;
int n = s.length();
set< char > st;
int len = 1;
st.insert(s[0]);
int i = 1;
int maxLen = 0;
while (i < n)
{
if (s[i] != s[i - 1] && st.find(s[i]) == st.end())
{
st.insert(s[i]);
len++;
i++;
if (len > maxLen)
{
maxLen = len;
}
}
else
{
if (len == 1)
{
i++;
}
else
{
st.clear();
i = i - len + 1;
len = 0;
}
}
}
return max(maxLen, len);
}
int main()
{
string str = "abcabcbb" ;
cout << "The input string is " << str << endl;
int len = longestSubstrDistinctChars(str);
cout << "The length of the longest non-repeating character substring " << len;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int longestSubstrDistinctChars(String s)
{
if (s.length() == 0 ) {
return 0 ;
}
int n = s.length();
HashSet<Character> st = new HashSet<Character>();
int len = 1 ;
st.add(s.charAt( 0 ));
int i = 1 ;
int maxLen = 0 ;
while (i < n) {
if (s.charAt(i) != s.charAt(i - 1 )
&& !st.contains(s.charAt(i))) {
st.add(s.charAt(i));
len++;
i++;
if (len > maxLen) {
maxLen = len;
}
}
else {
if (len == 1 ) {
i++;
}
else {
st.clear();
i = i - len + 1 ;
len = 0 ;
}
}
}
return Math.max(maxLen, len);
}
public static void main(String[] args)
{
String str = "abcabcbb" ;
System.out.println( "The input string is " + str);
int len = longestSubstrDistinctChars(str);
System.out.println(
"The length of the longest non-repeating character substring "
+ len);
}
}
|
Python3
def longestSubstrDistinctChars(s):
if len (s) = = 0 :
return 0
n = len (s)
st = set ()
leng = 1
st.add(s[ 0 ])
i = 1
maxLen = 0
while i < n:
if s[i] ! = s[i - 1 ] and s[i] not in st:
st.add(s[i])
leng + = 1
i + = 1
if leng > maxLen:
maxLen = leng
else :
if leng = = 1 :
i + = 1
else :
st.clear()
i = i - leng + 1
leng = 0
return max (maxLen, leng)
if __name__ = = '__main__' :
string = "abcabcbb"
print ( "The input string is " + string)
leng = longestSubstrDistinctChars(string)
print ( "The length of the longest non-repeating character substring " + str (leng))
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
static int longestSubstrDistinctChars( string s)
{
if (s.Length == 0)
return 0;
int n = s.Length;
HashSet< char > st= new HashSet< char >();
int len = 1;
st.Add(s[0]);
int i = 1;
int maxLen = 0;
while (i < n)
{
if (s[i] != s[i - 1] && !st.Contains(s[i]))
{
st.Add(s[i]);
len++;
i++;
if (len > maxLen)
{
maxLen = len;
}
}
else
{
if (len == 1)
{
i++;
}
else
{
st.Clear();
i = i - len + 1;
len = 0;
}
}
}
return Math.Max(maxLen, len);
}
public static void Main ( string [] args)
{
string str = "abcabcbb" ;
Console.WriteLine( "The input string is " + str);
int len = longestSubstrDistinctChars(str);
Console.WriteLine( "The length of the longest non-repeating character substring " + len);
}
}
|
Javascript
<script>
function longestSubstrDistinctChars(s) {
if (s.length === 0)
return 0;
const n = s.length;
const st = new Set();
let len = 1;
st.add(s[0]);
let i =1;
let maxLen = 0;
while (i<n){
if (s[i]!==s[i-1] && !st.has(s[i])){
st.add(s[i]);
len++;
i++;
if (len>maxLen){
maxLen = len;
}
} else {
if (len ===1) {i++;}
else {
st.clear();
i=i-len+1;
len = 0;
}
}
}
return maxLen || len;
}
var str = "abcabcbb" ;
document.write( "The input string is " + str);
var len = longestSubstrDistinctChars(str);
document.write( "The length of the longest non-repeating character substring " + len);
</script>
|
Output
The input string is abcabcbb
The length of the longest non-repeating character substring 3
Time Complexity : O(n) where n is the input string length
Auxiliary Space: O(m) where m is the length of the resultant sub string
Please Login to comment...