Sliding Window: Longest substring without repeating character

Problem Statement:

You are given a string, you need to find the length of the longest substring without repeating characters.

Example:

Input: s = "bwberty"

Output: 6

Explanation: wberty

Solution Explanation:

We will solve the problem with the help of sliding window.
We will keep extending the window from the right side, till we see the distinct characters.

When a repeated character is seen, remove the characters from the left side of the window and then simultaneously track the maximum length window.

Time Complexity: O(1)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <unordered_set>
using namespace std;


int solution(string s) 
{
	unordered_set<char> set;

	int i = 0;
	int j = 0;
	int n = s.size();
	int ans = 0;

	while( i<n && j<n)
	{
		//if the character is not present in set
		if(set.find(s[j]) == set.end())
		{
			//insert char in set
			set.insert(s[j++]); 

			//check if the new distance is longer than the current answer
			ans = max(ans, j-i); 
		}
		else
		{
			// if char is present in the set, then
			// it is a repeated char, update left side and continue with checking for substring
			set.erase(s[i++]); 
		}
	}

	return ans;
}

int main() 
{
    string s = "bwberty";
    cout << solution(s);
    return 0;
}

Output

6
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *