C++ Program To Find Length Of The Longest Substring Without Repeating Characters
Last Updated :
19 Apr, 2023
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).
C++
// C++ program to find the length of the longest substring
// without repeating characters
#include <bits/stdc++.h>
using namespace std;
// This functionr eturns 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;
}
OutputThe 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.
C++
// C++ program to find the length of the longest substring
// without repeating characters
#include <bits/stdc++.h>
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;
}
OutputThe 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 :
C++
// C++ program to find the length of the longest substring
// without repeating characters
#include <bits/stdc++.h>
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;
}
OutputThe 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)
{
// Creating a set 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
OutputThe 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!
Similar Reads
How to Find the Length of a Substring in a char Array? In C++, a substring is a string inside another string that is the contiguous part of the string. In this article, we will learn how to find the length of a substring in a char array in C++. Example Input: str[] = "Hello, World!";substr= "World";Output: Length of substring World is: 5Finding Length o
2 min read
Longest substring that starts with X and ends with Y Given a string str, two characters X and Y. The task is to find the length of the longest substring that starts with X and ends with Y. It is given that there always exists a substring that starts with X and ends with Y. Examples: Input: str = "QWERTYASDFZXCV", X = 'A', Y = 'Z' Output: 5 Explanation
10 min read
Largest substring where all characters appear at least K times | Set 2 Given a string str and an integer K, the task is to find the length of the longest sub-string S such that every character in S appears at least K times.Examples:Input: str = "aabbba", K = 3Output: 6 Explanation: In substring aabbba, each character repeats at least k times and its length is 6.Input:
7 min read
How to Compare Two Substrings in a Character Array in C++? In C++, character arrays are used to store a sequence of characters also known as strings. A Substring is a continuous sequence of characters within a string. In this article, we will learn how we can compare two substrings in a character array in C++. Examples: Input: string: "Hello World" Substrin
2 min read
Find longest length number in a string Given a string of digits and characters. Write a program to find the number with the maximum number of digits in a string. Note: The number may not be the greatest number in the string. For example, if the string is "a123bc321" then the answer can be 123 or 321 as the problem is to find the number w
6 min read
Longest prefix in a string with highest frequency Given a string, find a prefix with the highest frequency. If two prefixes have the same frequency then consider the one with the maximum length. Examples: Input : str = "abc" Output : abc Each prefix has same frequency(one) and the prefix with maximum length is "abc". Input : str = "abcab" Output :
7 min read
Java Program To Find Length Of The Longest Substring Without Repeating Characters 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
8 min read
Python Program To Find Length Of The Longest Substring Without Repeating Characters 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
6 min read
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters 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
5 min read
Print Longest substring without repeating characters Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples:Input: s = âgeeksforgeeksâOutput: 7 Explanation: The longest substrings without repeating characters are âeksforgâ and âksforgeâ, with lengths of 7.Input: s = âaaaâOutput: 1E
14 min read