Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Length of Longest sub array without repeating characters (Window Sliding) #8699

Open
wants to merge 8 commits into
base: Competitive_Programming
Choose a base branch
from
60 changes: 60 additions & 0 deletions Competitive_Programming/C++/Array/longest_sub_without_repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Length of the Longest Substring without Repeating Characters

Here we will see a program to find the length of Longest substring without repeating characters.

## Explanation
In this program we are using the concept of Window sliding i.e. Whenever we see repetition, we remove the previous occurrence and slide the window.
A loop is runniig from i=0 to n=sizeof(str).
In side this loop one more loop is running from j=i till n.
We define vector with all the value as false and keep it makin true for the characters that are visited once in the loop.
Comment on lines +5 to +9
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please explain the approach in detail with snippet examples as this is a basic problem.


## Code
``` cpp
#include <bits/stdc++.h>
using namespace std;

int Substtr(string str)
{
int n = str.size();
int result = 0;

for (int i = 0; i < n; i++) {

vector<bool> visited(256);

for (int j = i; j < n; j++) {

if (visited[str[j]] == true) // If current character is visited
break; // Break the loop

else { // Else update the result if
res = max(res, j - i + 1); // this window is larger, and mark
visited[str[j]] = true; // current character as visited.
}
}

visited[str[i]] = false; // Remove the first character of previous window
}
return result;
}

int main()
{
string str = "girlscriptwinterofcontributing";
cout << "The string used is " << str << endl;
int length =Substtr(str);
cout << "The length of the longest non-repeating "
"character substring is "
<< length;
return 0;
}

```
## Time and Space Complexity
**Time Complexity**: O(n^2)
**Space Complexity**:O(n)

## Input/Output
**Input**: s = "abcabcbb"
**Output**: 3
**Explanation**: The answer is "abc", with the length of 3.