The Wayback Machine - https://web.archive.org/web/20250109194257/https://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/
Open In App

Longest Substring Without Repeating Characters

Last Updated : 03 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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));

Output
7

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));

Output
7

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));

Output
7

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.



Next Article

Similar Reads

three90RightbarBannerImg