Longest Substring Without Repeating Characters
Last Updated :
03 Jan, 2025
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: 1
Explanation: The longest substring without repeating characters is “a”
Input: s = “abcdefabcbb”
Output: 6
Explanation: The longest substring without repeating characters is “abcdef”.
[Naive Approach] Consider Substrings Starting From Every Index
The idea is to find length of longest substring with distinct characters starting from every index and maximum of all such lengths will be our answer.
To find the length of the longest substring with distinct characters starting from an index, we create a new visited array of size = MAX_CHAR = 26 to keep track of included characters in the substring. vis[0] checks for ‘a’, vis[1] checks for ‘b’, vis[2] checks for ‘c’ and so on.
Note the MAX_CHAR is alphabet size of input characters which is typically a constant. If we have only lower case characters, then MAX_CHAR is 26 only. If we consider all ASCII characters, then MAX_CHAR is 256.
C++
// C++ program to find the length of the longest
// substring without repeating characters
#include <iostream>
#include <vector>
using namespace std;
const int MAX_CHAR = 26;
int longestUniqueSubstr(string& s) {
int n = s.size();
int res = 0;
for (int i = 0; i < n; i++) {
// Initializing all characters as not visited
vector<bool> vis(MAX_CHAR, false);
for (int j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (vis[s[j] - 'a'] == true)
break;
// Else update the result if this window is larger,
// and mark current character as visited.
else {
res = max(res, j - i + 1);
vis[s[j] - 'a'] = true;
}
}
}
return res;
}
int main() {
string s = "geeksforgeeks";
cout << longestUniqueSubstr(s);
return 0;
}
C
// C program to find the length of the longest
// substring without repeating characters
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 26
int longestUniqueSubstr(char* s) {
int n = strlen(s);
int res = 0;
for (int i = 0; i < n; i++) {
// Initializing all characters as not visited
int vis[MAX_CHAR] = {0};
for (int j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (vis[s[j] - 'a'] == 1)
break;
// Else update the result if this window is larger,
// and mark current character as visited.
else {
res = (res > (j - i + 1)) ? res : (j - i + 1);
vis[s[j] - 'a'] = 1;
}
}
}
return res;
}
int main() {
char s[] = "geeksforgeeks";
printf("%d", longestUniqueSubstr(s));
return 0;
}
Java
// Java program to find the length of the longest
// substring without repeating characters
import java.util.*;
class GfG {
static final int MAX_CHAR = 26;
static int longestUniqueSubstr(String s) {
int n = s.length();
int res = 0;
for (int i = 0; i < n; i++) {
// Initializing all characters as not visited
boolean[] vis = new boolean[MAX_CHAR];
for (int j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (vis[s.charAt(j) - 'a'] == 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);
vis[s.charAt(j) - 'a'] = true;
}
}
}
return res;
}
public static void main(String[] args) {
String s = "geeksforgeeks";
System.out.println(longestUniqueSubstr(s));
}
}
Python
# Python program to find the length of the longest
# substring without repeating characters
MAX_CHAR = 26
def longestUniqueSubstr(s):
n = len(s)
res = 0
for i in range(n):
# Initializing all characters as not visited
vis = [False] * MAX_CHAR
for j in range(i, n):
# If current character is visited
# Break the loop
if vis[ord(s[j]) - ord('a')] == True:
break
# Else update the result if this window is larger,
# and mark current character as visited.
else:
res = max(res, j - i + 1)
vis[ord(s[j]) - ord('a')] = True
return res
if __name__ == "__main__":
s = "geeksforgeeks"
print(longestUniqueSubstr(s))
C#
// C# program to find the length of the longest
// substring without repeating characters
using System;
class GfG {
const int MAX_CHAR = 26;
static int longestUniqueSubstr(string s) {
int n = s.Length;
int res = 0;
for (int i = 0; i < n; i++) {
// Initializing all characters as not visited
bool[] vis = new bool[MAX_CHAR];
for (int j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (vis[s[j] - 'a'] == 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);
vis[s[j] - 'a'] = true;
}
}
}
return res;
}
static void Main() {
string s = "geeksforgeeks";
Console.WriteLine(longestUniqueSubstr(s));
}
}
JavaScript
// JavaScript program to find the length of the longest
// substring without repeating characters
const MAX_CHAR = 26;
function longestUniqueSubstr(s) {
let n = s.length;
let res = 0;
for (let i = 0; i < n; i++) {
// Initializing all characters as not visited
let vis = new Array(MAX_CHAR).fill(false);
for (let j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (vis[s.charCodeAt(j) - 'a'.charCodeAt(0)] === 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);
vis[s.charCodeAt(j) - 'a'.charCodeAt(0)] = true;
}
}
}
return res;
}
// Driver Code
let s = "geeksforgeeks";
console.log(longestUniqueSubstr(s));
Time Complexity: O(n*MAX_CHAR), the outer loop runs O(n) time, and the inner loop runs in O(MAX_CHAR) in the worst case (considering all unique characters), resulting in a total time complexity of O(n * MAX_CHAR).
Auxiliary Space: O(MAX_CHAR).
[Expected Approach 1] Using Sliding Window of Distinct Characters
The idea is to maintain a window of distinct characters. The window is initialized as single character. We keep extending the window on the right side till we see distinct characters. When we see a repeating character, we remove characters from the left side of the window. We keep track of the maximum length window.
Below are the detailed steps:
- Initialize 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.
Working:
C++
// C++ code to find the largest substring with non-repeating
// characters using Sliding Window
#include <iostream>
#include <vector>
using namespace std;
const int MAX_CHAR = 26;
int longestUniqueSubstr(string& s) {
if (s.length() == 0 || s.length() == 1)
return s.length();
int res = 0;
vector<bool>vis(MAX_CHAR, false);
// left and right pointer of sliding window
int left = 0, right = 0;
while (right < s.length()) {
// If character is repeated, move left pointer marking
// visited characters as false until the repeating
// character is no longer part of the current window
while (vis[s[right] - 'a'] == true) {
vis[s[left] - 'a'] = false;
left++;
}
vis[s[right] - 'a'] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
res = max(res, (right - left + 1));
right++;
}
return res;
}
int main() {
string s = "geeksforgeeks";
cout << longestUniqueSubstr(s);
return 0;
}
C
// C code to find the largest substring with non-repeating
// characters using Sliding Window
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 26
int longestUniqueSubstr(char* s) {
if (strlen(s) == 0 || strlen(s) == 1)
return strlen(s);
int res = 0;
int vis[MAX_CHAR] = {0};
// left and right pointer of sliding window
int left = 0, right = 0;
while (right < strlen(s)) {
// If character is repeated, move left pointer marking
// visited characters as false until the repeating
// character is no longer part of the current window
while (vis[s[right] - 'a'] == 1) {
vis[s[left] - 'a'] = 0;
left++;
}
vis[s[right] - 'a'] = 1;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
res = (res > (right - left + 1)) ? res : (right - left + 1);
right++;
}
return res;
}
int main() {
char s[] = "geeksforgeeks";
printf("%d", longestUniqueSubstr(s));
return 0;
}
Java
// Java code to find the largest substring with non-repeating
// characters using Sliding Window
class GfG {
static final int MAX_CHAR = 26;
static int longestUniqueSubstr(String s) {
if (s.length() == 0 || s.length() == 1)
return s.length();
int res = 0;
boolean[] vis = new boolean[MAX_CHAR];
// left and right pointer of sliding window
int left = 0, right = 0;
while (right < s.length()) {
// If character is repeated, move left pointer marking
// visited characters as false until the repeating
// character is no longer part of the current window
while (vis[s.charAt(right) - 'a'] == true) {
vis[s.charAt(left) - 'a'] = false;
left++;
}
vis[s.charAt(right) - 'a'] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
res = Math.max(res, (right - left + 1));
right++;
}
return res;
}
public static void main(String[] args) {
String s = "geeksforgeeks";
System.out.println(longestUniqueSubstr(s));
}
}
Python
# Python code to find the largest substring with non-repeating
# characters using Sliding Window
MAX_CHAR = 26
def longestUniqueSubstr(s):
if len(s) == 0 or len(s) == 1:
return len(s)
res = 0
vis = [False] * MAX_CHAR
# left and right pointer of sliding window
left = 0
right = 0
while right < len(s):
# If character is repeated, move left pointer marking
# visited characters as false until the repeating
# character is no longer part of the current window
while vis[ord(s[right]) - ord('a')] == True:
vis[ord(s[left]) - ord('a')] = False
left += 1
vis[ord(s[right]) - ord('a')] = True
# The length of the current window (right - left + 1)
# is calculated and answer is updated accordingly.
res = max(res, (right - left + 1))
right += 1
return res
if __name__ == "__main__":
s = "geeksforgeeks"
print(longestUniqueSubstr(s))
C#
// C# code to find the largest substring with non-repeating
// characters using Sliding Window
using System;
class GfG {
const int MAX_CHAR = 26;
static int longestUniqueSubstr(string s) {
if (s.Length == 0 || s.Length == 1)
return s.Length;
int res = 0;
bool[] vis = new bool[MAX_CHAR];
// left and right pointer of sliding window
int left = 0, right = 0;
while (right < s.Length) {
// If character is repeated, move left pointer marking
// visited characters as false until the repeating
// character is no longer part of the current window
while (vis[s[right] - 'a'] == true) {
vis[s[left] - 'a'] = false;
left++;
}
vis[s[right] - 'a'] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
res = Math.Max(res, (right - left + 1));
right++;
}
return res;
}
static void Main() {
string s = "geeksforgeeks";
Console.WriteLine(longestUniqueSubstr(s));
}
}
JavaScript
// JavaScript code to find the largest substring with non-repeating
// characters using Sliding Window
const MAX_CHAR = 26;
function longestUniqueSubstr(s) {
if (s.length === 0 || s.length === 1)
return s.length;
let res = 0;
let vis = new Array(MAX_CHAR).fill(false);
// left and right pointer of sliding window
let left = 0, right = 0;
while (right < s.length) {
// If character is repeated, move left pointer marking
// visited characters as false until the repeating
// character is no longer part of the current window
while (vis[s[right].charCodeAt(0) - 'a'.charCodeAt(0)] === true) {
vis[s[left].charCodeAt(0) - 'a'.charCodeAt(0)] = false;
left++;
}
vis[s[right].charCodeAt(0) - 'a'.charCodeAt(0)] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
res = Math.max(res, (right - left + 1));
right++;
}
return res;
}
// Driver Code
const s = "geeksforgeeks";
console.log(longestUniqueSubstr(s));
Time Complexity: O(n), since each character is processed by the left and right pointers exactly once.
Auxiliary Space: O(MAX_CHAR), MAX_CHAR = 26 as the input string can have only lowercase letters.
[Expected Approach 2] Using Last Index of Each Character
The approach stores the last indexes of already visited characters. The idea is to maintain a window of distinct characters. Start from the first character, and keep extending the window on the right side till we see distinct characters. When we see a repeating character, we check for the last index of the repeated character:
- If last index of repeated character >= starting index of the current window, then we update the starting index of the current window to last index of repeated character + 1 to remove the repeated character.
- If last index of repeated character < starting index of the current window, then it means that the repeated character is already outside the current window so the window size remains unchanged.
After iterating over all the characters, the largest window size will be our answer.
Working:
C++
// C++ code to find the largest substring with non-repeating
// characters using last index of repeated character
#include <iostream>
#include <vector>
using namespace std;
const int MAX_CHAR = 26;
int longestUniqueSubstr(string& s) {
int n = s.size();
int res = 0;
// last index of all characters is initialized as -1
vector<int> lastIndex(MAX_CHAR, -1);
// Initialize start of current window
int start = 0;
// Move end of current window
for (int end = 0; end < n; end++) {
// Find the last index of s[end]
// Update starting index of current window as
// maximum of current value of end and last index + 1
start = max(start, lastIndex[s[end] - 'a'] + 1);
// Update result if we get a larger window
res = max(res, end - start + 1);
// Update last index of s[end]
lastIndex[s[end] - 'a'] = end;
}
return res;
}
int main() {
string s = "geeksforgeeks";
cout << longestUniqueSubstr(s);
return 0;
}
C
// C code to find the largest substring with non-repeating
// characters using last index of repeated character
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 26
int longestUniqueSubstr(char* s) {
int n = strlen(s);
int res = 0;
// last index of all characters is initialized as -1
int lastIndex[MAX_CHAR];
for (int i = 0; i < MAX_CHAR; i++) {
lastIndex[i] = -1;
}
// Initialize start of current window
int start = 0;
// Move end of current window
for (int end = 0; end < n; end++) {
// Find the last index of s[end]
// Update starting index of current window as
// maximum of current value of end and last index + 1
start = (start > lastIndex[s[end] - 'a'] + 1) ? start :
(lastIndex[s[end] - 'a'] + 1);
// Update result if we get a larger window
res = (res > end - start + 1) ? res : (end - start + 1);
// Update last index of s[end]
lastIndex[s[end] - 'a'] = end;
}
return res;
}
int main() {
char s[] = "geeksforgeeks";
printf("%d\n", longestUniqueSubstr(s));
return 0;
}
Java
// Java code to find the largest substring with non-repeating
// characters using last index of repeated character
class GfG {
static final int MAX_CHAR = 26;
static int longestUniqueSubstr(String s) {
int n = s.length();
int res = 0;
// last index of all characters is initialized as -1
int[] lastIndex = new int[MAX_CHAR];
for (int i = 0; i < MAX_CHAR; i++) {
lastIndex[i] = -1;
}
// Initialize start of current window
int start = 0;
// Move end of current window
for (int end = 0; end < n; end++) {
// Find the last index of s[end]
// Update starting index of current window as
// maximum of current value of end and last index + 1
start = Math.max(start, lastIndex[s.charAt(end) - 'a'] + 1);
// Update result if we get a larger window
res = Math.max(res, end - start + 1);
// Update last index of s[end]
lastIndex[s.charAt(end) - 'a'] = end;
}
return res;
}
public static void main(String[] args) {
String s = "geeksforgeeks";
System.out.println(longestUniqueSubstr(s));
}
}
Python
# Python code to find the largest substring with non-repeating
# characters using last index of repeated character
MAX_CHAR = 26
def longestUniqueSubstr(s):
n = len(s)
res = 0
# last index of all characters is initialized as -1
lastIndex = [-1] * MAX_CHAR
# Initialize start of current window
start = 0
# Move end of current window
for end in range(n):
# Find the last index of s[end]
# Update starting index of current window as
# maximum of current value of end and last index + 1
start = max(start, lastIndex[ord(s[end]) - ord('a')] + 1)
# Update result if we get a larger window
res = max(res, end - start + 1)
# Update last index of s[end]
lastIndex[ord(s[end]) - ord('a')] = end
return res
if __name__ == "__main__":
s = "geeksforgeeks"
print(longestUniqueSubstr(s))
C#
// C# code to find the largest substring with non-repeating
// characters using last index of repeated character
using System;
class GfG {
const int MAX_CHAR = 26;
public static int longestUniqueSubstr(string s) {
int n = s.Length;
int res = 0;
// last index of all characters is initialized as -1
int[] lastIndex = new int[MAX_CHAR];
for (int i = 0; i < MAX_CHAR; i++) {
lastIndex[i] = -1;
}
// Initialize start of current window
int start = 0;
// Move end of current window
for (int end = 0; end < n; end++) {
// Find the last index of s[end]
// Update starting index of current window as
// maximum of current value of end and last index + 1
start = Math.Max(start, lastIndex[s[end] - 'a'] + 1);
// Update result if we get a larger window
res = Math.Max(res, end - start + 1);
// Update last index of s[end]
lastIndex[s[end] - 'a'] = end;
}
return res;
}
static void Main() {
string s = "geeksforgeeks";
Console.WriteLine(longestUniqueSubstr(s));
}
}
JavaScript
// JavaScript code to find the largest substring with non-repeating
// characters using last index of repeated character
const MAX_CHAR = 26;
function longestUniqueSubstr(s) {
const n = s.length;
let res = 0;
// last index of all characters is initialized as -1
const lastIndex = new Array(MAX_CHAR).fill(-1);
// Initialize start of current window
let start = 0;
// Move end of current window
for (let end = 0; end < n; end++) {
// Find the last index of s[end]
// Update starting index of current window as
// maximum of current value of end and last index + 1
start = Math.max(start, lastIndex[s.charCodeAt(end) - 'a'.charCodeAt(0)] + 1);
// Update result if we get a larger window
res = Math.max(res, end - start + 1);
// Update last index of s[end]
lastIndex[s.charCodeAt(end) - 'a'.charCodeAt(0)] = end;
}
return res;
}
// Driver Code
const s = "geeksforgeeks";
console.log(longestUniqueSubstr(s));
Time Complexity: O(n), each character is processed once.
Auxiliary Space: O(MAX_CHAR), MAX_CHAR = 26 as the input string can have only lowercase letters.
Similar Reads
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:
15+ min read
Print Longest substring without repeating characters
Given a string, print the longest substring without repeating characters. For example, the longest substrings without repeating characters for âABDEFGABEFâ are âBDEFGAâ and âDEFGABâ, with length 6. For âBBBBâ the longest substring is âBâ, with length 1. The desired time complexity is O(n) where n is
14 min read
Longest Common Subsequence with no repeating character
Given two strings s1 and s2, the task is to find the length of the longest common subsequence with no repeating character. Examples: Input: s1= "aabbcc", s2= "aabc"Output: 3Explanation: "aabc" is longest common subsequence but it has two repeating character 'a'.So the required longest common subsequ
10 min read
Count K-Length Substrings With No Repeated Characters
Given a string S and an integer k, the task is to return the number of substrings in S of length k with no repeated characters. Example: Input: S = "geeksforgeeks", k = 5Output: 4Explanation: There are 4 substrings, they are: 'eksfo', 'ksfor', 'sforg', 'forge'. Input: S = "home", k = 5Output: 0Expla
6 min read
Find the last non repeating character in string
Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is "GeeksForGeeks", then the output should be 'r' and if the input string is "GeeksQuiz" then the output should be 'z'. if there is no non-repeating character then print -1.Examples: Inpu
5 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
K'th Non-repeating Character
Given a string str of length n (1 <= n <= 106) and a number k, the task is to find the kth non-repeating character in the string. Examples: Input : str = geeksforgeeks, k = 3Output : rExplanation: First non-repeating character is f, second is o and third is r. Input : str = geeksforgeeks, k =
14 min read
Longest substring with K unique characters using Binary Search
Given a string str and an integer K, the task is to print the length of the longest possible substring that has exactly K unique characters. If there is more than one substring of the longest possible length, then print any one of them or print -1 if there is no such substring possible. Examples: In
10 min read
Longest Substring that can be made a palindrome by swapping of characters
Given a numeric string S, the task is to find the longest non-empty substring that can be made palindrome. Examples: Input: S = "3242415"Output: 5Explanation: "24241" is the longest such substring which can be converted to the palindromic string "24142". Input: S = "213123"Output: 6Explanation: "213
12 min read
Length of the longest substring with consecutive characters
Given string str of lowercase alphabets, the task is to find the length of the longest substring of characters in alphabetical order i.e. string "dfabck" will return 3. Note that the alphabetical order here is considered circular i.e. a, b, c, d, e, ..., x, y, z, a, b, c, .... Examples: Input: str =
7 min read
Count substrings with same first and last characters
We are given a string S, we need to find count of all contiguous substrings starting and ending with same character. Examples : Input : S = "abcab"Output : 7There are 15 substrings of "abcab"a, ab, abc, abca, abcab, b, bc, bcabcab, c, ca, cab, a, ab, bOut of the above substrings, there are 7 substri
13 min read
Longest Substring of 1's after removing one character
Given a binary string S of length N, the task is to find the longest substring consisting of '1's only present in the string after deleting a character from the string. Examples: Input: S = "1101"Output: 3Explanation: Removing S[0], S modifies to "101". Longest possible substring of '1's is 1.Removi
12 min read
Find the longest substring with k unique characters in a given string
Given a string you need to print longest possible substring that has exactly M unique characters. If there is more than one substring of longest possible length, then print any one of them. Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max substring can be any one from {"aa" , "bb" , "
15+ min read
Longest substring whose characters can be rearranged to form a Palindrome
Given a string S of length N which only contains lowercase alphabets. Find the length of the longest substring of S such that the characters in it can be rearranged to form a palindrome. Examples: Input: S = âaabeâOutput: 3Explanation:The substring âaabâ can be rearranged to form "aba", which is a p
15+ min read
Maximum consecutive repeating character in string
Given a string, the task is to find the maximum consecutive repeating character in a string.Note: We do not need to consider the overall count, but the count of repeating that appears in one place.Examples: Input : str = "geeekk"Output : eInput : str = "aaaabbcbbb"Output : a The simple solution to t
13 min read
Print the longest common substring
Given two strings âXâ and âYâ, print the length of the longest common substring. If two or more substrings have the same value for the longest common substring, then print any one of them. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx"
15+ min read
Minimum length substring with exactly K distinct characters
Given a string S and a number K. The task is to find the minimum length substring having exactly K distinct characters. Note: The string S consists of only lowercase English alphabets. Examples: Input: S = "ababcb", K = 3 Output: abc Input: S="efecfefd", K = 4 Output: cfefd Naive approach: A simple
15 min read
Find the Earliest Repeating Character
Given a string S of length n, the task is to find the earliest repeated character in it. The earliest repeated character means, the character that occurs more than once and whose second occurrence has the smallest index. Example: Input: s = "geeksforgeeks" Output: e Explanation: e is the first eleme
9 min read
Find length of longest substring with at most K normal characters
Given a string P consisting of small English letters and a 26-digit bit string Q, where 1 represents the special character and 0 represents a normal character for the 26 English alphabets. The task is to find the length of the longest substring with at most K normal characters. Examples: Input : P =
12 min read