Algorithm : Longest Substring Without Repeating Characters

    Algorithm : Longest Substring Without Repeating Characters

Problem Statement: Given a string, find the length of the longest substring without repeating characters.  This question can be found in leetcode #3. 
   Example: if the input string is "sreenath", then the output should be: 5 
   Reason\Explanation: 
  • sre - First three characters, until the next e.  - 3
  • re. -  we move the next substring which is re until  - 2
  • since no words can be formed using starting with ee. -0 
  • enath   -  with no repeating characters. - 5 
   As you can see that the maximum number of characters is 5. 


    Logic:

    Sliding Window Technique:
    
    We have a window just like how you have a Window at home, if you want to open the window fully,       you basically slide the window to the fullest. If you have to slide so that you don't open completely, you have a choice how much you want to slide the window to. 

    Typical scenario of a sliding window technique will be: 
    • You have a left and right pointer, both set to index 0
    • You slide the window by incrementing the right pointer until a case is false. 
    • You slide the window by incrementing the left pointer until a case is true. 
    • In the above scenario, you slide(or increment ) the right pointer, till there are no duplicates.
    • You slide or (increment) the left pointer, when there are duplicates. 
    • At each step you find the maximum number(longest substring), - in the above scenario, when the case is true.        

static int LengthOfSubString(string s)
{
// Start of the window.
int startWindow = 0;
// End of the window
int endWindow = 0;
//Max Length at each step.
int maxLength = 0;
//HashSet for O(1) - Insert, Delete and search time.
//This is used to insert the characters along the way and remove the
//characters when the duplicates are found.
HashSet<Char> set = new HashSet<char>();
while(endWindow < s.Length)
{
if (!set.Contains(s[endWindow]))
{
set.Add(s[endWindow]);
maxLength = Math.Max(maxLength, endWindow - startWindow + 1);
endWindow++;
}
else
{
set.Remove(s[startWindow++]);
}
}

return maxLength;
}

static void Main(string[] args)
{
Console.WriteLine("Hello World!");

Console.WriteLine(LengthOfSubString("sreenath"));
}

//o/p: 5

Comments

Popular posts from this blog

Knowing too much is bad(in the world of OOP)

Reverse a LinkedList Algorithm

DateTime.Now in C#