Length of the longest substring without repeating characters
Last Updated :
29 Feb, 2024
Given a string str, find the length of the longest substring without repeating characters.
Example:
Example 1:
Input: “ABCDEFGABEF”
Output: 7
Explanation: The longest substring without repeating characters are “ABCDEFG”, “BCDEFGA”, and “CDEFGAB” with lengths of 7
Example 2:
Input: “GEEKSFORGEEKS”
Output: 7
Explanation: The longest substrings without repeating characters are “EKSFORG” and “KSFORGE”, with lengths of 7
Length of the longest substring without repeating characters using Sliding Window in O(n3) time:
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.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool areDistinct(string str, int i, int j)
{
vector< bool > visited(256);
for ( int k = i; k <= j; k++) {
if (visited[str[k]] == true )
return false ;
visited[str[k]] = 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[256];
for ( int i = 0; i < 256; i++)
visited[i] = 0;
for ( int k = i; k <= j; k++) {
if (visited[str[k]] == true )
return false ;
visited[str[k]] = 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 [ 256 ];
for ( int k = i; k <= j; k++) {
if (visited[str.charAt(k)] == true )
return false ;
visited[str.charAt(k)] = 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);
}
}
|
C#
using System;
class GFG {
public static bool areDistinct( string str, int i, int j)
{
bool [] visited = new bool [256];
for ( int k = i; k <= j; k++) {
if (visited[str[k]] == true )
return false ;
visited[str[k]] = 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
function areDistinct(str, i, j)
{
var visited = new Array(256);
for ( var k = i; k <= j; k++)
{
if (visited[str.charAt(k) ] == true )
return false ;
visited[str.charAt(k)] = 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" ;
console.log( "The input string is " + str);
var len = longestUniqueSubsttr(str);
console.log( "The length of the longest " +
"non-repeating character " +
"substring is " + len);
|
Python3
def areDistinct( str , i, j):
visited = [ 0 ] * ( 256 )
for k in range (i, j + 1 ):
if (visited[ ord ( str [k])] = = True ):
return False
visited[ ord ( str [k])] = 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 )
|
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)
Length of the longest substring without repeating characters using Sliding Window in O(n2) time:
For each index i, find the the length of longest substring without repeating characters starting at index i. This can be done by starting at index i, and iterating until the end of the string, if a repeating character is found before the end of string we will break else update the answer if the current substring is larger.
Below is the implementation of above approach:
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);
}
}
|
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
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" ;
console.log( "The input string is " + str);
var len = longestUniqueSubsttr(str);
console.log( "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 )
|
Output
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Time Complexity: O(n^2), (The outer loop runs in O(n) time, and the inner loop runs in O(n) in the worst case (considering all unique characters), resulting in a total time complexity of O(n^2).)
Auxiliary Space: O(1)
Length of the longest substring without repeating characters using Binary Search on Answer:
The idea is to check if a substring of a certain size “mid” is valid (A size mid is valid if there exists atleast one substring of size mid which contains all unique characters ), then all the size less than “mid” will also be valid. Similarly, if a substring of size “mid” is not valid(A size mid is not valid if there does not exists any substring of size mid which contains all unique characters ), then all the size larger than “mid” will also not be valid. This allows us to apply binary search effectively.
Follow the steps below to solve the problem:
- Initialize low and high as 1 and string length respectively denoting the minimum and maximum possible answer.
- For any value mid check if there is any substring of length mid in the string that contains all the unique characters.
- If any such substring of length exists then update the value of answer with mid store the starting index of that substring and update low to mid+1 and, check for substrings having lengths larger than mid.
- Otherwise, if any such substring does not exist then update high to mid-1 and, check for substrings having lengths smaller than mid.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isValid(string& s, int mid)
{
int count[256] = { 0 };
bool found = false ;
int distinct = 0;
for ( int i = 0; i < s.size(); i++) {
count[s[i]]++;
if (count[s[i]] == 1) {
distinct++;
}
if (i >= mid) {
count[s[i - mid]]--;
if (count[s[i - mid]] == 0) {
distinct--;
}
}
if (i >= mid - 1) {
if (distinct == mid) {
found = true ;
}
}
}
return found;
}
int longestUniqueSubsttr(string& s)
{
int len = s.length();
int ans = INT_MAX;
int low_bound = 1, high_bound = len;
while (low_bound <= high_bound) {
int mid = (low_bound + high_bound) / 2;
if (isValid(s,mid)) {
ans=mid;
low_bound = mid + 1;
}
else {
high_bound = mid - 1;
}
}
return ans;
}
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.Arrays;
public class Main {
static boolean isValid(String s, int mid) {
int [] count = new int [ 256 ];
boolean found = false ;
int distinct = 0 ;
for ( int i = 0 ; i < s.length(); i++) {
count[s.charAt(i)]++;
if (count[s.charAt(i)] == 1 ) {
distinct++;
}
if (i >= mid) {
count[s.charAt(i - mid)]--;
if (count[s.charAt(i - mid)] == 0 ) {
distinct--;
}
}
if (i >= mid - 1 && distinct == mid) {
found = true ;
}
}
return found;
}
static int longestUniqueSubsttr(String s) {
int len = s.length();
int ans = Integer.MAX_VALUE;
int lowBound = 1 , highBound = len;
while (lowBound <= highBound) {
int mid = (lowBound + highBound) / 2 ;
if (isValid(s, mid)) {
ans = mid;
lowBound = mid + 1 ;
} else {
highBound = mid - 1 ;
}
}
return ans;
}
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);
}
}
|
C#
using System;
class GFG
{
static bool IsValid( string s, int mid)
{
int [] count = new int [256];
bool found = false ;
int distinct = 0;
for ( int i = 0; i < s.Length; i++)
{
count[s[i]]++;
if (count[s[i]] == 1)
{
distinct++;
}
if (i >= mid)
{
count[s[i - mid]]--;
if (count[s[i - mid]] == 0)
{
distinct--;
}
}
if (i >= mid - 1)
{
if (distinct == mid)
{
found = true ;
}
}
}
return found;
}
static int LongestUniqueSubstring( string s)
{
int len = s.Length;
int ans = int .MaxValue;
int lowBound = 1, highBound = len;
while (lowBound <= highBound)
{
int mid = (lowBound + highBound) / 2;
if (IsValid(s, mid))
{
ans = mid;
lowBound = mid + 1;
}
else
{
highBound = mid - 1;
}
}
return ans;
}
static void Main( string [] args)
{
string str = "geeksforgeeks" ;
Console.WriteLine( "The input string is " + str);
int len = LongestUniqueSubstring(str);
Console.WriteLine( "The length of the longest non-repeating " +
"character substring is " + len);
}
}
|
Javascript
function isValid(s, mid) {
let count = new Array(256).fill(0);
let found = false ;
let distinct = 0;
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i)]++;
if (count[s.charCodeAt(i)] === 1) {
distinct++;
}
if (i >= mid) {
count[s.charCodeAt(i - mid)]--;
if (count[s.charCodeAt(i - mid)] === 0) {
distinct--;
}
}
if (i >= mid - 1) {
if (distinct === mid) {
found = true ;
}
}
}
return found;
}
function longestUniqueSubsttr(s) {
const len = s.length;
let ans = Number.MAX_SAFE_INTEGER;
let low_bound = 1;
let high_bound = len;
while (low_bound <= high_bound) {
const mid = Math.floor((low_bound + high_bound) / 2);
if (isValid(s, mid)) {
ans = mid;
low_bound = mid + 1;
} else {
high_bound = mid - 1;
}
}
return ans;
}
const str = "geeksforgeeks" ;
console.log( "The input string is " + str);
const len = longestUniqueSubsttr(str);
console.log( "The length of the longest non-repeating " +
"character substring is " + len);
|
Python3
def is_valid(s, mid):
count = [ 0 ] * 256
found = False
distinct = 0
for i in range ( len (s)):
count[ ord (s[i])] + = 1
if count[ ord (s[i])] = = 1 :
distinct + = 1
if i > = mid:
count[ ord (s[i - mid])] - = 1
if count[ ord (s[i - mid])] = = 0 :
distinct - = 1
if i > = mid - 1 :
if distinct = = mid:
found = True
return found
def longest_unique_substring(s):
length = len (s)
ans = float ( 'inf' )
low_bound = 1
high_bound = length
while low_bound < = high_bound:
mid = (low_bound + high_bound) / / 2
if is_valid(s, mid):
ans = mid
low_bound = mid + 1
else :
high_bound = mid - 1
return ans
if __name__ = = "__main__" :
input_str = "geeksforgeeks"
print ( "The input string is" , input_str)
length = longest_unique_substring(input_str)
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
Time Complexity: O(N*logN), where N is the length of string.
Auxiliary Space: O(1)
Length of the longest substring without repeating characters using Sliding Window:
Using this solution the problem can be solved in linear time using the window sliding technique.
Follow the steps below to solve the problem:
- Intialize two pointers left and right with 0, which define the current window being considered.
- The
right
pointer moves from left to right, extending the current window.
- If the character at
right pointer
is not visited , it’s marked as visited.
- If the character at
right pointer
is visited, it means there is a repeating character. The left
pointer moves to the right while marking visited characters as false until the repeating character is no longer part of the current window.
- The length of the current window (
right - left + 1
) is calculated and answer is updated accordingly.
Below is the implementation of above approach:
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;
while (right < str.length()) {
if (visited[str[right]] == true ) {
while (visited[str[right]] == true ) {
visited[str[left]] = false ;
left++;
}
}
visited[str[right]] = true ;
maxLength = max(maxLength, (right - left + 1));
right++;
}
return maxLength;
}
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.*;
class GFG {
public static int longestUniqueSubsttr(String str)
{
if (str.length() == 0 )
return 0 ;
if (str.length() == 1 )
return 1 ;
int maxLength = 0 ;
boolean [] visited = new boolean [ 256 ];
int left = 0 , right = 0 ;
while (right < str.length()) {
if (visited[str.charAt(right)]) {
while (visited[str.charAt(right)]) {
visited[str.charAt(left)] = false ;
left++;
}
}
visited[str.charAt(right)] = true ;
maxLength
= Math.max(maxLength, (right - left + 1 ));
right++;
}
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);
}
}
|
C#
using System;
public class GFG {
public static int LongestUniqueSubsttr( string str)
{
if (str.Length == 0)
return 0;
if (str.Length == 1)
return 1;
int maxLength = 0;
bool [] visited = new bool [256];
int left = 0, right = 0;
while (right < str.Length) {
if (visited[str[right]]) {
while (visited[str[right]]) {
visited[str[left]] = false ;
left++;
}
}
visited[str[right]] = true ;
maxLength
= Math.Max(maxLength, right - left + 1);
right++;
}
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 = new Array(256).fill( false );
let left = 0, right = 0;
while (right < str.length) {
if (visited[str.charCodeAt(right)]) {
while (visited[str.charCodeAt(right)]) {
visited[str.charCodeAt(left)] = false ;
left++;
}
}
visited[str.charCodeAt(right)] = true ;
maxLength = Math.max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
let s = "geeksforgeeks" ;
console.log( "The input string is " + s);
console.log( "The length of the longest non-repeating " +
"character substring is " + longestUniqueSubsttr(s));
|
Python3
import math
def longestUniqueSubsttr(s):
if len (s) = = 0 :
return 0
if len (s) = = 1 :
return 1
maxLength = 0
visited = [ False ] * 256
left, right = 0 , 0
while right < len (s):
if visited[ ord (s[right])]:
while visited[ ord (s[right])]:
visited[ ord (s[left])] = False
left + = 1
visited[ ord (s[right])] = True
maxLength = max (maxLength, right - left + 1 )
right + = 1
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)
|
Output
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Time Complexity: O(n), Since each character is processed by the left
and right
pointers exactly once.
Auxiliary Space: O(1)
Length of the longest substring without repeating characters by Storing the last index of each character:
The approach stores the last indexes of already visited characters. The idea is to traverse the string from left to right, for each character at index j
, update the i
pointer(starting index of current window)
to be the maximum of its current value and last Index of
str[j] + 1
. This step ensures that i
is moved to the appropriate position to exclude any repeating characters within the new window.
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);
}
}
|
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
var NO_OF_CHARS = 256;
function longestUniqueSubsttr(str)
{
var n = str.length;
var res = 0;
let lastIndex = new Array(256).fill(-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" ;
console.log( "The input string is " + str);
var len = longestUniqueSubsttr(str);
console.log( "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))
|
Output
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Time Complexity: O(n), each character is processed exactly twice: once when it enters the window (j
) and once when it exits the window (i
).
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...