Length of the longest substring | Practice | GeeksforGeeks

Given a string S, find the length of the longest substring without repeating characters. 

Example 1:
Input:
S = "geeksforgeeks"
Output:
7
Explanation:
Longest substring is
"eksforg".
Example 2:
Input:
S = "abdefgabef"
Output:
6
Explanation:
Longest substring are
"abdefg" , "bdefga" and "defgab".
 
Your Task:
You don't need to take input or print anything. Your task is to complete the function longestUniqueSubsttr() which takes a string S as and returns the length of the longest substring. 
 
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(K) where K is constant.
+1
aryany871in 2 hours
//Concise C++ solution  
 
int longestUniqueSubsttr(string s){              //TC-O(|S|), AS-O(26) or O(1)
       int n=s.size();       if(n==0 || n==1) return n;              vector<int>visited(26,-1); //visited array for characters       visited[s[0]-'a']=0;       int i=0,j=1,ans=1;             while(j<n){                      int curr= s[j]-'a';                      //if current character is not visited, include it in answer and mark it visited           if(visited[curr]==-1){               ans=max(ans,j-i+1);               visited[curr]=j;           }                      //if visited then reset visited array, and start with a new substring           else{               i=j=visited[curr]+1;               visited=vector<int>(26,-1); //reset visited array               visited[s[i]-'a']=i;           }                      j++;       }              return ans;      }
0
nitishmishra9372 days ago
class Solution{
   int longestUniqueSubsttr(String S){
       StringBuilder temp = new StringBuilder();
       int count = 1;
       int prevCount = 0;
       int lastIndex = -1;
       temp.append(S.charAt(0));
       for(int i = 1; i < S.length(); ++i) {
           if(!temp.toString().contains(Character.toString(S.charAt(i)))) {
               temp.append(S.charAt(i));
               ++count;
           } else {
               i = S.indexOf(S.charAt(i), lastIndex+1);
               prevCount = Math.max(count, prevCount);
               temp.setLength(0);
               count = 0;
               lastIndex = i;
           }
       }
       return Math.max(count, prevCount);
   }
}
0
kumarsurajroy36553 days ago
//User function Template for Java
class Solution{   int longestUniqueSubsttr(String S){              int n=S.length();              int res=0;              int i,j;              int arr[] = new int[128];              for(j=0,i=0;j<n;j++){           char c = S.charAt(j);                      i=Math.max(arr[c-0],i);                      res = Math.max(res,j-i+1);                      arr[c-0]=j+1;       }              return res;   }}
0
mahesh_phutane6 days ago
easiest solution in java using Set
class Solution{
    int longestUniqueSubsttr(String S){
       
        int n = S.length();
        int maxlen = Integer.MIN_VALUE;
        Set<Character> st = new HashSet<>();
        
        int i = 0,j = 0;
        while(j<S.length()){
            while( j<S.length() && !st.contains(S.charAt(j))){
                st.add(S.charAt(j));
                j+=1;
            }
            
            if(maxlen<j-i+1){
                
                maxlen = j-i;
            }
            st.remove(S.charAt(i));
            i +=1;
            
        }
        
        return maxlen;
    }
}
0
sagrikasoni1 week ago

class Solution{
    int longestUniqueSubsttr(String S){
        HashMap<Character, Integer> hs = new HashMap<Character,Integer>();
        int l =0, r =0; int maxLen =0;
        while(r<S.length()){
           if(hs.containsKey(S.charAt(r))){
               l = Math.max(l, hs.get(S.charAt(r))+1);
           }
           hs.put(S.charAt(r),r);
           maxLen = Math.max(maxLen, r-l+1);
           r++;
           
        }
        return maxLen;
    }
}
0
yashvardhansingh20192 weeks ago
//Java fast & Easy Solution
 
 int left =0,right =0;       int n = s.length();       Set<Character> set = new HashSet<>();       int max_len=0;       while(right<n){           if(!set.contains(s.charAt(right))){               set.add(s.charAt(right));               right++;               max_len = Math.max(max_len,set.size());           }else if(set.contains(s.charAt(left))){               set.remove(s.charAt(left));               left++;           }       }       return max_len;
0
mr0093 weeks ago
//what is wrong in this solution ???? for last 30 test case it is showing TLE
class Solution{   public:   int longestUniqueSubsttr(string S){       //code       int i=0;       int j=0;       int start=-1;       int currLen=0;       int maxLen=INT_MIN;       unordered_map<char,int>m;       while(j<S.size()){           char ch=S[j];           while(m.count(ch) && m[ch]>=i)           {               i=m[ch]+1;               currLen=j-i;                          }           m[ch]=j;           currLen++;           j++;              if(currLen>maxLen){           maxLen=currLen;           start=i;       }       }       return maxLen ;          }};
0
vaibhaviitj3 weeks ago
Why the below solution is giving TLE on gfg and not on Leetcode?
 
class Solution{
   public:
   int longestUniqueSubsttr(string S){
       //code
       unordered_set<char> s;
       int ans = 0;
       
       for(int st = 0, end =0; end < S.size(); ){
           if(s.find(S[end]) == s.end()){
               s.insert(S[end]); ans = max(ans, end-st+1); end++;        
           }
           else{
               s.erase(S[st]); st++;
           }
       }
       
       return ans;
   }
};
 
+2
blakepanther3 weeks ago
trying to keep it simple
class Solution{
    int longestUniqueSubsttr(String S){
        ArrayList<Character> al = new ArrayList<>();
        int i= 0, j = 0, max = 0;
        while(j < S.length() ){
            if(al.contains(S.charAt(j) ) ){
                al.remove(0 );
                i++;
            }else{
                al.add(S.charAt(j) );
                max = Math.max(max, al.size());
                j++;
            }
        }
        return max;
    }
}
0
rishikaa09064 weeks ago
C++ code .
Can someone help me identify the issue with my code on why it isn't even entering the first if statement?
 
 int longestUniqueSubsttr(string S){              unordered_map <char,bool> mp;       int n=S.size();       int count=1;       int max=INT_MIN;       for(int i=0;i<n;i++)       {           mp[S[i]]==true; //stores the count as value and array element as key.       }       for(int i=0;i<n;i++)       {                      if(S[i]!=S[i+1] and mp[S[i]]==true)           {                              count++;               // cout<<count;               mp[S[i]]=false;               if(count>max)               { max=count;}           }           if(S[i]==S[i+1] )           {               count=0;                         }       }       return max;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.