7)Length of the longest substring-(sliding window | variable size)

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



c++ implementation:

    int lengthOfLongestSubstring(string a) 
    {
        int i=0;int j=0; int n=a.length();
     
        int len=0;int count=0;
        unordered_map<char,int>map;
        while(j<n)
        {
            if(map[a[j]]==1)
            {
              map[a[j]]++;
              if(map[a[j]]>1)
              count++;
            }
            else
            map[a[j]]++;
            
            if(count==0)
            {
                len=max(len,j-i+1);
            }
            else if(count>0)
            {
                while(count>0)
                {
                    map[a[i]]--;
                    if(map[a[i]]==1)
                    count--;
                    
                    i++;
                }
                
            }
            j++;
        }
        return len;
        
    }
Time Complexity: O(n) 
space Complexity: O(n) 



darkmode