Longest Distinct characters in string | Practice | GeeksforGeeks

Given a string S, find length of the longest substring with all distinct characters. 
Example 1:
Input:
S = "geeksforgeeks"
Output: 7
Explanation: "eksforg" is the longest 
substring with all distinct characters.

â€‹Example 2:
Input: 
S = "aaa"
Output: 1
Explanation: "a" is the longest substring 
with all distinct characters.


Your Task:
You don't need to read input or print anything. Your task is to complete the function longestSubstrDitinctChars() which takes the string S as input and returns the length of the longest substring with all distinct characters.

Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(K), where K is Constant.

Constraints:
1<=|S|<=105
 
0
nikhilpmsnick5 days ago
unordered_set<char> un;   int length=0;   int count=0;   for(int i=0; i<S.size();i++)   {       if(un.find(S[i])==un.end())       {           //s.push_back(S[i]);           un.insert(S[i]);           length++;       }                      else       {           if(length>count)           {               count=length;           }           un.clear();           //s.push_back(S[i]);           i=i-length;           length=0;       }   }   if(length>=count)   return length;   else   return count;
0
ayushmishra252 weeks ago
longestSubstrDistinctChars(s) {   let items = s.split(""), iteratorA=0, iteratorB=0, newStr="", maxStrLength="";      while(iteratorA !== items.length && iteratorB !== items.length){              if(!newStr.includes(items[iteratorB])){           newStr+=items[iteratorB];                      if(maxStrLength < newStr.length){           maxStrLength  = newStr.length;           }       }else{           if(maxStrLength < newStr.length){           maxStrLength  = newStr.length;            }                     iteratorB =iteratorA;           iteratorA++;              if(items.length > iteratorB)            newStr = items[iteratorB];       }                     iteratorB++;                  }      return maxStrLength;   }
0
harsh39rathod2 weeks ago
SIMPLE SOLN C++
 
int longestSubstrDistinctChars (string S){   int ans=INT_MIN;   map<char,int> m;   int st=0;   int run=0;   while(run<S.length()){       if(m[S[run]]!=0){           ans=max(ans,run-st);           while(S[st]!=S[run]){               m[S[st]]--;               st++;           }           m[S[st]]--;           st++;       }       m[S[run]]++;       run++;   }   ans=max(ans,run-st);      return ans;   }
0
ravi1010prakash1 month ago
int longestSubstrDistinctChars (string s){ vector<int>prev(256,-1); int n=s.length(); int i=0; int res=0; for(int j=0;j<n;j++) {     i=max(i,prev[s[j]]+1);     int maxend=j-i+1;     res=max(res,maxend);     prev[s[j]]=j; } return res; }
0
ravi1010prakash1 month ago
  int i=0,j=0,mx=0;   unordered_map<int,int>mp;   while(j<s.size())   {       mp[s[j]]++;       if(mp.size()>j-i+1)       j++;       else if( mp.size()==j-i+1)       {           mx=max(mx,j-i+1);           j++;                  }       else if(mp.size()<j-i+1)       {           while(mp.size()<j-i+1)           {               mp[s[i]]--;               if(mp[s[i]]==0)               mp.erase(s[i]);               i++;           }j++;                  }          }return mx;
0
geeky_kuldeep1 month ago
JS Solution

class Solution {
 longestSubstrDistinctChars(s) {
   let max = Number.MIN_VALUE;
   let sub = {};
   let count = 0;
   let start = 0;
   let i = 0;
   while (i < s.length) {
       if (sub[s[i]] >= 1) {
           sub = {};
           i = start + 1;
           sub[s[i]] = 1;
           start = i;
           count = 1;
       } else {
           sub[s[i]] = 1;
           count++;
       }
       if (count > max) {
           max = count;
       }
       i++;
   }
   return max;
 }
}
+1
ayushsunariya4581 month ago
int longestSubstrDistinctChars (string s)
{
    // your code here
    vector<int>res(26,0);
    int j=0,len=0;
    for(int i=0;i<s.size();i++){
        res[s[i]-'a']++;
        while(res[s[i]-'a']>1){
            res[s[j++]-'a']--;
        }
        len=max(len,i-j+1);
    }
    return len;
}
0
tirtha19025681 month ago
class Solution{
   static int longestSubstrDistinctChars(String S){
       HashMap<Character,Integer>map = new HashMap<>();
       int i = 0;
       int j = 0;
       int max = Integer.MIN_VALUE;
       
       while(j<S.length())
       {
           char ch = S.charAt(j);
           map.put(ch,map.getOrDefault(ch,0)+1 );
           
           if(map.size() == j-i+1){
               max = Math.max(max,j-i+1);
           }
           
           // remove elements if repeating elements found
           if(map.size() < j-i+1)
           {
               while(map.size() < j-i+1){
                   char ci = S.charAt(i);
                   map.put(ci,map.get(ci)-1);
                   if(map.get(ci) == 0){
                       map.remove(ci);
                   }
                   i++;
               } 
           }
           
           j++;
       }
       if(max == Integer.MIN_VALUE){
           return -1;
       }
       return max;
   }
}
+1
amanasati11 month ago
Python using Sliding window technique
class Solution:

    def longestSubstrDistinctChars(self, S):
        # code here
        l=0
        i,j=0,0
        dic={}
        while j<len(S):
            if S[j] not in dic:
                dic[S[j]]=1
                l=max(l,len(dic))
            else:
                while S[i]!=S[j]:
                    del dic[S[i]]
                    i+=1
                i+=1
                dic[S[j]]=1
            j+=1
        return l
0
deepeshacharya22 months ago
Java Solution using HashMap
static int longestSubstrDistinctChars(String S){       HashMap<Character, Integer> hm = new HashMap<>();       int maxCount = 0,i,n=S.length(),countTillNow = 0;              for (i=0;i<n;i++) {           if (hm.containsKey(S.charAt(i))) {               i = hm.get(S.charAt(i));               i++;               hm.clear();               hm.put(S.charAt(i),i);               countTillNow = 1;           }           else {               countTillNow++;               hm.put(S.charAt(i),i);               if (countTillNow > maxCount)                   maxCount = countTillNow;           }       }       return maxCount;   }
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.