Skip to main content

Command Palette

Search for a command to run...

Longest Substring Without Repeating Characters

Published
1 min read
Longest Substring Without Repeating Characters
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Longest Substring Without Repeating Characters

https://www.geeksforgeeks.org/problems/longest-distinct-characters-in-string5848/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=bottom_sticky_on_article

Hint:

  • Use an array of size 26 to hash characters with the indexes.

  • Initially every alphabet will be 0.

  • Iterate through array and if the alphabet is new increase the count of that alphabet.

  • If at any point count of an alphabet is more that 0 then it is repeated.

Code:

int longestSubstrDistinctChars (string input)
{
    // your code here
    int n = input.size();
    int maxLen = 1;
    int ind = 0;

    vector<int> hash(26,0);
    // hash[input[0]-'a']++;
    int i = 0;

    while(i<n){
        int p = input[i]-'a';

        if(i==n-1 && hash[p]==0){
            maxLen = max(maxLen, i-ind+1);
        }
        if(hash[p]>0){
            maxLen = max(maxLen, i-ind);

            for(int j=ind;j<i;j++){
                if(input[j]==input[i]){
                    ind = j+1;
                    break;
                }
                hash[input[j]-'a'] = 0;
            }
            i++;
        }
        else{
            hash[p]++;
            i++;
        }
    }
    return maxLen;
}

DSA prep

Part 13 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Strings - Sorting Characters By Frequency

Sorting Characters By Frequency Problem Link: https://www.codingninjas.com/studio/problems/sorting-characters-by-frequency_1263699?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf&leftPanelTabValue=PROBLEM https://leetcode.com/proble...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.