 GFG App
Open App Browser
Continue

# Length of the longest substring without repeating characters

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++

 `// C++ program to find the length of the longest substring` `// without repeating characters` `#include ` `using` `namespace` `std;`   `// This function returns true if all characters in str[i..j]` `// are distinct, otherwise returns false` `bool` `areDistinct(string str, ``int` `i, ``int` `j)` `{`   `    ``// Note : Default values in visited are false` `    ``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``;` `}`   `// Returns length of the longest substring` `// with all distinct characters.` `int` `longestUniqueSubsttr(string str)` `{` `    ``int` `n = str.size();` `    ``int` `res = 0; ``// result` `    ``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;` `}`   `// Driver code` `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;` `}`   `// This code is contributed by Sania Kumari Gupta (kriSania804)`

## C

 `// C program to find the length of the longest substring` `// without repeating characters` `#include ` `#include ` `#include `   `// Find maximum between two numbers.` `int` `max(``int` `num1, ``int` `num2)` `{` `    ``return` `(num1 > num2) ? num1 : num2;` `}`   `// This function returns true if all characters in str[i..j]` `// are distinct, otherwise returns false` `bool` `areDistinct(``char` `str[], ``int` `i, ``int` `j)` `{`   `    ``// Note : Default values in visited are false` `    ``bool` `visited;` `      ``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``;` `}`   `// Returns length of the longest substring` `// with all distinct characters.` `int` `longestUniqueSubsttr(``char` `str[])` `{` `    ``int` `n = ``strlen``(str);` `    ``int` `res = 0; ``// result` `    ``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;` `}`   `// Driver code` `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;` `}`   `// This code is contributed by Sania Kumari Gupta (kriSania804)`

## Java

 `// Java program to find the length of the` `// longest substring without repeating` `// characters` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG{`   `// This function returns true if all characters in` `// str[i..j] are distinct, otherwise returns false` `public` `static` `Boolean areDistinct(String str, ` `                                  ``int` `i, ``int` `j)` `{` `    `  `    ``// Note : Default values in visited are false` `    ``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``;` `}`   `// Returns length of the longest substring` `// with all distinct characters.` `public` `static` `int` `longestUniqueSubsttr(String str)` `{` `    ``int` `n = str.length();` `    `  `    ``// Result` `    ``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;` `}`   `// Driver code` `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);` `}` `}`   `// This code is contributed by akhilsaini`

## Python3

 `# Python3 program to find the length` `# of the longest substring without` `# repeating characters`   `# This function returns true if all` `# characters in str[i..j] are ` `# distinct, otherwise returns false` `def` `areDistinct(``str``, i, j):`   `    ``# Note : Default values in visited are false` `    ``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`   `# Returns length of the longest substring` `# with all distinct characters.` `def` `longestUniqueSubsttr(``str``):` `    `  `    ``n ``=` `len``(``str``)` `    `  `    ``# Result` `    ``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`   `# Driver code` `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``)`   `# This code is contributed by mohit kumar 29`

## C#

 `// C# program to find the length of the ` `// longest substring without repeating ` `// characters ` `using` `System;` ` `  `class` `GFG{` ` `  `// This function returns true if all characters in` `// str[i..j] are distinct, otherwise returns false` `public` `static` `bool` `areDistinct(``string` `str, ` `                               ``int` `i, ``int` `j)` `{` `    `  `    ``// Note : Default values in visited are false` `    ``bool``[] visited = ``new` `bool``;` ` `  `    ``for``(``int` `k = i; k <= j; k++)` `    ``{` `        ``if` `(visited[str[k] - ``'a'``] == ``true``)` `            ``return` `false``;` `             `  `        ``visited[str[k] - ``'a'``] = ``true``;` `    ``}` `    ``return` `true``;` `}` ` `  `// Returns length of the longest substring` `// with all distinct characters.` `public` `static` `int` `longestUniqueSubsttr(``string` `str)` `{` `    ``int` `n = str.Length;` `     `  `    ``// Result` `    ``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;` `}` ` `  `// Driver code` `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);` `}` `}`   `// This code is contributed by sanjoy_62`

## Javascript

 ``

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++

 `// C++ program to find the length of the longest substring` `// without repeating characters` `#include ` `using` `namespace` `std;`   `int` `longestUniqueSubsttr(string str)` `{` `    ``int` `n = str.size();` `    ``int` `res = 0; ``// result`   `    ``for` `(``int` `i = 0; i < n; i++) {` `        `  `        ``// Note : Default values in visited are false` `        ``vector<``bool``> visited(256);   `   `        ``for` `(``int` `j = i; j < n; j++) {`   `            ``// If current character is visited` `            ``// Break the loop` `            ``if` `(visited[str[j]] == ``true``)` `                ``break``;`   `            ``// Else update the result if` `            ``// this window is larger, and mark` `            ``// current character as visited.` `            ``else` `{` `                ``res = max(res, j - i + 1);` `                ``visited[str[j]] = ``true``;` `            ``}` `        ``}`   `        ``// Remove the first character of previous` `        ``// window` `        ``visited[str[i]] = ``false``;` `    ``}` `    ``return` `res;` `}`   `// Driver code` `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

 `// Java program to find the length of the ` `// longest substring without repeating` `// characters` `import` `java.io.*;` `import` `java.util.*;`   `class` `GFG{`   `public` `static` `int` `longestUniqueSubsttr(String str)` `{` `    ``int` `n = str.length();` `    `  `    ``// Result` `    ``int` `res = ``0``;` `    `  `    ``for``(``int` `i = ``0``; i < n; i++)` `    ``{` `        `  `        ``// Note : Default values in visited are false` `        ``boolean``[] visited = ``new` `boolean``[``256``];` `        `  `        ``for``(``int` `j = i; j < n; j++)` `        ``{` `            `  `            ``// If current character is visited` `            ``// Break the loop` `            ``if` `(visited[str.charAt(j)] == ``true``)` `                ``break``;`   `            ``// Else update the result if` `            ``// this window is larger, and mark` `            ``// current character as visited.` `            ``else` `            ``{` `                ``res = Math.max(res, j - i + ``1``);` `                ``visited[str.charAt(j)] = ``true``;` `            ``}` `        ``}`   `        ``// Remove the first character of previous` `        ``// window` `        ``visited[str.charAt(i)] = ``false``;` `    ``}` `    ``return` `res;` `}`   `// Driver code` `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);` `}` `}`   `// This code is contributed by akhilsaini`

## Python3

 `# Python3 program to find the ` `# length of the longest substring` `# without repeating characters` `def` `longestUniqueSubsttr(``str``):` `    `  `    ``n ``=` `len``(``str``)` `    `  `    ``# Result` `    ``res ``=` `0` ` `  `    ``for` `i ``in` `range``(n):` `         `  `        ``# Note : Default values in ` `        ``# visited are false` `        ``visited ``=` `[``0``] ``*` `256`   ` `  `        ``for` `j ``in` `range``(i, n):` ` `  `            ``# If current character is visited` `            ``# Break the loop` `            ``if` `(visited[``ord``(``str``[j])] ``=``=` `True``):` `                ``break` ` `  `            ``# Else update the result if` `            ``# this window is larger, and mark` `            ``# current character as visited.` `            ``else``:` `                ``res ``=` `max``(res, j ``-` `i ``+` `1``)` `                ``visited[``ord``(``str``[j])] ``=` `True` `            `  `        ``# Remove the first character of previous` `        ``# window` `        ``visited[``ord``(``str``[i])] ``=` `False` `    `  `    ``return` `res`   `# Driver code` `str` `=` `"geeksforgeeks"` `print``(``"The input is "``, ``str``)`   `len` `=` `longestUniqueSubsttr(``str``)` `print``(``"The length of the longest "` `      ``"non-repeating character substring is "``, ``len``)`   `# This code is contributed by sanjoy_62`

## C#

 `// C# program to find the length of the ` `// longest substring without repeating` `// characters ` `using` `System;`   `class` `GFG{` `    `  `static` `int` `longestUniqueSubsttr(``string` `str) ` `{ ` `    ``int` `n = str.Length; ` `    `  `    ``// Result ` `    ``int` `res = 0; ` `  `  `    ``for``(``int` `i = 0; i < n; i++)` `    ``{ ` `        `  `        ``// Note : Default values in visited are false ` `        ``bool``[] visited = ``new` `bool``; ` `        `  `        ``// visited = visited.Select(i => false).ToArray();` `        ``for``(``int` `j = i; j < n; j++)` `        ``{ ` `            `  `            ``// If current character is visited ` `            ``// Break the loop ` `            ``if` `(visited[str[j]] == ``true``) ` `                ``break``; ` `  `  `            ``// Else update the result if ` `            ``// this window is larger, and mark ` `            ``// current character as visited. ` `            ``else` `            ``{ ` `                ``res = Math.Max(res, j - i + 1); ` `                ``visited[str[j]] = ``true``; ` `            ``} ` `        ``} ` `        `  `        ``// Remove the first character of previous ` `        ``// window ` `        ``visited[str[i]] = ``false``; ` `    ``} ` `    ``return` `res; ` `} `   `// Driver code` `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 );` `}` `}`   `// This code is contributed by divyeshrabadiya07`

## Javascript

 ``

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 ` `#include ` `using` `namespace` `std;`   `int` `longestUniqueSubsttr(string str)` `{` `    ``// if string length is 0` `    ``if` `(str.length() == 0)` `        ``return` `0;`   `    ``// if string length 1` `    ``if` `(str.length() == 1)` `        ``return` `1;`   `    ``// if string length is more than 2` `    ``int` `maxLength = 0;` `    ``bool` `visited = { ``false` `};`   `    ``// left and right pointer of sliding window` `    ``int` `left = 0, right = 0;` `    ``for` `(; right < str.length(); right++) {`   `        ``// if character is not visited then mark visited` `        ``if` `(visited[str[right]] == ``false``)` `            ``visited[str[right]] = ``true``;`   `        ``// if character is visited` `        ``else` `{` `            ``/*    capture the unique string from [left ,` `               ``right). Not including right since repeating` `               ``character is at index right.` `            ``*/` `            ``maxLength = max(maxLength, (right - left));`   `            ``/*    Mark all characters until repeating` `                ``character as unvisited but not the repeating` `                ``character as it is in the new unique string.` `                ``However move window past the repeating` `                ``character.` `            ``*/` `            ``while` `(left < right) {` `                ``if` `(str[left] != str[right])` `                    ``visited[str[left]] = ``false``;` `                ``else` `{` `                    ``left++;` `                    ``break``;` `                ``}` `                ``left++;` `            ``}` `        ``}` `    ``}`   `    ``// compare current left,right with previous result` `    ``maxLength = max(maxLength, (right - left));`   `    ``return` `maxLength;` `}`   `int` `main()` `{` `    ``string s = ``"GeeksForGeeks!"``;` `    `  `      ``cout << longestUniqueSubsttr(s) << endl;   ` `      `  `      ``//expected result : 7` `      ``//unique substring = eksForG` `  `  `    ``return` `0;` `}`

## Java

 `import` `java.io.*;`   `class` `GFG {` `    ``public` `static` `int` `longestUniqueSubsttr(String str)` `    ``{` `        ``String test = ``""``;`   `        ``// Result` `        ``int` `maxLength = -``1``;`   `        ``// Return zero if string is empty` `        ``if` `(str.isEmpty()) {` `            ``return` `0``;` `        ``}` `        ``// Return one if string length is one` `        ``else` `if` `(str.length() == ``1``) {` `            ``return` `1``;` `        ``}` `        ``for` `(``char` `c : str.toCharArray()) {` `            ``String current = String.valueOf(c);`   `            ``// If string already contains the character` `            ``// Then substring after repeating character` `            ``if` `(test.contains(current)) {` `                ``test = test.substring(test.indexOf(current)` `                                      ``+ ``1``);` `            ``}` `            ``test = test + String.valueOf(c);` `            ``maxLength = Math.max(test.length(), maxLength);` `        ``}`   `        ``return` `maxLength;` `    ``}`   `    ``// Driver code` `    ``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);` `    ``}` `}`   `// This code is contributed by Alex Bennet`

## Python3

 `import` `math`   `def` `longestUniqueSubsttr(``str``):` `    ``test ``=` `""` `    ``# Result` `    ``maxLength ``=` `-``1` `    `  `    ``# Return zero if string is empty` `    ``if` `(``len``(``str``) ``=``=` `0``):` `        ``return` `0` `    ``elif``(``len``(``str``) ``=``=` `1``):` `        ``return` `1` `    ``for` `c ``in` `list``(``str``):` `        ``current ``=` `"".join(c)` `        `  `        ``# If string already contains the character` `        ``# Then substring after repeating character` `        ``if` `(current ``in` `test):` `            ``test ``=` `test[test.index(current) ``+` `1``:]` `        ``test ``=` `test ``+` `"".join(c)` `        ``maxLength ``=` `max``(``len``(test), maxLength)` `    ``return` `maxLength`     `# Driver Code` `string ``=` `"geeksforgeeks"` `print``(``"The input string is"``, string)` `length ``=` `longestUniqueSubsttr(string)` `print``(``"The length of the longest non-repeating character substring is"``, length)`   `# This code is contributed by santeswar.`

## C#

 `// Include namespace system` `using` `System;`   `public` `class` `GFG` `{` `  ``public` `static` `int` `longestUniqueSubsttr(String str)` `  ``{` `    ``var` `test = ``""``;`   `    ``// Result` `    ``var` `maxLength = -1;`   `    ``// Return zero if string is empty` `    ``if` `(str.Length == 0)` `    ``{` `      ``return` `0;` `    ``}` `    ``else` `if` `(str.Length == 1)` `    ``{` `      ``return` `1;` `    ``}` `    ``foreach` `(``char` `c ``in` `str.ToCharArray())` `    ``{` `      ``var` `current = c+``""``;`   `      ``// If string already contains the character` `      ``// Then substring after repeating character` `      ``if` `(test.Contains(current))` `      ``{` `        ``test = test.Substring(test.IndexOf(current) + 1);` `      ``}` `      ``test = test + c;` `      ``maxLength = Math.Max(test.Length,maxLength);` `    ``}` `    ``return` `maxLength;` `  ``}`   `  ``// Driver code` `  ``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());` `  ``}` `}`   `// This code is contributed by phasing17.`

## Javascript

 `function` `longestUniqueSubsttr( str)` `{` `    ``// if string length is 0` `    ``if` `(str.length == 0)` `        ``return` `0;`   `    ``// if string length 1` `    ``if` `(str.length == 1)` `        ``return` `1;`   `    ``// if string length is more than 2` `    ``let maxLength = 0;` `    ``let visited=[];` `    ``for``(let i=0;i<256;i++)` `        ``visited.push(``false``);`   `    ``// left and right pointer of sliding window` `    ``let left = 0, right = 0;` `    ``for` `(; right < str.length; right++) {`   `        ``// if character is not visited then mark visited` `       ``if` `(visited[str.charCodeAt(right)] == ``false``)` `               ``visited[str.charCodeAt(right)] = ``true``;`   `        ``// if character is visited` `        ``else` `{` `            ``/*    capture the unique string from [left ,` `               ``right). Not including right since repeating` `               ``character is at index right.` `            ``*/` `            ``maxLength = Math.max(maxLength, (right - left));` `            `  `            ``/*    Mark all characters until repeating` `                ``character as unvisited but not the repeating` `                ``character as it is in the new unique string.` `                ``However move window past the repeating` `                ``character.` `            ``*/` `            ``while` `(left < right) {` `                ``if` `(str.charCodeAt(left) != str.charCodeAt(right))` `                    ``visited[str.charCodeAt(left)] = ``false``;` `                ``else` `{` `                    ``left++;` `                    ``break``;` `                ``}` `                ``left++;` `            ``}` `        ``}` `    ``}`   `    ``// compare current left,right with previous result` `    ``maxLength = Math.max(maxLength, (right - left));`   `    ``return` `maxLength;` `}`     `    ``let s = ``"GeeksForGeeks!"``;` `    ``console.log(longestUniqueSubsttr(s));   ` `      `  `      ``// This code is contributed by garg28harsh.`

Output

```7
```

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++

 `// C++ program to find the length of the longest substring` `// without repeating characters` `#include ` `using` `namespace` `std;` `#define NO_OF_CHARS 256`   `int` `longestUniqueSubsttr(string str)` `{` `    ``int` `n = str.size();`   `    ``int` `res = 0; ``// result`   `    ``// last index of all characters is initialized` `    ``// as -1` `    ``vector<``int``> lastIndex(NO_OF_CHARS, -1);`   `    ``// Initialize start of current window` `    ``int` `i = 0;`   `    ``// Move end of current window` `    ``for` `(``int` `j = 0; j < n; j++) {`   `        ``// Find the last index of str[j]` `        ``// Update i (starting index of current window)` `        ``// as maximum of current value of i and last` `        ``// index plus 1` `        ``i = max(i, lastIndex[str[j]] + 1);`   `        ``// Update result if we get a larger window` `        ``res = max(res, j - i + 1);`   `        ``// Update last index of j.` `        ``lastIndex[str[j]] = j;` `    ``}` `    ``return` `res;` `}`   `// Driver code` `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

 `// Java program to find the length of the longest substring` `// without repeating characters` `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``; ``// result`   `        ``// last index of all characters is initialized` `        ``// as -1` `        ``int` `[] lastIndex = ``new` `int``[NO_OF_CHARS];` `        ``Arrays.fill(lastIndex, -``1``);`   `        ``// Initialize start of current window` `        ``int` `i = ``0``;`   `        ``// Move end of current window` `        ``for` `(``int` `j = ``0``; j < n; j++) {`   `            ``// Find the last index of str[j]` `            ``// Update i (starting index of current window)` `            ``// as maximum of current value of i and last` `            ``// index plus 1` `            ``i = Math.max(i, lastIndex[str.charAt(j)] + ``1``);`   `            ``// Update result if we get a larger window` `            ``res = Math.max(res, j - i + ``1``);`   `            ``// Update last index of j.` `            ``lastIndex[str.charAt(j)] = j;` `        ``}` `        ``return` `res;` `    ``}`   `    ``/* Driver program to test above function */` `    ``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);` `    ``}` `}` `// This code is contributed by Sumit Ghosh`

## Python3

 `# Python3 program to find the length` `# of the longest substring` `# without repeating characters` `def` `longestUniqueSubsttr(string):`   `    ``# last index of every character` `    ``last_idx ``=` `{}` `    ``max_len ``=` `0`   `    ``# starting index of current ` `    ``# window to calculate max_len` `    ``start_idx ``=` `0`   `    ``for` `i ``in` `range``(``0``, ``len``(string)):` `      `  `        ``# Find the last index of str[i]` `        ``# Update start_idx (starting index of current window)` `        ``# as maximum of current value of start_idx and last` `        ``# index plus 1` `        ``if` `string[i] ``in` `last_idx:` `            ``start_idx ``=` `max``(start_idx, last_idx[string[i]] ``+` `1``)`   `        ``# Update result if we get a larger window` `        ``max_len ``=` `max``(max_len, i``-``start_idx ``+` `1``)`   `        ``# Update last index of current char.` `        ``last_idx[string[i]] ``=` `i`   `    ``return` `max_len`     `# Driver program to test the above function` `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#

 `// C# program to find the length of the longest substring ` `// without repeating characters ` `using` `System;` `public` `class` `GFG` `{` `  ``static` `int` `NO_OF_CHARS = 256; ` `  ``static` `int` `longestUniqueSubsttr(``string` `str) ` `  ``{` `    ``int` `n = str.Length; ` `    ``int` `res = 0; ``// result `   `    ``// last index of all characters is initialized ` `    ``// as -1 ` `    ``int` `[] lastIndex = ``new` `int``[NO_OF_CHARS]; ` `    ``Array.Fill(lastIndex, -1); `   `    ``// Initialize start of current window ` `    ``int` `i = 0; `   `    ``// Move end of current window ` `    ``for` `(``int` `j = 0; j < n; j++) ` `    ``{ `   `      ``// Find the last index of str[j] ` `      ``// Update i (starting index of current window) ` `      ``// as maximum of current value of i and last ` `      ``// index plus 1 ` `      ``i = Math.Max(i, lastIndex[str[j]] + 1); `   `      ``// Update result if we get a larger window ` `      ``res = Math.Max(res, j - i + 1); `   `      ``// Update last index of j. ` `      ``lastIndex[str[j]] = j; ` `    ``} ` `    ``return` `res; ` `  ``}`   `  ``/* Driver program to test above function */` `  ``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);` `  ``}` `}`   `// This code is contributed by avanitrachhadiya2155`

## Javascript

 ``

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 ` `using` `namespace` `std;`   `int` `longestUniqueSubsttr(string s)` `{` `    `  `    ``// Creating a map to store the last positions ` `    ``// of occurrence` `    ``map<``char``, ``int``> seen ;` `    ``int` `maximum_length = 0;`   `    ``// Starting the initial point of window to index 0` `    ``int` `start = 0;`   `    ``for``(``int` `end = 0; end < s.length(); end++) ` `    ``{` `        `  `        ``// Checking if we have already seen the element or` `        ``// not` `        ``if` `(seen.find(s[end]) != seen.end())` `        ``{` `            `  `            ``// If we have seen the number, move the start` `            ``// pointer to position after the last occurrence` `            ``start = max(start, seen[s[end]] + 1);` `        ``}`   `        ``// Updating the last seen value of the character` `        ``seen[s[end]] = end;` `        ``maximum_length = max(maximum_length, ` `                             ``end - start + 1);` `    ``}` `    ``return` `maximum_length;` `}`   `// Driver code` `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;` `}`   `// This code is contributed by ukasp`

## Java

 `import` `java.util.*;` `class` `GFG {`   `  ``static` `int` `longestUniqueSubsttr(String s)` `  ``{`   `    ``// Creating a set to store the last positions of occurrence` `    ``HashMap seen = ``new` `HashMap<>();  ` `    ``int` `maximum_length = ``0``;`   `    ``// starting the initial point of window to index 0` `    ``int` `start = ``0``;`   `    ``for``(``int` `end = ``0``; end < s.length(); end++)` `    ``{` `      ``// Checking if we have already seen the element or not` `      ``if``(seen.containsKey(s.charAt(end)))` `      ``{` `        ``// If we have seen the number, move the start pointer` `        ``// to position after the last occurrence` `        ``start = Math.max(start, seen.get(s.charAt(end)) + ``1``);` `      ``}`   `      ``// Updating the last seen value of the character` `      ``seen.put(s.charAt(end), end);` `      ``maximum_length = Math.max(maximum_length, end-start + ``1``);` `    ``}` `    ``return` `maximum_length;` `  ``}`   `  ``// Driver code` `  ``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);` `  ``}` `}`   `// This code is contributed by rutvik_56.`

## Python3

 `# Here, we are planning to implement a simple sliding window methodology` ` `  `def` `longestUniqueSubsttr(string):` `     `  `    ``# Creating a set to store the last positions of occurrence` `    ``seen ``=` `{}` `    ``maximum_length ``=` `0` ` `  `    ``# starting the initial point of window to index 0` `    ``start ``=` `0` `     `  `    ``for` `end ``in` `range``(``len``(string)):` ` `  `        ``# Checking if we have already seen the element or not` `        ``if` `string[end] ``in` `seen:`   `            ``# If we have seen the number, move the start pointer` `            ``# to position after the last occurrence` `            ``start ``=` `max``(start, seen[string[end]] ``+` `1``)` ` `  `        ``# Updating the last seen value of the character` `        ``seen[string[end]] ``=` `end` `        ``maximum_length ``=` `max``(maximum_length, end``-``start ``+` `1``)` `    ``return` `maximum_length` ` `  `# Driver Code` `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)` `  ``{`   `    ``// Creating a set to store the last positions of occurrence` `    ``Dictionary<``char``, ``int``> seen = ``new` `Dictionary<``char``, ``int``>();  ` `    ``int` `maximum_length = 0;`   `    ``// starting the initial point of window to index 0` `    ``int` `start = 0;`   `    ``for``(``int` `end = 0; end < s.Length; end++)` `    ``{` `      ``// Checking if we have already seen the element or not` `      ``if``(seen.ContainsKey(s[end]))` `      ``{` `        ``// If we have seen the number, move the start pointer` `        ``// to position after the last occurrence` `        ``start = Math.Max(start, seen[s[end]] + 1);` `      ``}`   `      ``// Updating the last seen value of the character` `      ``seen[s[end]] = end;` `      ``maximum_length = Math.Max(maximum_length, end-start + 1);` `    ``}` `    ``return` `maximum_length;` `  ``}`   `  ``// Driver code` `  ``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);` `  ``}` `}`   `// This code is contributed by divyesh072019.`

## Javascript

 ``

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++

 `// C++ implementation of the above approach` `#include ` `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);` `    ``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);` `}`   `// Driver program to test above function` `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;` `}` `// this code is contributed by akashish__`

## Java

 `/*package whatever //do not write package name here */` `import` `java.util.*;`   `class` `GFG {` `  ``public` `static` `int` `longestSubstrDistinctChars(String s)` `  ``{` `    ``if` `(s.length() == ``0``) {` `      ``return` `0``;` `    ``}` `    ``int` `n = s.length();` `    ``HashSet st = ``new` `HashSet();` `    ``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);` `  ``}` `}`   `// This code is contributed by akashish__`

## Python3

 `# Python3 implementation of the above approach` `# instead of len variable we have used leng ` `# because len is a reserved keyword in python.` `# same reason for using string instead of str` `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:` `        ``# check if consiqutive chars are distinct and non repeating` `        ``if` `s[i] !``=` `s[i ``-` `1``] ``and` `s[i] ``not` `in` `st:` `            ``st.add(s[i])` `            ``leng ``+``=` `1` `            ``i ``+``=` `1` `            ``# back up the max length` `            ``if` `leng > maxLen:` `                ``maxLen ``=` `leng` `        ``else``:` `            ``# move forward for repeating chars ` `            ``if` `leng ``=``=` `1``:` `                ``i ``+``=` `1` `            ``else``:` `                ``# reset the substring and set the pivot for next sub string ` `                ``st.clear()` `                ``i ``=` `i ``-` `leng ``+` `1` `                ``leng ``=` `0` `    ``return` `max``(maxLen, leng)`   `# Driver program to test above function` `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))`   `# this code is contributed by akashish__`

## C#

 `// C# implementation of the above approach`   `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);` `        ``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);` `    ``}` `    `  `    ``// Driver program to test above function` `    ``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

 ``

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

My Personal Notes arrow_drop_up