Longest substring without repeating characters
Last Updated :
27 Aug, 2024
Given a string s, find the length of the longest substring without repeating characters.
Examples:
Input: “ABCBC”
Output: 3
Explanation: The longest substring without repeating characters is “ABC”
Input: “AAA”
Output: 1
Explanation: The longest substring without repeating characters is “A”
Input: “GEEKSFORGEEKS”
Output: 7
Explanation: The longest substrings without repeating characters are “EKSFORGâ and “KSFORGE”, with lengths of 7.
[Naive Approach] Consider substrings starting from every index – O(n ^ 2) Time and O(1) Space
We mainly 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 256 (We can also use a hash set, but a visited array would be better because we know that the character set is 256 in most of the cases) to keep track of included characters in the substring.
C++
// C++ program to find the length of the longest
// substring without repeating characters
#include <bits/stdc++.h>
using namespace std;
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> visited(256, false);
for (int j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (visited[s[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[s[j]] = 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>
#include <stdbool.h>
int longestUniqueSubstr(char* s) {
int n = strlen(s);
int res = 0;
for (int i = 0; i < n; i++) {
// Initializing all characters as not visited
bool visited[256] = { false };
for (int j = i; j < n; j++) {
// If current character is visited,
// break the loop
if (visited[s[j]]) {
break;
}
// Else update the result if this window is larger,
// and mark current character as visited.
else {
if (res < j - i + 1)
res = j - i + 1;
visited[s[j]] = true;
}
}
}
return res;
}
int main() {
char s[] = "geeksforgeeks";
printf("%d\n", longestUniqueSubstr(s));
return 0;
}
Java
// Java program to find the length of the longest
// substring without repeating characters
import java.util.*;
public class GfG {
// Function to find the length of the longest
// substring without repeating characters
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[] visited = new boolean[256];
for (int j = i; j < n; j++) {
// If current character is visited,
// Break the loop
if (visited[s.charAt(j)]) {
break;
}
else {
// Else update the result if this
// window is larger, and mark current
// character as visited.
res = Math.max(res, j - i + 1);
visited[s.charAt(j)] = 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
def longestUniqueSubstr(s):
n = len(s)
res = 0
for i in range(n):
# Initializing all characters as not visited
visited = [False] * 256
for j in range(i, n):
# If current character is visited
# Break the loop
if visited[ord(s[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(s[j])] = 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 {
// Function to find the length of the longest
// substring without repeating characters
public 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[] visited = new bool[256];
for (int j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (visited[s[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[s[j]] = 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
function longestUniqueSubstr(s) {
let n = s.length;
let res = 0;
for (let i = 0; i < n; i++) {
// Initializing all characters as not visited
let visited = new Array(256).fill(false);
for (let j = i; j < n; j++) {
// If current character is visited
// Break the loop
if (visited[s.charCodeAt(j)] === true) {
break;
} else {
// Else update the result if this window is larger,
// and mark current character as visited.
res = Math.max(res, j - i + 1);
visited[s.charCodeAt(j)] = true;
}
}
}
return res;
}
const s = "geeksforgeeks";
console.log(longestUniqueSubstr(s));
Time Complexity: O(n^2), the outer loop runs 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) assuming character set is constant. We can better say O(Character-Set-Size)
[Expected Approach – 1] Using Sliding Window of Distinct Characters – O(n) Time and O(1) Space
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.
C++
// C++ code to find the largest substring with
// non-repeating characters using Sliding Window
#include <bits/stdc++.h>
using namespace std;
int longestUniqueSubstr(string& s) {
// if string length is 0
if (s.length() == 0)
return 0;
// if string length 1
if (s.length() == 1)
return 1;
// if string length is more than 1
int maxLength = 0;
vector<bool>visited(256, false);
// left and right pointer of sliding window
int left = 0, right = 0;
while (right < s.length()) {
// If the character is repeated, move left pointer
// to the right and mark visited characters as false
// until the repeating character is no longer part
// of the current window.
while (visited[s[right]] == true) {
visited[s[left]] = false;
left++;
}
visited[s[right]] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
maxLength = max(maxLength, (right - left + 1));
right++;
}
return maxLength;
}
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>
#include <stdbool.h>
int longestUniqueSubstr(const char* s) {
// if string length is 0
if (strlen(s) == 0)
return 0;
// if string length 1
if (strlen(s) == 1)
return 1;
// if string length is more than 1
int maxLength = 0;
bool visited[256] = { false };
// left and right pointer of sliding window
int left = 0, right = 0;
int n = strlen(s); // Store the length of the string
while (right < n) {
// If the character is repeated, move left pointer
// to the right and mark visited characters as false
// until the repeating character is no longer part
// of the current window.
while (visited[s[right]] == true) {
visited[s[left]] = false;
left++;
}
visited[s[right]] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
if(maxLength < (right - left + 1))
maxLength = (right - left + 1);
right++;
}
return maxLength;
}
int main() {
const char* s = "geeksforgeeks";
printf("%d\n", longestUniqueSubstr(s));
return 0;
}
Java
// Java code to find the largest substring with
// non-repeating characters using Sliding Window
class GfG {
// Function to find the length of the largest substring
// with non-repeating characters using Sliding Window
static int longestUniqueSubstr(String s) {
// if string length is 0
if (s.length() == 0)
return 0;
// if string length 1
if (s.length() == 1)
return 1;
// if string length is more than 1
int maxLength = 0;
boolean[] visited = new boolean[256];
// left and right pointer of sliding window
int left = 0, right = 0;
while (right < s.length()) {
// If the character is repeated, move left pointer
// to the right and mark visited characters as false
// until the repeating character is no longer part
// of the current window.
while (visited[s.charAt(right)]) {
visited[s.charAt(left)] = false;
left++;
}
visited[s.charAt(right)] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly
maxLength = Math.max(maxLength, (right - left + 1));
right++;
}
return maxLength;
}
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
def longestUniqueSubstr(s):
# if string length is 0
if len(s) == 0:
return 0
# if string length 1
if len(s) == 1:
return 1
# if string length is more than 1
maxLength = 0
visited = [False] * 256
# left and right pointer of sliding window
left = 0
right = 0
while right < len(s):
# If the character is repeated, move left pointer
# to the right and mark visited characters as false
# until the repeating character is no longer part
# of the current window.
while visited[ord(s[right])] == True:
visited[ord(s[left])] = False
left += 1
visited[ord(s[right])] = True
# The length of the current window (right - left + 1)
# is calculated and answer is updated accordingly.
maxLength = max(maxLength, right - left + 1)
right += 1
return maxLength
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 {
// Function to find the largest substring with non-repeating
// characters using Sliding Window
static int longestUniqueSubstr(string s) {
// if string length is 0
if (s.Length == 0)
return 0;
// if string length 1
if (s.Length == 1)
return 1;
// if string length is more than 1
int maxLength = 0;
bool[] visited = new bool[256];
// left and right pointer of sliding window
int left = 0, right = 0;
while (right < s.Length) {
// If the character is repeated, move left pointer
// to the right and mark visited characters as false
// until the repeating character is no longer part
// of the current window.
while (visited[s[right]] == true) {
visited[s[left]] = false;
left++;
}
visited[s[right]] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
maxLength = Math.Max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
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
function longestUniqueSubstr(s) {
// if string length is 0
if (s.length === 0)
return 0;
// if string length 1
if (s.length === 1)
return 1;
// if string length is more than 1
let maxLength = 0;
let visited = new Array(256).fill(false);
// left and right pointer of sliding window
let left = 0, right = 0;
while (right < s.length) {
// If the character is repeated, move left pointer
// to the right and mark visited characters as false
// until the repeating character is no longer part
// of the current window.
while (visited[s.charCodeAt(right)] === true) {
visited[s.charCodeAt(left)] = false;
left++;
}
visited[s.charCodeAt(right)] = true;
// The length of the current window (right - left + 1)
// is calculated and answer is updated accordingly.
maxLength = Math.max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
const s = "geeksforgeeks";
console.log(longestUniqueSubstr(s));
Working:
Complexity Analysis:
- Time Complexity: O(n), since each character is processed by the
left and right pointers exactly once. - Auxiliary Space: O(1) assuming character set is constant. We can better say O(Character-Set-Size)
[Expected Approach – 2] Using Last Index of Each Character – O(n) Time and O(1) Space
The approach stores the last indexes of already visited characters. The idea is to maintain a window of distinct characters and 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 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.
C++
// C++ code to find the largest substring with
// non-repeating characters using last index of
// repeated character
#include <bits/stdc++.h>
using namespace std;
int longestUniqueSubstr(string& s) {
int n = s.size();
int res = 0;
// last index of all characters is initialized as -1
vector<int> lastIndex(256, -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]] + 1);
// Update result if we get a larger window
res = max(res, end - start + 1);
// Update last index of s[end]
lastIndex[s[end]] = 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>
#include <limits.h>
int longestUniqueSubstr(const char* s) {
int n = strlen(s);
int res = 0;
// last index of all characters is initialized as -1
int lastIndex[256];
for (int i = 0; i < 256; 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 start and last index + 1
start = (start > lastIndex[s[end]] + 1) ? start :
(lastIndex[s[end]] + 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]] = end;
}
return res;
}
int main() {
const 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 int longestUniqueSubstr(String s) {
int n = s.length();
int res = 0;
// last index of all characters is initialized as -1
int[] lastIndex = new int[256];
for (int i = 0; i < 256; 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 start and last index + 1
start = Math.max(start, lastIndex[s.charAt(end)] + 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)] = 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
def longestUniqueSubstr(s):
n = len(s)
res = 0
# last index of all characters is initialized as -1
last_index = [-1] * 256
# 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 start and last index + 1
start = max(start, last_index[ord(s[end])] + 1)
# Update result if we get a larger window
res = max(res, end - start + 1)
# Update last index of s[end]
last_index[ord(s[end])] = end
return res
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 {
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[256];
for (int i = 0; i < 256; 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]] + 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]] = 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
function longestUniqueSubstr(s) {
const n = s.length;
let res = 0;
// last index of all characters is initialized as -1
const lastIndex = new Array(256).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 start and last index + 1
start = Math.max(start, lastIndex[s.charCodeAt(end)] + 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)] = end;
}
return res;
}
const s = "geeksforgeeks";
console.log(longestUniqueSubstr(s));
Working:
Complexity Analysis:
- Time Complexity: O(n), each character is processed at least once: while entering the window.
- Auxiliary Space: O(1) assuming character set is constant. We can better say O(Character-Set-Size)