Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count substrings with k distinct characters
Next article icon

Print Longest substring without repeating characters

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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”.

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 the length of the string.

Examples: 

Input : GEEKSFORGEEKS
Output : EKSFORG
Input : ABDEFGABEF
Output : BDEFGA


Approach: 

The idea is to traverse the string and for each already visited character store its last occurrence in a hash table(Here unordered_map is used as a hash with key as character and value as its last position). The variable st stores the starting point of the current substring, maxlen stores the length of maximum length substring, and start stores the starting index of maximum length substring. While traversing the string, check whether the current character is present in the hash table or not. 

If it is not present, then store the current character in the hash table with value as the current index. If it is already present in the hash table, this means the current character could repeat in the current substring. For this check, if the previous occurrence of character is before or after the starting point st of the current substring. If it is before st, then only update the value in the hash table. If it is after st, then find the length of current substring currlen as i-st, where i is the current index. Compare currlen with maxlen. If maxlen is less than currlen, then update maxlen as currlen and start as st. After complete traversal of the string, the required the longest substring without repeating characters is from s[start] to s[start+maxlen-1]. 

Implementation: 

C++
// C++ program to find and print longest // substring without repeating characters. #include <bits/stdc++.h>  using namespace std;  // Function to find and print longest // substring without repeating characters. string findLongestSubstring(string str) {     int i;     int n = str.length();      // starting point of current substring.     int st = 0;      // length of current substring.     int currlen;      // maximum length substring without repeating      // characters.     int maxlen = 0;      // starting index of maximum length substring.     int start;      // Hash Map to store last occurrence of each     // already visited character.     unordered_map<char, int> pos;      // Last occurrence of first character is index 0;     pos[str[0]] = 0;      for (i = 1; i < n; i++) {          // If this character is not present in hash,         // then this is first occurrence of this         // character, store this in hash.         if (pos.find(str[i]) == pos.end())             pos[str[i]] = i;          else {             // If this character is present in hash then             // this character has previous occurrence,             // check if that occurrence is before or after             // starting point of current substring.             if (pos[str[i]] >= st) {                  // find length of current substring and                 // update maxlen and start accordingly.                 currlen = i - st;                 if (maxlen < currlen) {                     maxlen = currlen;                     start = st;                 }                  // Next substring will start after the last                 // occurrence of current character to avoid                 // its repetition.                 st = pos[str[i]] + 1;             }              // Update last occurrence of             // current character.             pos[str[i]] = i;         }     }      // Compare length of last substring with maxlen and     // update maxlen and start accordingly.     if (maxlen < i - st) {         maxlen = i - st;         start = st;     }      // The required longest substring without     // repeating characters is from str[start]     // to str[start+maxlen-1].     return str.substr(start, maxlen); }  // Driver function int main() {     string str = "GEEKSFORGEEKS";     cout << findLongestSubstring(str);     return 0; } 
Java
// Java program to find  // and print longest substring // without repeating characters.  import java.util.*;  class GFG{  // Function to find and print longest  // substring without repeating characters.  public static String findLongestSubstring(String str)  {      int i;      int n = str.length();           // Starting point      // of current substring.      int st = 0;           // length of      // current substring.      int currlen = 0;           // maximum length      // substring without      // repeating characters.      int maxlen = 0;           // starting index of      // maximum length substring.      int start = 0;           // Hash Map to store last      // occurrence of each           // already visited character.      HashMap<Character,              Integer> pos = new HashMap<Character,                                          Integer>();           // Last occurrence of first      // character is index 0;      pos.put(str.charAt(0), 0);           for (i = 1; i < n; i++)      {         // If this character is not present in hash,          // then this is first occurrence of this          // character, store this in hash.          if (!pos.containsKey(str.charAt(i)))         {             pos.put(str.charAt(i), i);         }         else         {              // If this character is present              // in hash then this character              // has previous occurrence,              // check if that occurrence              // is before or after starting              // point of current substring.              if (pos.get(str.charAt(i)) >= st)              {                 // find length of current                  // substring and update maxlen                 // and start accordingly.                  currlen = i - st;                  if (maxlen < currlen)                  {                  maxlen = currlen;                  start = st;                  }                           // Next substring will start                  // after the last occurrence                  // of current character to avoid                  // its repetition.                  st = pos.get(str.charAt(i)) + 1;              }                       // Update last occurrence of              // current character.              pos.replace(str.charAt(i), i);         }      }           // Compare length of last      // substring with maxlen and      // update maxlen and start      // accordingly.      if (maxlen < i - st)      {          maxlen = i - st;          start = st;      }           // The required longest      // substring without      // repeating characters      // is from str[start]      // to str[start+maxlen-1].      return str.substring(start,                           start +                           maxlen);  }   // Driver Code public static void main(String[] args)  {     String str = "GEEKSFORGEEKS";     System.out.print(findLongestSubstring(str)); } }  // This code is contributed by divyeshrabadiya07 
Python
# Python3 program to find and print longest  # substring without repeating characters.   # Function to find and print longest  # substring without repeating characters.  def findLongestSubstring(string):      n = len(string)       # starting point of current substring.      st = 0      # maximum length substring without      # repeating characters.      maxlen = 0      # starting index of maximum      # length substring.      start = 0      # Hash Map to store last occurrence      # of each already visited character.      pos = {}       # Last occurrence of first     # character is index 0      pos[string[0]] = 0      for i in range(1, n):           # If this character is not present in hash,          # then this is first occurrence of this          # character, store this in hash.          if string[i] not in pos:              pos[string[i]] = i           else:             # If this character is present in hash then              # this character has previous occurrence,              # check if that occurrence is before or after              # starting point of current substring.              if pos[string[i]] >= st:                   # find length of current substring and                  # update maxlen and start accordingly.                  currlen = i - st                  if maxlen < currlen:                      maxlen = currlen                      start = st                   # Next substring will start after the last                  # occurrence of current character to avoid                  # its repetition.                  st = pos[string[i]] + 1                          # Update last occurrence of              # current character.              pos[string[i]] = i               # Compare length of last substring with maxlen      # and update maxlen and start accordingly.      if maxlen < i - st:          maxlen = i - st          start = st           # The required longest substring without      # repeating characters is from string[start]      # to string[start+maxlen-1].      return string[start : start + maxlen]   # Driver Code if __name__ == "__main__":       string = "GEEKSFORGEEKS"     print(findLongestSubstring(string))   # This code is contributed by Rituraj Jain 
C#
// C# program to find  // and print longest substring // without repeating characters.  using System; using System.Collections.Generic; class GFG{  // Function to find and  // print longest substring  // without repeating characters.  public static String findlongestSubstring(String str)  {    int i;    int n = str.Length;     // Starting point    // of current substring.    int st = 0;     // length of    // current substring.    int currlen = 0;     // maximum length    // substring without    // repeating characters.    int maxlen = 0;     // starting index of    // maximum length substring.    int start = 0;     // Hash Map to store last    // occurrence of each     // already visited character.    Dictionary<char,               int> pos = new Dictionary<char,                                         int>();    // Last occurrence of first    // character is index 0;    pos.Add(str[0], 0);     for (i = 1; i < n; i++)    {     // If this character is not present in hash,      // then this is first occurrence of this      // character, store this in hash.      if (!pos.ContainsKey(str[i]))     {       pos.Add(str[i], i);     }     else     {        // If this character is present        // in hash then this character        // has previous occurrence,        // check if that occurrence        // is before or after starting        // point of current substring.        if (pos[str[i]] >= st)        {         // find length of current          // substring and update maxlen         // and start accordingly.          currlen = i - st;          if (maxlen < currlen)          {            maxlen = currlen;            start = st;          }           // Next substring will start          // after the last occurrence          // of current character to avoid          // its repetition.          st = pos[str[i]] + 1;        }         // Update last occurrence of        // current character.        pos[str[i]] = i;     }    }     // Compare length of last    // substring with maxlen and    // update maxlen and start    // accordingly.    if (maxlen < i - st)    {      maxlen = i - st;      start = st;    }     // The required longest    // substring without    // repeating characters    // is from str[start]    // to str[start+maxlen-1].    return str.Substring(start,                          maxlen);  }   // Driver Code public static void Main(String[] args)  {   String str = "GEEKSFORGEEKS";   Console.Write(findlongestSubstring(str)); } }  // This code is contributed by shikhasingrajput  
JavaScript
<script>  // JavaScript program for the above approach  // Function to find and print longest // substring without repeating characters. function findLongestSubstring(str) {     var i;     var n = str.length;      // starting point of current substring.     var st = 0;      // length of current substring.     var currlen;      // maximum length substring without repeating      // characters.     var maxlen = 0;      // starting index of maximum length substring.     var start;      // Hash Map to store last occurrence of each     // already visited character.     var pos = new Map();      // Last occurrence of first character is index 0;     pos.set(str[0], 0);      for (var i = 1; i < n; i++) {          // If this character is not present in hash,         // then this is first occurrence of this         // character, store this in hash.         if (!pos.has(str[i]))             pos.set(str[i],i) ;          else {             // If this character is present in hash then             // this character has previous occurrence,             // check if that occurrence is before or after             // starting point of current substring.             if (pos.get(str[i]) >= st) {                  // find length of current substring and                 // update maxlen and start accordingly.                 currlen = i - st;                 if (maxlen < currlen) {                     maxlen = currlen;                     start = st;                 }                  // Next substring will start after the last                 // occurrence of current character to avoid                 // its repetition.                 st = pos.get(str[i]) + 1;             }              // Update last occurrence of             // current character.             pos.set(str[i], i);         }     }      // Compare length of last substring with maxlen and     // update maxlen and start accordingly.     if (maxlen < i - st) {         maxlen = i - st;         start = st;     }      // The required longest substring without     // repeating characters is from str[start]     // to str[start+maxlen-1].          return str.substr(start,maxlen); }  var str = "GEEKSFORGEEKS"; document.write(findLongestSubstring(str));  // This code is contributed by SoumikMondal  </script> 

Output
EKSFORG

Complexity Analysis:

  • Time Complexity: O(n) 
  • Auxiliary Space: O(n)

Another Approach:

  1. Initialize a hash set to keep track of the characters that have been visited and two variables l and r to mark the left and right ends of the current substring. Also, initialize variables maxL, maxR, and maxStr to keep track of the longest substring found so far.
  2. Iterate through the string using a while loop until the right pointer r reaches the end of the string.
  3. Check if the character s[r] is present in the hash set. If it’s not present, insert it into the hash set and move the right pointer r to the next character.
  4. If the character s[r] is already present in the hash set, it means that the current substring has repeating characters. In this case, remove the character s[l] from the hash set and move the left pointer l to the next character. Repeat this step until the character s[r] is no longer present in the hash set.
  5. Check if the length of the current substring (r – l + 1) is greater than the length of the longest substring found so far (maxStr). If it is, update maxStr to the length of the current substring, and update maxL and maxR to the left and right pointers l and r.
  6. Once the loop is finished, use the maxL and maxR indices to print the longest substring without repeating characters.

Below is the implementation of above approach:

C++
#include <iostream> #include <unordered_set> using namespace std;  void printLongestSubstring(string s) {     int n = s.size();     int l = 0, r = 0;     unordered_set<char> visited;     int maxStr = 0;     int maxL = 0, maxR = 0;     while (r < n) {         if (visited.find(s[r]) == visited.end()) {             visited.insert(s[r]);             if (r - l + 1 > maxStr) {                 maxStr = r - l + 1;                 maxL = l;                 maxR = r;             }             r++;         }         else {             visited.erase(s[l]);             l++;         }     }     for (int i = maxL; i <= maxR; i++) {         cout << s[i];     }     cout << endl; }  int main() {     string str = "GEEKSFORGEEKS";     printLongestSubstring(str);     return 0; } 
Java
import java.util.HashSet;  public class Main {   public static void printLongestSubstring(String s)   {     int n = s.length();     int l = 0, r = 0;     HashSet<Character> visited = new HashSet<>();     int maxStr = 0;     int maxL = 0, maxR = 0;     while (r < n) {       if (!visited.contains(s.charAt(r))) {         visited.add(s.charAt(r));         if (r - l + 1 > maxStr) {           maxStr = r - l + 1;           maxL = l;           maxR = r;         }         r++;       }       else {         visited.remove(s.charAt(l));         l++;       }     }     for (int i = maxL; i <= maxR; i++) {       System.out.print(s.charAt(i));     }     System.out.println();   }    public static void main(String[] args)   {     String str = "GEEKSFORGEEKS";     printLongestSubstring(str);   } }  // This code is contributed by Prajwal Kandekar 
Python
def printLongestSubstring(s: str) -> None:     n = len(s)     l, r = 0, 0     visited = set()     maxStr = 0     maxL, maxR = 0, 0     while r < n:         if s[r] not in visited:             visited.add(s[r])             if r - l + 1 > maxStr:                 maxStr = r - l + 1                 maxL, maxR = l, r             r += 1         else:             visited.remove(s[l])             l += 1     print(s[maxL:maxR+1])  str = "GEEKSFORGEEKS" printLongestSubstring(str) 
C#
using System; using System.Collections.Generic;  namespace LongestSubstring { class Program { static void printLongestSubstring(string s) { int n = s.Length; int l = 0, r = 0; HashSet<char> visited = new HashSet<char>(); int maxStr = 0; int maxL = 0, maxR = 0; while (r < n) { if (!visited.Contains(s[r])) { visited.Add(s[r]); if (r - l + 1 > maxStr) { maxStr = r - l + 1; maxL = l; maxR = r; } r++; } else { visited.Remove(s[l]); l++; } } for (int i = maxL; i <= maxR; i++) { Console.Write(s[i]); } Console.WriteLine(); }          static void Main(string[] args)     {         string str = "GEEKSFORGEEKS";         printLongestSubstring(str);         Console.ReadKey();     } }  } 
JavaScript
function printLongestSubstring(s) {     const n = s.length;     let l = 0;     let r = 0;     const visited = new Set();     let maxStr = 0;     let maxL = 0;     let maxR = 0;      while (r < n) {         // Check if the character at s[r] has not been visited         if (!visited.has(s[r])) {             visited.add(s[r]);             // Calculate the length of the current substring             if (r - l + 1 > maxStr) {                 maxStr = r - l + 1;                 maxL = l;                 maxR = r;             }             r++;         } else {             // If the character at s[r] has been visited, remove s[l] from the set             visited.delete(s[l]);             l++;         }     }      // Print the longest substring without repeating characters     let longestSubstring = '';     for (let i = maxL; i <= maxR; i++) {         longestSubstring += s[i];     }     console.log(longestSubstring); }  // Main function const str = "GEEKSFORGEEKS"; printLongestSubstring(str); 

Output
EKSFORG

Time Complexity: O(n)

Auxiliary Space: O(1)



Next Article
Count substrings with k distinct characters
author
nik1996
Improve
Article Tags :
  • DSA
  • Hash
  • Strings
Practice Tags :
  • Hash
  • Strings

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:
    12 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
  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Largest substring with same Characters
    Given a string s of size N. The task is to find the largest substring which consists of the same charactersExamples: Input : s = "abcdddddeff" Output : 5 Substring is "ddddd"Input : s = aabceebeee Output : 3 Approach : Traverse through the string from left to right. Take two variables ans and temp.
    4 min read
  • Count substrings with k distinct characters
    Given a string consisting of lowercase characters and an integer k, the task is to count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Examples: Input: s = "abc", k = 2Output: 2Explanation: Possible substrings are {"ab", "bc"} Input: s = "aba", k = 2Outp
    10 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
  • 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
  • Longest substring with k unique characters
    Given a string you need to print longest possible substring that has exactly k unique characters. If there is more than one substring of longest possible length, then print any one of them. Note:- Source(Google Interview Question). Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max subs
    13 min read
  • Count substrings with different first and last characters
    Given a string S, the task is to print the count of substrings from a given string whose first and last characters are different. Examples: Input: S = "abcab"Output: 8Explanation: There are 8 substrings having first and last characters different {ab, abc, abcab, bc, bca, ca, cab, ab}. Input: S = "ab
    10 min read
  • Longest repeating and non-overlapping substring
    Given a string s, the task is to find the longest repeating non-overlapping substring in it. In other words, find 2 identical substrings of maximum length which do not overlap. Return -1 if no such string exists. Note: Multiple Answers are possible but we have to return the substring whose first occ
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences