question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | CPP solution using brute force. | cpp-solution-using-brute-force-by-ankurk-f05p | IntuitionBrute forceApproachMake all the pairs of happy string using recursion and return the k'th (index k-1) string in vector if vector is big enough else ret | ankurkarn | NORMAL | 2025-02-19T13:25:26.356754+00:00 | 2025-02-19T13:25:26.356754+00:00 | 19 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Brute force
# Approach
<!-- Describe your approach to solving the problem. -->
Make all the pairs of happy string using recursion and return the k'th (index k-1) string in vector if vector is big enough else return empty string.
# Complexity
- Time complexity: O(2^n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(2^n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
void solve(int n, vector<string>& st, string s){
if(s.size() == n){
st.push_back(s);
return;
}
if(s.size() == 0){
solve(n, st, s+"a");
solve(n, st, s+"b");
solve(n, st, s+"c");
}else{
if(s.back() != 'a') solve(n, st, s+"a");
if(s.back() != 'b') solve(n, st, s+"b");
if(s.back() != 'c') solve(n, st, s+"c");
}
}
public:
string getHappyString(int n, int k) {
vector<string> st;
string s;
solve(n, st, s);
if(st.size() < k) return "";
return st[k-1];
}
};
``` | 2 | 0 | ['C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simplest solution with Explaination in O(N) & 100% beats | simplest-solution-with-explaination-in-o-8rd0 | IntuitionThe problem involves generating the k-th lexicographically smallest "happy string" of lengthn. A "happy string" is one that adheres to the following co | patel_jaimin | NORMAL | 2025-02-19T12:11:32.125870+00:00 | 2025-02-19T12:11:32.125870+00:00 | 117 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem involves generating the k-th lexicographically smallest "happy string" of length `n`. A "happy string" is one that adheres to the following constraints:
- The string consists only of characters `'a'`, `'b'`, and `'c'`.
- No two consecutive characters are the same.
Given the constraints, my initial intuition was to:
- Count how many possible happy strings of length `n` exist (which is `3 * 2^(n - 1)`).
- Use a divide-and-conquer approach to figure out which specific happy string corresponds to the k-th position without generating all the strings explicitly. This approach would involve breaking down the problem into blocks of happy strings that start with the same character, and progressively refining the search for the k-th string.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Total Number of Happy Strings:
- For any string of length `n`, the first character can be one of the three characters (`'a'`, `'b'`, or `'c'`). For each subsequent character, there are 2 possibilities (since no two consecutive characters can be the same).
- Thus, the total number of happy strings of length `n` is `3 * 2^(n - 1)`.
2. Divide and Conquer:
- To find the k-th happy string, we can break the problem into smaller subproblems. For each character in the string, we know how many strings start with a given character. Specifically, if the first character is `'a'`, there will be a block of happy strings that start with `'a'`, another block for `'b'`, and another for `'c'`.
- By calculating the size of each block (which is `2^(n - 1)`), we can determine which block the k-th string belongs to. Once we know the first character, we can recursively determine the subsequent characters in the string.
3. Step-by-step Procedure:
- Step 1: Calculate the total number of possible strings. If `k` exceeds this number, return an empty string because it's out of bounds.
- Step 2: For each character in the string, determine which block the k-th string falls into. This will help us select the correct character at that position.
- Step 3: Update `k` as we proceed through each block, adjusting for the number of strings that precede the k-th string in the current block.
4. Recursive Character Selection:
- Given the previous character, the next character must be different, so the choices for each subsequent character are limited based on the previous character. This ensures the string remains "happy".
5. Result Construction:
- Using the divide-and-conquer approach, we construct the string character by character until we have the complete happy string.
By following this approach, we avoid generating all possible strings explicitly and efficiently calculate the k-th happy string.
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
int total = 3 * pow(2, n - 1);
if (k > total) return "";
string ans = "";
char prev = '\0';
for (int i = 0; i < n; ++i) {
int block_size = pow(2, n - i - 1);
int block_index = (k - 1) / block_size;
if (prev == '\0') {
ans += 'a' + block_index;
} else {
ans += (prev == 'a') ? (block_index == 0 ? 'b' : 'c') :
(prev == 'b') ? (block_index == 0 ? 'a' : 'c') :
(block_index == 0 ? 'a' : 'b');
}
prev = ans.back();
k -= block_index * block_size;
}
return ans;
}
};
```
```java []
class Solution {
public String getHappyString(int n, int k) {
int total = 3 * (int) Math.pow(2, n - 1);
if (k > total) return "";
StringBuilder ans = new StringBuilder();
char prev = '\0';
for (int i = 0; i < n; i++) {
int block_size = (int) Math.pow(2, n - i - 1);
int block_index = (k - 1) / block_size;
if (prev == '\0') {
ans.append((char) ('a' + block_index));
} else {
ans.append(getChar(prev, block_index));
}
prev = ans.charAt(i);
k -= block_index * block_size;
}
return ans.toString();
}
private char getChar(char prev, int blockIndex) {
if (prev == 'a') {
return blockIndex == 0 ? 'b' : 'c';
} else if (prev == 'b') {
return blockIndex == 0 ? 'a' : 'c';
} else {
return blockIndex == 0 ? 'a' : 'b';
}
}
}
```
```javascript []
/**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getHappyString = function (n, k) {
let total = 3 * Math.pow(2, n - 1);
if (k > total) return "";
let ans = '';
let prev = '';
for (let i = 0; i < n; i++) {
let block_size = Math.pow(2, n - i - 1);
let block_index = Math.floor((k - 1) / block_size);
if (prev === '') {
ans += String.fromCharCode(97 + block_index);
} else {
ans += getChar(prev, block_index);
}
prev = ans[ans.length - 1];
k -= block_index * block_size;
}
return ans;
};
var getChar = function (prev, blockIndex) {
if (prev === 'a') {
return blockIndex === 0 ? 'b' : 'c';
} else if (prev === 'b') {
return blockIndex === 0 ? 'a' : 'c';
} else {
return blockIndex === 0 ? 'a' : 'b';
}
}
```
```typescript []
function getHappyString(n: number, k: number): string {
let total = 3 * Math.pow(2, n - 1);
if (k > total) return "";
let ans = '';
let prev = '';
for (let i = 0; i < n; i++) {
let block_size = Math.pow(2, n - i - 1);
let block_index = Math.floor((k - 1) / block_size);
if (prev === '') {
ans += String.fromCharCode(97 + block_index);
} else {
ans += getChar(prev, block_index);
}
prev = ans[ans.length - 1];
k -= block_index * block_size;
}
return ans;
};
function getChar(prev, blockIndex) {
if (prev === 'a') {
return blockIndex === 0 ? 'b' : 'c';
} else if (prev === 'b') {
return blockIndex === 0 ? 'a' : 'c';
} else {
return blockIndex === 0 ? 'a' : 'b';
}
};
```
```c []
char getChar(char prev, int block_index) {
if (prev == 'a') {
return (block_index == 0) ? 'b' : 'c';
} else if (prev == 'b') {
return (block_index == 0) ? 'a' : 'c';
} else {
return (block_index == 0) ? 'a' : 'b';
}
}
char* getHappyString(int n, int k) {
static char ans[100];
int total = 3 * (int)pow(2, n - 1);
if (k > total) return "";
int prev = '\0';
int i;
for (i = 0; i < n; i++) {
int block_size = (int)pow(2, n - i - 1);
int block_index = (k - 1) / block_size;
if (prev == '\0') {
ans[i] = 'a' + block_index;
} else {
ans[i] = getChar(prev, block_index);
}
prev = ans[i];
k -= block_index * block_size;
}
ans[i] = '\0';
return ans;
}
```
```python3 []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
total = 3 * 2**(n - 1)
if k > total:
return ""
ans = []
prev = ''
for i in range(n):
block_size = 2**(n - i - 1)
block_index = (k - 1) // block_size
if prev == '':
ans.append(chr(ord('a') + block_index))
else:
ans.append(self.getChar(prev, block_index))
prev = ans[-1]
k -= block_index * block_size
return ''.join(ans)
def getChar(self, prev: str, blockIndex: int) -> str:
if prev == 'a':
return 'b' if blockIndex == 0 else 'c'
elif prev == 'b':
return 'a' if blockIndex == 0 else 'c'
else:
return 'a' if blockIndex == 0 else 'b'
```
```python []
class Solution(object):
def getHappyString(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
total = 3 * 2**(n - 1)
if k > total:
return ""
ans = []
prev = ''
for i in range(n):
block_size = 2**(n - i - 1)
block_index = (k - 1) // block_size
if prev == '':
ans.append(chr(ord('a') + block_index))
else:
ans.append(self.getChar(prev, block_index))
prev = ans[-1]
k -= block_index * block_size
return ''.join(ans)
def getChar(self, prev, blockIndex) :
if prev == 'a':
return 'b' if blockIndex == 0 else 'c'
elif prev == 'b':
return 'a' if blockIndex == 0 else 'c'
else:
return 'a' if blockIndex == 0 else 'b'
```
```Dart []
class Solution {
String getHappyString(int n, int k) {
int total = 3 * (1 << (n - 1));
if (k > total) return "";
StringBuffer ans = StringBuffer();
String prev = '';
for (int i = 0; i < n; i++) {
int block_size = 1 << (n - i - 1);
int block_index = (k - 1) ~/ block_size;
if (prev == '') {
ans.write(String.fromCharCode(97 + block_index));
} else {
ans.write(getChar(prev, block_index));
}
prev = ans.toString().substring(i, i + 1);
k -= block_index * block_size;
}
return ans.toString();
}
String getChar(String prev, int blockIndex) {
if (prev == 'a') {
return blockIndex == 0 ? 'b' : 'c';
} else if (prev == 'b') {
return blockIndex == 0 ? 'a' : 'c';
} else {
return blockIndex == 0 ? 'a' : 'b';
}
}
}
```
```golang []
func getChar(prev rune, blockIndex int) rune {
if prev == 'a' {
if blockIndex == 0 {
return 'b'
}
return 'c'
} else if prev == 'b' {
if blockIndex == 0 {
return 'a'
}
return 'c'
} else {
if blockIndex == 0 {
return 'a'
}
return 'b'
}
}
func getHappyString(n int, k int) string {
total := 3 * int(math.Pow(2, float64(n-1)))
if k > total {
return ""
}
ans := []rune{}
var prev rune
for i := 0; i < n; i++ {
blockSize := int(math.Pow(2, float64(n-i-1)))
blockIndex := (k - 1) / blockSize
if prev == 0 {
ans = append(ans, rune('a'+blockIndex))
} else {
ans = append(ans, getChar(prev, blockIndex))
}
prev = ans[len(ans)-1]
k -= blockIndex * blockSize
}
return string(ans)
}
```
```csharp []
public class Solution {
public string GetHappyString(int n, int k) {
int total = 3 * (int)Math.Pow(2, n - 1);
if (k > total) return "";
StringBuilder ans = new StringBuilder();
char prev = '\0';
for (int i = 0; i < n; i++) {
int block_size = (int)Math.Pow(2, n - i - 1);
int block_index = (k - 1) / block_size;
if (prev == '\0') {
ans.Append((char)('a' + block_index));
} else {
ans.Append(GetChar(prev, block_index));
}
prev = ans[ans.Length - 1];
k -= block_index * block_size;
}
return ans.ToString();
}
private char GetChar(char prev, int blockIndex) {
if (prev == 'a') {
return blockIndex == 0 ? 'b' : 'c';
} else if (prev == 'b') {
return blockIndex == 0 ? 'a' : 'c';
} else {
return blockIndex == 0 ? 'a' : 'b';
}
}
}
```

| 2 | 0 | ['C', 'Python', 'C++', 'Java', 'Go', 'TypeScript', 'Python3', 'JavaScript', 'C#', 'Dart'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Most Optimal Approach TC- O(n) | most-optimal-approach-tc-on-by-aayushaga-vm79 | IntuitionImagine you’re building a string step by step, and at each step, you have to choose the next character (a,b, orc) while following two rules:
You can’t | AayushAgarwal001 | NORMAL | 2025-02-19T10:43:19.454237+00:00 | 2025-02-19T10:43:19.454237+00:00 | 47 | false |
# Intuition
Imagine you’re building a string step by step, and at each step, you have to choose the next character (`a`, `b`, or `c`) while following two rules:
1. You can’t repeat the same character twice in a row.
2. The strings must be in **alphabetical order** (like a dictionary).
The trick is that you don’t need to build all possible strings. Instead, you can **jump directly to the $ k $-th string** by dividing the problem into smaller groups.
---
# Approach
Think of it like climbing stairs:
1. At each step, decide which character (`a`, `b`, or `c`) to add based on where $ k $ falls.
2. After choosing a character, update $ k $ to focus only on the remaining part of the string.
3. Repeat this process until the string is complete.
---
# Example Walkthrough
Let’s say $ n = 3 $ (length of the string) and $ k = 9 $ (we want the 9th string).
### Step 1: Total Strings
For $ n = 3 $, the total number of happy strings is:
$$
\text{Total} = 3 \cdot 2^{n-1} = 3 \cdot 4 = 12
$$
So there are 12 happy strings in total.
### Step 2: Group by First Character
The strings are grouped by their first character:
- Strings starting with `a`: $ 1 $ to $ 4 $
- Strings starting with `b`: $ 5 $ to $ 8 $
- Strings starting with `c`: $ 9 $ to $ 12 $
Since $ k = 9 $, the first character is **`c`**.
---
### Step 3: Focus on Remaining Characters
Now we know the string starts with `c`. We need to find the **1st string** in the group of strings starting with `c` (because $ k = 9 $ is the 1st string in this group).
#### Remaining Characters:
After `c`, the next character can only be `a` or `b` (no repeats). These are divided into two groups:
- Strings starting with `ca`: $ 1 $ to $ 2 $
- Strings starting with `cb`: $ 3 $ to $ 4 $
Since $ k = 1 $ (after adjusting for the previous group), the next character is **`a`**.
---
### Step 4: Final Character
Now the string starts with `ca`. For the last character, the options are:
- Strings ending with `cab`
- Strings ending with `cac`
Since $ k = 1 $, the final character is **`b`**.
---
### Final Answer:
The 9th happy string is:
$$
\boxed{"cab"}
$$
---
# Complexity
- **Time Complexity**: $ O(n) $
- We make one decision per character, so the time grows linearly with $ n $.
- **Space Complexity**: $ O(n) $
- We store the result string, which has length $ n $.
---
# Code
Here’s the code in simple terms:
```cpp
class Solution {
public:
string getHappyString(int n, int k) {
int total = 3 * (1 << (n - 1));
if (k > total) return "";
string result = "";
int groupSize = 1 << (n - 1);
char options[3] = {'a', 'b', 'c'};
while (n > 0) {
int groupIndex = (k - 1) / groupSize;
char currentChar = options[groupIndex];
result += currentChar;
k -= groupIndex * groupSize;
if (currentChar == 'a') {
options[0] = 'b';
options[1] = 'c';
} else if (currentChar == 'b') {
options[0] = 'a';
options[1] = 'c';
} else {
options[0] = 'a';
options[1] = 'b';
}
groupSize /= 2;
n--;
}
return result;
}
};
```
| 2 | 0 | ['String', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | C++ Simple and Clean Backtracking Solution | c-simple-and-clean-backtracking-solution-6gkt | IntuitionThe functionbacktrackrecursively constructs all possible happy strings.If the current string reaches length n, it increments count.Once count reaches k | yehudisk | NORMAL | 2025-02-19T09:22:41.415388+00:00 | 2025-02-19T09:22:41.415388+00:00 | 5 | false | # Intuition
The function `backtrack` recursively constructs all possible happy strings.
If the current string reaches length n, it increments count.
Once count reaches k, the function stores the k-th happy string in res.
The loop ensures that no two consecutive characters are the same.
The function getHappyString initializes count and starts the recursion.
### Time Complexity:
O(3^n) in the worst case, as each position has up to 3 choices.
### Space Complexity:
O(n) for recursion depth.
# Code
```cpp []
class Solution {
public:
string res;
void backtrack(int n, int k, string curr, int& count) {
if (curr.size() == n) {
count++;
if (count == k) res = curr;
return;
}
for (int a = 'a'; a <= 'c'; a++) {
if (curr.size() == 0 || curr.back() != a) {
curr += a;
backtrack(n, k, curr, count);
curr.pop_back();
}
}
}
string getHappyString(int n, int k) {
int count = 0;
backtrack(n, k, "", count);
return res;
}
};
```
### Like it? Please upvote! | 2 | 0 | ['C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Begineer Friendly Backtracking Solution | Very easy intuition and approch | Easy to understand | begineer-friendly-backtracking-solution-86q8y | IntuitionThe problem requires generating "happy strings" of lengthn. A happy string is a string consisting of only 'a', 'b', and 'c' where no two adjacent chara | ParthTiwari01 | NORMAL | 2025-02-19T08:51:10.041683+00:00 | 2025-02-19T08:51:10.041683+00:00 | 38 | false |
# **Intuition**
The problem requires generating "happy strings" of length `n`. A happy string is a string consisting of only 'a', 'b', and 'c' where no two adjacent characters are the same.
Our goal is to generate all such strings in lexicographical order and return the `k`-th string.
---
# **Approach**
1. **Backtracking:**
- We generate all possible happy strings recursively.
- We maintain a `curr` string that is being built character by character.
- At each step, we add characters 'a', 'b', or 'c', ensuring no adjacent characters are the same.
- If `curr` reaches the required length `n`, we store it in `result`.
2. **Recursive Function (`solve`)**
- Base Case: If `curr.length() == n`, add `curr` to `result` and return.
- Iterate over `i = 0` to `2`, corresponding to 'a', 'b', and 'c'.
- If `curr` is empty, we can add any character.
- Otherwise, ensure the last character is not the same as the one we are about to add.
- Use recursion to generate the next character and backtrack after exploring all options.
3. **Main Function (`getHappyString`)**
- Call `solve` to generate all happy strings.
- If `result.size() < k`, return an empty string (invalid case).
- Return `result[k - 1]` (zero-based indexing).
---
# **Complexity Analysis**
- **Time Complexity:**
- Each character has 2 choices (except the first one, which has 3 choices).
- The total number of happy strings of length `n` is at most `3 * 2^(n-1)`.
- So, the time complexity is **O(3 * 2^(n-1))**, which simplifies to **O(2^n)**.
- **Space Complexity:**
- We store all happy strings in `result`, which requires **O(2^n)** space.
- The recursion stack takes **O(n)** space.
- So, the overall space complexity is **O(2^n)**.
---
# **Code**
```cpp
class Solution {
public:
// Recursive function to generate happy strings
void solve(int n, string &curr, vector<string> &result) {
// Base case: If the current string reaches the required length
if(curr.length() == n) {
result.push_back(curr);
return;
}
// Iterate through 'a', 'b', 'c'
for(int i = 0; i < 3; i++) {
// If the string is empty, we can add any character
if(curr.empty()) {
curr.push_back(i + 'a');
solve(n, curr, result); // Recur for the next character
curr.pop_back(); // Backtrack
}
// Ensure no two adjacent characters are the same
else if(curr.back() == (i + 'a')) {
continue;
}
else {
curr.push_back(i + 'a');
solve(n, curr, result);
curr.pop_back();
}
}
}
// Function to return the k-th happy string
string getHappyString(int n, int k) {
vector<string> result; // Store all valid happy strings
string curr;
solve(n, curr, result);
// If k is larger than the number of happy strings, return empty string
if(result.size() < k) return "";
return result[k - 1]; // Return k-th happy string (1-based index)
}
};
```
---
# **Example Walkthrough**
### **Example 1**
**Input:**
```cpp
n = 3, k = 4
```
**Step-by-step Happy String Generation:**
```
1. "aba"
2. "abc"
3. "aca"
4. "acb"
5. "bab"
6. "bac"
7. "bca"
8. "bcb"
9. "cab"
10. "cac"
11. "cba"
12. "cbc"
```
**Output:**
```cpp
"acb" // The 4th happy string
```
---
# **Key Takeaways**
✅ Uses backtracking to generate happy strings.
✅ Ensures adjacent characters are not the same.
✅ Stores all valid strings in lexicographical order.
✅ Uses zero-based indexing for returning the correct answer.
| 2 | 0 | ['String', 'Backtracking', 'C++'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✅ Beat 100% runtime, O(N x K) Time, O(N) Space| no recursion, solution generating next permutation | beat-100-runtime-on-x-k-time-on-space-wi-t69c | IntuitionWe need kth lexicographical happy string of length n.If we know the first string (smallest lexicographically) and a way to generate the next lexicograp | astrothames | NORMAL | 2025-02-19T08:39:56.339343+00:00 | 2025-02-20T05:11:29.332448+00:00 | 26 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We need kth lexicographical happy string of length n.
If we know the first string (smallest lexicographically) and a way to generate the next lexicographical happy string from the given string, we would simply use it k-1 times to get kth lexicographical happy string.
An edge case of k being higher than the number of all possible happy strings of length n would have to be handled too.
# Approach
<!-- Describe your approach to solving the problem. -->
The constraint of happy string is that consecutive letters cant be same (str[i] != str[i+1]). So we will need atleast 2 different letters to satisfy this condition. If we place the smallest 2 available letters alternately, that would satisfy the condition and also be the smallest lexicographical string as we are the using the smallest letters available. Thus 'ababab...', this sequence of length n would be smallest lexicographical happy string.
Now, we have to find a logic to generate the next permutation of happy string.
For this, we can start from the end of string and check the first letter we can increase. We increase that and make the part of string which is right to it the smallest (i.e. 'abab').
The increase could be done at ith position if following conditions are met:
- The letter is 'a' or 'b', we can increase 'a' to 'b'/'c' and 'b' to 'c', but can't increase 'c' to 'd' as happy string only consists of 'a','b','c'.
- The i-1 th letter is not the same as the new letter we are going to put.
If we reach index 0 without doing any change, we change letter at 0th position to 'b' or 'c' if its 'a' and back to 'a' if its 'c'.
You can see it as first finding the position 'it' where the change would be done. Then we make the string to the right side of that point as 'ababab' (or 'bababa' in case the letter at it position is 'a').
Iterate this k-1 times and in between if we get the starting string again, return "", as it means we have reached the end of possible permutations and still not reached k.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(N x K), as K times we use a function to generate next permutation which is O(N)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(N) as we only store the string and modify it only.
# Code
```cpp []
class Solution {
public:
void next(string &s, int n){
int it=n-1;
for(;it>0;it--){
if(s[it]=='a'){
if(s[it-1]!='b'){
s[it]='b';
break;
}
if(s[it-1]!='c'){
s[it]='c';
break;
}
}
if(s[it]=='b'){
if(s[it-1]!='c'){
s[it]='c';
break;
}
}
}
if(it==0){
if(s[it]<'c') s[it]++;
else
s[it]='a';
}
char c= s[it] == 'a' ? 'b' : 'a';
for(int j=it+1;j<n;j++){
s[j]=c;
c = c=='a'? 'b' : 'a';
}
return;
}
string getHappyString(int n, int k) {
string s="";
char c = 'a';
for(int i=0;i<n;i++){
s.push_back(c);
c = c=='a'? 'b' : 'a';
}
string tmp=s;
for(int i=0;i<k-1;i++){
next(tmp,n);
// cout<<tmp<<endl;
if(tmp==s)
return "";
}
return tmp;
}
};
``` | 2 | 0 | ['String', 'Greedy', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Beats 100% || Simple Backtracing Code || Easily Understandable approch | beats-100-simple-backtracing-code-easily-ogmv | IntuitionA "happy string" of lengthnconsists of charactersa,b, andcsuch that no two adjacent characters are the same. To find thek-th lexicographically smallest | 717822f143 | NORMAL | 2025-02-19T08:32:40.735644+00:00 | 2025-02-19T08:32:40.735644+00:00 | 20 | false |
**Intuition**
A "happy string" of lengthnconsists of charactersa,b, andcsuch that no two adjacent characters are the same. To find thek-th lexicographically smallest happy string, we can generate all valid strings in lexicographical order and return thek-th one.
**Approach**
Userecursive backtrackingapproach to generate happy strings of lengthn.
Maintaincounter (cnt)to track the number of happy strings generated.
If the current string reaches lengthn, decrementcntand check if it is thek-th string.
Useset of allowed characters{a, b, c}and ensure no two adjacent characters are the same.
Stop recursion early once thek-th string is found to optimize performance.
Complexity
**Time Complexity:**
O(3n) in the worst case, as each position in the string has 3 choices. However, early termination optimizes this in practice.
Space Complexity:
O(n)for the recursion stack depth.
Code
**# Code**
```java []
class Solution {
Set<String> s = new TreeSet<>();
String str="";
int tot=0;
boolean b=true;
public void fun(StringBuilder sb, int c, int l) {
if (c > l)
return;
if (c == l) {
s.add(sb.toString());
if(s.size()==tot){
str=sb.toString();
b=!b;
}
}
for (char cha='a'; cha <'d'&&b; cha++) {
if (sb.length()==0||sb.charAt(sb.length() - 1) != cha) {
sb.append(cha);
fun(sb, c + 1, l);
sb.setLength(sb.length() - 1);
}
}
}
public String getHappyString(int n, int k) {
tot=k;
fun(new StringBuilder(),0,n);
return str;
}
}
``` | 2 | 0 | ['Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple Math Solution -> No Backtracking O(N) Explained | simple-math-solution-no-backtracking-on-22dwa | IntuitionThe question requires formation of specific happy strings. Instead of DFS, one can focus on simple maths solution which can perform same operation in e | Nitkapur30 | NORMAL | 2025-02-19T08:10:42.777138+00:00 | 2025-02-19T08:10:42.777138+00:00 | 24 | false | # Intuition
The question requires formation of specific happy strings. Instead of DFS, one can focus on simple maths solution which can perform same operation in equal time.
Let us consider happy strings formation :
#### Length n = 1
Happy Strings : ["a", "b", "c" ]
```Number of strings starting with a = 1```
```Number of strings starting with b = 1```
```Number of strings starting with c = 1```
```Total : 1 * 3 = 3```
#### Length n = 2
Happy Strings : ["ab", "ac", "ba", "bc", "ca", "cb"]
```Number of strings starting with : a = 2```
```Number of strings starting with b = 2```
```Number of strings starting with c = 2```
```Total : 2 * 3 = 6```
#### Length n = 3
Happy Strings : ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]
```Number of strings starting with a = 4```
```Number of strings starting with b = 4```
```Number of strings starting with c = 4```
```Total : 4 * 3 = 12```
#### Length n = 4
Happy Strings :
["abab", "abac", "abca", "abcb", "acab", "acac", "acba", "acbc",
"baba", "babc", "baca", "bacb", "bcab", "bcac", "bcba", "bcbc",
"caba", "cabc", "caca", "cacb", "cbab", "cbac", "cbca", "cbcb"]
```Number of strings starting with a = 8```
```Number of strings starting with b = 8```
```Number of strings starting with c = 8```
```Total : 8 * 3 = 24```
#### Length n = 5
Happy Strings are :
[ "ababa", "ababc", "abaca", "abacb", "abcab", "abcac", "abcba", "abcbc",
"acaba", "acabc", "acaca", "acacb", "acbab", "acbac", "acbca", "acbcb",
"babab", "babac", "babca", "babcb", "bacab", "bacac", "bacba", "bacbc",
"bcaba", "bcabc", "bcaca", "bcacb", "bcbab", "bcbac", "bcbca", "bcbcb",
"cabab", "cabac", "cabca", "cabcb", "cacab", "cacac", "cacba", "cacbc",
"cbaba", "cbabc", "cbaca", "cbacb", "cbcab", "cbcac", "cbcba", "cbcbc"]
```Number of strings starting with a = 16```
```Number of strings starting with b = 16```
```Number of strings starting with c = 16```
```Total : 16 * 3 = 48```
_______________________________________________________________________________________________
- From above results we can see grouping creates specific formula
```n=1 : elements in 1 group = 2^0 = 1```
```n=2 : elements in 1 group = 2^1 = 2```
```n=3 : elements in 1 group = 2^2 = 4```
```n=4 : elements in 1 group = 2^3 = 6```
#### Hence Final Formula :
```Elements in single group = 2^(n-1)```
```Total Elements = 3*2^(n-1)```
# Approach
- **Step 1 :** Find ```total``` using ```3*2^(n-1)```and check whether k exceeds total. If yes, return "".
- **Step 2 :** By using grouping formula ```(k-1)/2^(n-1)``` to push first element into result string.
- **Step 3 :** Build the rest of the string. Each position has two choices. Execute for loop where we divide power - > ```(2^(n-1))/2``` in each case followed by insertion into answer according to conditions.
- **Step 4 :** Update ```k %= power``` to move forward.
# Complexity
- Time complexity: O(n)
- Space complexity: O(n)
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
int total = 3 * (1 << (n - 1)); // bit maniputaltion to represent
// 2^(n-1)
k--;
// base case
if (k >= total)
return "";
string result;
int power = 1 << (n - 1);
//push initial character on basis of grouping
result.push_back('a' + (k / power));
k%= power;
for (int i = 1; i < n; i++) {
power/= 2;
char prev = result.back();
if (k / power == 0) {
result.push_back(prev == 'a' ? 'b' : 'a');
} else {
result.push_back(prev == 'c' ? 'b' : 'c');
}
k %= power;
}
return result;
}
};
``` | 2 | 0 | ['Math', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Begginner's Friendly || C++ | begginners-friendly-c-by-manish_8312-ppt1 | IntuitionThe problem requires generating lexicographically ordered "happy" strings of lengthnusing the characters'a','b', and'c', where no two adjacent characte | manish_code_fun | NORMAL | 2025-02-19T07:58:10.756827+00:00 | 2025-02-19T07:58:10.756827+00:00 | 47 | false | # Intuition
The problem requires generating lexicographically ordered "happy" strings of length `n` using the characters `'a'`, `'b'`, and `'c'`, where no two adjacent characters are the same. The goal is to find the `k`-th such string.
# Approach
1. Use **backtracking** to generate all valid happy strings of length `n`.
2. Maintain a **counter** to track the number of happy strings generated.
3. Stop recursion when the `k`-th happy string is found and store it.
4. Ensure that no adjacent characters in the string are the same.
5. Return the stored `k`-th happy string or an empty string if `k` exceeds the total number of happy strings.
# Complexity
- **Time Complexity:** \( O(3^n) \) in the worst case since each position in the string has at most three choices, but pruning reduces this.
- **Space Complexity:** \( O(n) \) due to the recursion stack depth.
# Code
```cpp []
class Solution {
public:
string kth = "";
int cnt = 0;
int flag = 1;
void solve(int n, string& ans, int k) {
if (ans.size() == n) {
cnt++;
if (cnt == k) {
kth = ans;
flag = 0;
}
return;
}
if (flag)
for (char ch = 'a'; ch <= 'c'; ch++) {
if (ans != "" && ans.back() == ch)
continue;
ans.push_back(ch);
solve(n, ans, k);
ans.pop_back();
}
}
string getHappyString(int n, int k) {
string str = "";
solve(n, str, k);
return kth;
}
};
``` | 2 | 0 | ['C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python 🐍| Easy Explanation to Understand 💡 | python-easy-explanation-to-understand-by-odsd | IntuitionThe problem requires generating ahappy stringof lengthn, where no two adjacent characters are the same.Instead of generating all possible strings and f | nxr_deen | NORMAL | 2025-02-19T07:45:22.892465+00:00 | 2025-02-19T07:45:22.892465+00:00 | 31 | false | # Intuition
The problem requires generating a **happy string** of length `n`, where no two adjacent characters are the same.
Instead of generating all possible strings and filtering invalid ones, we can use **backtracking** to construct valid happy strings directly in lexicographical order.
This allows us to stop early once we find the `k`-th happy string, making the solution efficient.
---
# Approach
1. **Backtracking with Pruning:**
- Start with an empty string and recursively append **'a', 'b', or 'c'** while ensuring no adjacent characters are the same.
- Use a **counter (`self.count`)** to track how many valid happy strings have been generated.
- Stop the recursion early once the `k`-th happy string is found to optimize performance.
2. **Early Termination:**
- As soon as we reach the `k`-th happy string, **store the result and exit recursion**.
- This avoids unnecessary computations and speeds up execution.
3. **Lexicographical Order Guarantee:**
- Since we iterate in the order `"abc"`, the first string we construct is already the lexicographically smallest possible.
---
# Complexity
- **Time Complexity:**
- **Worst Case:** \( O(3^n) \) (if `k` is large and we have to generate many strings).
- **Optimized Case:** \( O(k) \) (since we terminate early when `k`-th happy string is found).
- This is significantly **faster** than generating all happy strings and then indexing the `k`-th one.
- **Space Complexity:**
- **Recursive Stack:** \( O(n) \) (maximum depth of recursion).
- **Optimized Approach:** Uses **constant extra space** \( O(1) \) (since we don’t store all valid strings, only a counter and result string).
---
This approach ensures we **efficiently find the k-th happy string without unnecessary computations**, making it highly optimized for large `n`. 🚀
# Code
```python []
class Solution(object):
def getHappyString(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
def backtrack(s):
if len(s) == n:
self.count += 1
if self.count == k:
self.result = s
return
for c in "abc":
if not s or s[-1] != c: # Ensure no adjacent characters are the same
backtrack(s + c)
if self.result: # Stop early if we found the k-th string
return
self.count = 0
self.result = ""
backtrack("")
return self.result
``` | 2 | 0 | ['String', 'Backtracking', 'Python'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Kotlin. Beats 100% (1 ms). Simple DFS | kotlin-beats-100-1-ms-simple-dfs-by-mobd-whgc | Code | mobdev778 | NORMAL | 2025-02-19T07:42:00.048647+00:00 | 2025-02-19T07:42:00.048647+00:00 | 35 | false | 
# Code
```kotlin []
class Solution {
var k = 0
fun getHappyString(n: Int, k: Int): String {
val chars = CharArray(n)
this.k = k
if (dfs(chars, 0, ' ')) return String(chars, 0, chars.size)
return ""
}
private fun dfs(chars: CharArray, index: Int, last: Char): Boolean {
if (chars.size == index) {
k--
return k == 0
}
for (c in 'a'..'c') {
if (c != last) {
chars[index] = c
if (dfs(chars, index + 1, c) == true) return true
}
}
return false
}
}
``` | 2 | 0 | ['Kotlin'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 🚀🔥C++ | Easy Solution using Backtracking | c-easy-solution-using-backtracking-by-aa-y854 | Intuition💡The problem requires generating happy strings of length n, where:To solve this, we can recursively build all valid strings while ensuring that no two | AashutoshRaut | NORMAL | 2025-02-19T07:34:36.715947+00:00 | 2025-02-19T07:34:36.715947+00:00 | 32 | false | # Intuition💡
The problem requires generating happy strings of length n, where:
A happy string consists of only 'a', 'b', and 'c'.
No two adjacent characters should be the same.
We need to return the k-th lexicographically smallest happy string.
To solve this, we can recursively build all valid strings while ensuring that no two adjacent characters are the same. Once we generate all valid strings, we return the k-th one.
# Approach 🚀
**Step 1: Recursively Build the Strings**
1. Start with an empty string.
2. At each step, add a character ('a', 'b', or 'c') as long as it does not match the last character.
3. Continue until the string reaches length n.
**Step 2: Store Valid Strings**
1. Once a valid string of length n is formed, store it in a list.
2. Continue backtracking to explore all possible happy strings.
**Step 3: Return the k-th String**
1. Sort the generated strings lexicographically (which happens naturally in our recursive order).
2. If k is larger than the number of generated strings, return an empty string ("").
3. Otherwise, return the k-th smallest string
# Example Walkthrough:
| **Step** | **Current String** | **Next Choices** | **Recursive Call Expands To** |
|----------|--------------------|------------------|-----------------------------|
| **1** | `""` | `'a'`, `'b'`, `'c'` | `possible(n, "a")`, `possible(n, "b")`, `possible(n, "c")` |
| **2** | `"a"` | `'b'`, `'c'` | `possible(n, "ab")`, `possible(n, "ac")` |
| **3** | `"ab"` | `'a'`, `'c'` | `possible(n, "aba")`, `possible(n, "abc")` |
| **4** | `"aba"` | `'b'`, `'c'` | `possible(n, "abab")`, `possible(n, "abac")` |
| **5** | `"abab"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **6** | `"abac"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **7** | `"abc"` | `'a'`, `'b'` | `possible(n, "abca")`, `possible(n, "abcb")` |
| **8** | `"abca"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **9** | `"abcb"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **10** | `"ac"` | `'a'`, `'b'` | `possible(n, "aca")`, `possible(n, "acb")` |
| **11** | `"aca"` | `'b'`, `'c'` | `possible(n, "acab")`, `possible(n, "acac")` |
| **12** | `"acab"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **13** | `"acac"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **14** | `"acb"` | `'a'`, `'c'` | `possible(n, "acba")`, `possible(n, "acbc")` |
| **15** | `"acba"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **16** | `"acbc"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **17** | `"b"` | `'a'`, `'c'` | `possible(n, "ba")`, `possible(n, "bc")` |
| **18** | `"ba"` | `'b'`, `'c'` | `possible(n, "bab")`, `possible(n, "bac")` |
| **19** | `"bab"` | `'a'`, `'c'` | `possible(n, "baba")`, `possible(n, "babc")` |
| **20** | `"baba"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **21** | `"babc"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **22** | `"bac"` | `'a'`, `'b'` | `possible(n, "baca")`, `possible(n, "bacb")` |
| **23** | `"baca"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **24** | `"bacb"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **25** | `"bc"` | `'a'`, `'b'` | `possible(n, "bca")`, `possible(n, "bcb")` |
| **26** | `"bca"` | `'b'`, `'c'` | `possible(n, "bcab")`, `possible(n, "bcac")` |
| **27** | `"bcab"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **28** | `"bcac"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **29** | `"bcb"` | `'a'`, `'c'` | `possible(n, "bcba")`, `possible(n, "bcbc")` |
| **30** | `"bcba"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **31** | `"bcbc"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **32** | `"c"` | `'a'`, `'b'` | `possible(n, "ca")`, `possible(n, "cb")` |
| **33** | `"ca"` | `'b'`, `'c'` | `possible(n, "cab")`, `possible(n, "cac")` |
| **34** | `"cab"` | `'a'`, `'c'` | `possible(n, "caba")`, `possible(n, "cabc")` |
| **35** | `"caba"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **36** | `"cabc"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **37** | `"cac"` | `'a'`, `'b'` | `possible(n, "caca")`, `possible(n, "cacb")` |
| **38** | `"caca"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **39** | `"cacb"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **40** | `"cb"` | `'a'`, `'c'` | `possible(n, "cba")`, `possible(n, "cbc")` |
| **41** | `"cba"` | `'b'`, `'c'` | `possible(n, "cbab")`, `possible(n, "cbac")` |
| **42** | `"cbab"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **43** | `"cbac"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **44** | `"cbc"` | `'a'`, `'b'` | `possible(n, "cbca")`, `possible(n, "cbcb")` |
| **45** | `"cbca"` | ✅ **Valid (length 4)** | **Store in answer list** |
| **46** | `"cbcb"` | ✅ **Valid (length 4)** | **Store in answer list** |
# Complexity
| **Factor** 🚀 | **Analysis** 📊 |
|----------------------|-------------------------------------------------------------------------------------------|
| **Total Strings Generated** 📜 | Each character can be `'a'`, `'b'`, or `'c'`, but no consecutive characters can be the same. |
| **Number of Valid Strings** 🔢 | At each position, we have **2 choices** (except the first position, which has **3 choices**). So, the total valid strings of length `n` is: **`3 × 2^(n-1)`**. |
| **Time Complexity** ⏳ | **O(3 × 2^(n-1)) ≈ O(2^n)**, since we generate all possible valid happy strings recursively. |
| **Space Complexity** 💾 | **O(2^n)** for storing all valid happy strings in the `ans` vector. |
| **Recursive Stack Space** 📌 | **O(n)**, since at most `n` recursive calls exist in the stack at any time. |
# Code
```cpp []
class Solution {
public:
void possible(int n,string& temp,vector<string>&ans)
{
if(temp.size()==n)
{
ans.push_back(temp);
return ;
}
if(temp.size()>0)
{
if(temp[temp.size()-1]=='a')
{
temp.push_back('b');
possible(n,temp,ans);
temp.pop_back();
temp.push_back('c');
possible(n,temp,ans);
temp.pop_back();
}
else if(temp[temp.size()-1]=='b')
{
temp.push_back('a');
possible(n,temp,ans);
temp.pop_back();
temp.push_back('c');
possible(n,temp,ans);
temp.pop_back();
}
else
{
temp.push_back('a');
possible(n,temp,ans);
temp.pop_back();
temp.push_back('b');
possible(n,temp,ans);
temp.pop_back();
}
}
else
{
temp.push_back('a');
possible(n,temp,ans);
temp.pop_back();
temp.push_back('b');
possible(n,temp,ans);
temp.pop_back();
temp.push_back('c');
possible(n,temp,ans);
temp.pop_back();
}
return ;
}
string getHappyString(int n, int k) {
string temp="";
vector<string>ans;
possible(n,temp,ans);
if(k>ans.size())return "";
return ans[k-1];
}
};
``` | 2 | 0 | ['C++'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Recursive solution using Python | Beats 100% 📈📈📈 | python-solution-beats-76-of-other-soluti-7w4m | IntuitionTotal number of possible strings=3×2N−1IfK>3×2N−1return"".Approach
Create an array to store the happy strings.
There are 2 base conditions:
Length of t | dark_mortal | NORMAL | 2025-02-19T07:08:25.206434+00:00 | 2025-02-20T09:56:50.338282+00:00 | 81 | false | # Intuition
Total number of possible strings $=3\times2^{N-1}$
If $K>3\times2^{N-1}$ return `""`.
# Approach
- Create an array to store the happy strings.
- There are 2 base conditions:
- Length of the string being made $=N$.
- Length of the happy-string array $=K$.
- Get the current last character of the string and store it in a variable (say `c`).
- Loop through the list of available characters and append it to the current string if it is not equal to the current last character `c`.
# Complexity
- Time complexity: $$O(2^N)$$
- Space complexity: $$O(N\times K)$$
# Code
```python3 []
class Solution:
def __init__(self):
self.charList = ['a', 'b', 'c']
self.happyStrings = []
def hydrateArray(self, n: int, k: int, string = ""):
if len(self.happyStrings) == k: return
if len(string) == n:
self.happyStrings.append(string); return
# if len(self.happyStrings) == k: return
lastChar = ('' if string == "" else string[-1])
for i in self.charList:
if i == lastChar: continue
if not len(self.happyStrings) == k:
self.hydrateArray(n, k, string + i)
def getHappyString(self, n: int, k: int) -> str:
totalStrings = 3 << (n - 1)
if k > totalStrings: return ""
# optimization for less number of iterations
if k > (totalStrings >> 1):
self.charList = ['c', 'b', 'a']
self.hydrateArray(n, totalStrings - k + 1)
return self.happyStrings[-1]
self.hydrateArray(n, k)
return self.happyStrings[-1]
```
# Screenshot

***
| 2 | 0 | ['Bit Manipulation', 'Recursion', 'Python3'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple Java Solution🚀|| Well Explained✅|| Beginner Friendly🔥 | simple-java-solution-well-explained-begi-w45e | IntuitionThe problem requires us to generate all happy strings of length n, sort them lexicographically, and return the k-th string. Given that n is small (≤ 10 | ghumeabhi04 | NORMAL | 2025-02-19T06:54:24.592386+00:00 | 2025-02-19T06:54:24.592386+00:00 | 102 | false | # Intuition
The problem requires us to generate all happy strings of length n, sort them lexicographically, and return the k-th string. Given that n is small (≤ 10), a backtracking approach is efficient for generating all valid strings.
---
# Approach
1. Backtracking to generate happy strings:
- Use a helper function to construct strings character by character.
- Ensure that no adjacent characters are the same.
- If the string reaches length n, add it to the list.
2. Sort and retrieve the k-th string:
- The backtracking approach already generates strings in lexicographical order.
- If there are fewer than k valid strings, return an empty string.
- Otherwise, return the k-th string from the list.
---
# Complexity
- Time complexity: O(3×2^(n−1))
- Space complexity:
---
# Code
```java []
class Solution {
List<String> list = new ArrayList<>();
public String getHappyString(int n, int k) {
StringBuilder res = new StringBuilder("");
helper(n, list, res);
if(list.size() < k) return "";
return list.get(k-1);
}
public void helper(int n, List<String> list, StringBuilder sb) {
if(sb.length() == n) {
list.add(sb.toString());
return;
}
for(char ch='a'; ch<='c'; ch++) {
if(sb.length()>0 && sb.charAt(sb.length()-1) == ch) continue;
//do
sb.append(ch);
//explore
helper(n, list, sb);
//undo
sb.deleteCharAt(sb.length()-1);
}
}
}
``` | 2 | 0 | ['String', 'Backtracking', 'Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | BEATS 99.09% SOLUTIONS | JAVA | Explained With Comments !!! | beats-9909-solutions-java-explained-with-dj12 | Code | Siddharth_Bahuguna | NORMAL | 2025-02-19T06:25:43.902531+00:00 | 2025-02-19T06:25:43.902531+00:00 | 91 | false |
# Code
```java []
class Solution {
String res;
int count;
public String getHappyString(int n, int k) {
count=0;
res="";
backtrack(n,k,new StringBuilder(""));
return res;
}
public boolean backtrack(int n,int k,StringBuilder cur){
if(cur.length()==n){ //if string reached the desired length
count++;
if(count==k){
res=cur.toString(); //store Kth happy string
return true; //stop further processing
}
return false; //continue backtracking if not Kth string
}
for(char ch='a';ch<='c';ch++){ //loop through a,b,c
int len=cur.length();
if(len>0 && cur.charAt(len-1)==ch) continue; //skip if same as last character
cur.append(ch);
if(backtrack(n,k,cur)){ //rec. and stop if Kth string is found
return true;
}
cur.deleteCharAt(cur.length()-1); //backtrack by removing last element
}
return false; //if no valid string is found
}
}
``` | 2 | 0 | ['Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Backtracking with Lexicographic Ordering | backtracking-with-lexicographic-ordering-mhab | IntuitionA "happy string" is a string of length n formed using the characters {'a', 'b', 'c'}, where no two adjacent characters are the same. Since we need the | poonammalik9817 | NORMAL | 2025-02-19T06:17:03.712022+00:00 | 2025-02-19T06:17:03.712022+00:00 | 7 | false | # Intuition
A "happy string" is a string of length n formed using the characters {'a', 'b', 'c'}, where no two adjacent characters are the same. Since we need the k-th lexicographical happy string, we can use backtracking to generate them in order and return the k-th result.
# Approach
1. Use backtracking to generate all valid happy strings.
2. Maintain a list ans to store generated strings.
3. If we reach k valid strings, stop early to optimize runtime.
4. The recursion ensures:
Each character added is different from the last one.
The generation follows lexicographic order (a → b → c).
Return ans[k-1] if k strings exist; otherwise, return "".
# Complexity
- Time complexity:
1. In the worst case, we generate all happy strings of length n.
2. Each string has n choices (a, b, c), but adjacent letters must differ.
3. The count of valid happy strings is 2 * 3^(n-1) (since the first
- character has 3 choices and subsequent ones have 2).
---
The upper bound is O(3^n), but the early stopping condition (ans.size() == k) optimizes it significantly.
- Space complexity:
- The recursion depth is at most O(n).
- The answer list ans stores at most k strings.
- Overall: O(n + k).
# Code
```cpp []
class Solution {
public:
vector<string> ans;
void build(int n,int k,string s)
{
if(ans.size()==k)
{
return ;
}
else if(s.size()==n)
{
ans.push_back(s);
return;
}
for(auto charToAdd:{'a','b','c'})
{
if(s.size()==0 or s.back()!=charToAdd)
{
build(n,k,s+charToAdd);
}
}
}
string getHappyString(int n, int k) {
build(n,k,"");
if(ans.size()<k)
{
return "";
}
return ans[k-1];
}
};
``` | 2 | 0 | ['String', 'Backtracking', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple Solution || More like a brute | simple-solution-more-like-a-brute-by-kan-rp8v | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Kanishq_24je3 | NORMAL | 2025-02-19T06:07:51.437810+00:00 | 2025-02-19T06:07:51.437810+00:00 | 34 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
void rec(int n,string t,string &ans,string curr,int& k) {
if(curr.length() == n) {
k--;
if(k == 0) {
ans = curr;
}
return;
}
bool flag = false;
for(int i = 0; i<3;i++) {
if(curr.empty()) {
curr += t[i];
rec(n,t,ans,curr,k);
curr.pop_back();
}
else {
char ch = curr.back();
if(ch != t[i]) {
curr += t[i];
rec(n,t,ans,curr,k);
curr.pop_back();
}
}
}
}
public:
string getHappyString(int n, int k) {
string s = "";
string t = "abc";
string ans = "";
rec(n,t,ans,s,k);
return ans;
}
};
``` | 2 | 0 | ['Backtracking', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 🔥🔥 Go Solution || 0ms Runtime || beats 100% | go-solution-0ms-runtime-beats-100-by-sha-g7v3 | 🙏🏼 If you find this helpful please don't forget to upvote👍 🙏🏼IntuitionFirst we will check for the count of all possible happy strings. To get that we will use t | ShaliniYadav09 | NORMAL | 2025-02-19T05:08:03.768242+00:00 | 2025-02-20T11:34:41.362651+00:00 | 86 | false | ## 🙏🏼 If you find this helpful please don't forget to upvote👍 🙏🏼
# Intuition
First we will check for the count of all possible happy strings. To get that we will use the formula (3*(2^(n-1))) as for the first place the possible characters are 3 and for the rest of the poisitions are 2. If the total possible strings are less than k we return empty string, if not then we will call a recurssive function to get the happy strings.

# Approach
In happy strings generator function we will check if length of curr string is equal to n if yes we decrement k as one of the string is already generated.
We will then iterate over the characters one by one. If the character is same as the last one in currString then we skip that one and move to the next one. If not, we append it to the currString and call the recurrsion.
Once a happy string is generated, we check if it is the kth string. If yes, we return this string and if not we move to the next possible happy string.
# Complexity
- Time complexity:
O(2^n)
- Space complexity:
O(n)
# Code
```golang []
var K int
func getHappyString(n int, k int) string {
K = k
totalHappyStringsPossible := int(3 * (math.Pow(2, float64(n-1))))
if totalHappyStringsPossible < k {
return ""
}
return generateHappyStrings(n, "")
}
func generateHappyStrings(n int, currString string) string {
length := len(currString)
if length == n {
K--
return currString
}
for _, ch := range []string{"a", "b", "c"} {
lastCh := ""
if length > 0 {
lastCh = string(currString[length-1])
}
if lastCh == ch {
continue
}
happyString := generateHappyStrings(n, currString+ch)
if K == 0 {
return happyString
}
}
return ""
}
```
## 🙏🏼 If you find this helpful please don't forget to upvote👍 🙏🏼 | 2 | 0 | ['Go'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple Backtracking Solution✅✅ | simple-backtracking-solution-by-karthike-t622 | IntuitionThe problem requires generating lexicographically ordered "happy strings" of length 𝑛, where no two adjacent characters are the same. We need to find t | karthikeyan__05 | NORMAL | 2025-02-19T04:53:59.526752+00:00 | 2025-02-21T07:13:58.477271+00:00 | 16 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires generating lexicographically ordered "happy strings" of length 𝑛, where no two adjacent characters are the same. We need to find the 𝑘 -th such string.
**Key Observations:**
Lexicographical Order Generation
Since we only use 'a', 'b', and 'c', we generate strings in sorted order.
The first character can be 'a', 'b', or 'c'.
Every subsequent character must differ from the last one.
**Total Happy Strings of Length 𝑛:**
The first character has 3 choices ('a', 'b', or 'c').
Each subsequent character has 2 choices (it cannot be the same as the previous character).
Thus, the total number of happy strings of length 𝑛 is : 2×(3^(n−1))
If 𝑘 exceeds this number, the answer should be "" (empty string).
**Backtracking to Generate Strings in Order:**
We build strings character by character.
We try 'a' first, then 'b', and then 'c', ensuring lexicographical order.
Once we construct a valid happy string, we increment a counter (curr).
When curr == k, we store the result and stop further recursion.
**Why Backtracking?**
Instead of storing all happy strings and retrieving the 𝑘 - th one (which is inefficient), we generate them on the fly.
This ensures minimal memory usage and early termination when we reach the 𝑘 - th string.
# Approach
<!-- Describe your approach to solving the problem. -->
The problem requires finding the 𝑘-th lexicographically smallest "happy" string of length 𝑛. A happy string is a string made up of characters 'a', 'b', and 'c' such that no two adjacent characters are the same.
This solution uses backtracking to generate happy strings in lexicographical order. The main idea is:
1 . Start with a placeholder character 'x' to ensure that the first character can be any of 'a', 'b', or 'c'.
2 . Recursively generate strings by appending 'a', 'b', or 'c' (ensuring that no two adjacent characters are the same).
3 . When a valid happy string of length 𝑛 is formed, increment a counter (curr).
4 . If curr reaches 𝑘, store the result and stop further recursion.
5 . If all possible happy strings are generated and 𝑘 is greater than the total number of happy strings, return an empty string.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
2×3^(n−1)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n)
# Code
```java []
class Solution {
String ans = "";
int curr = 0;
public String getHappyString(int n, int k) {
StringBuilder sb = new StringBuilder();
sb.append("x");
backtrack(n, k, sb);
return ans;
}
public boolean backtrack(int n, int k, StringBuilder sb) {
if(sb.length() == n + 1) {
curr++;
if(curr == k) {
sb.deleteCharAt(0);
ans = sb.toString();
return true;
}
return false;
}
if(sb.charAt(sb.length() - 1) != 'a') {
sb.append('a');
if(backtrack(n, k, sb)) {
return true;
}
sb.deleteCharAt(sb.length() - 1);
}
if(sb.charAt(sb.length() - 1) != 'b') {
sb.append('b');
if(backtrack(n, k, sb)) {
return true;
}
sb.deleteCharAt(sb.length() - 1);
}
if(sb.charAt(sb.length() - 1) != 'c') {
sb.append('c');
if(backtrack(n, k, sb)) {
return true;
}
sb.deleteCharAt(sb.length() - 1);
}
return false;
}
}
``` | 2 | 0 | ['Backtracking', 'Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✅✅Beginner Friendly Easy solution || c++ python3 java || TC :O(n) SC :O(1) || 🔥Beats 100%🔥 | beginner-friendly-easy-solution-c-python-62iw | IntuitionApproachComplexity
Time complexity: O(n)
Space complexity: O(1)
Code | HrsilmalanI | NORMAL | 2025-02-19T04:50:28.829126+00:00 | 2025-02-19T04:55:37.281448+00:00 | 23 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
string ans;
int tot=pow(2,n-1);
if(tot*3<k) return "";
int p1=tot,p2=tot*2;
if(k<=p1){
ans.push_back('a');
}
else if(k>p2){
ans.push_back('c');
k-=p2;
}
else{
ans.push_back('b');
k-=p1;
}
while(ans.size()<n){
int mid=tot/2;
if(k<=mid){
//find smallest haracter not equal to last character of string ans.
if(ans.back()=='a'){
ans.push_back('b');
}
else ans.push_back('a');
}
else{
//find second smallest haracter not equal to last character of string ans.
if(ans.back()=='c'){
ans.push_back('b');
}
else ans.push_back('c');
k-=mid;
}
tot/=2;
}
return ans;
}
};
```
```python []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
ans = []
tot = 2 ** (n - 1)
if tot * 3 < k:
return ""
p1, p2 = tot, tot * 2
if k <= p1:
ans.append('a')
elif k > p2:
ans.append('c')
k -= p2
else:
ans.append('b')
k -= p1
while len(ans) < n:
mid = tot // 2
if k <= mid:
ans.append('b' if ans[-1] == 'a' else 'a')
else:
ans.append('b' if ans[-1] == 'c' else 'c')
k -= mid
tot //= 2
return "".join(ans)
```
```java []
class Solution {
public String getHappyString(int n, int k) {
StringBuilder ans = new StringBuilder();
int tot = (int) Math.pow(2, n - 1);
if (tot * 3 < k) return "";
int p1 = tot, p2 = tot * 2;
if (k <= p1) {
ans.append('a');
} else if (k > p2) {
ans.append('c');
k -= p2;
} else {
ans.append('b');
k -= p1;
}
while (ans.length() < n) {
int mid = tot / 2;
if (k <= mid) {
ans.append(ans.charAt(ans.length() - 1) == 'a' ? 'b' : 'a');
} else {
ans.append(ans.charAt(ans.length() - 1) == 'c' ? 'b' : 'c');
k -= mid;
}
tot /= 2;
}
return ans.toString();
}
}
```
| 2 | 1 | ['String', 'Binary Search', 'Combinatorics', 'C++', 'Java', 'Python3'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Java Faster than 100% | Greedy approach | java-faster-than-100-greedy-approach-by-3kxsm | IntuitionEliminate unwanted string sets at each index.
If you observe starting with each letter you can make at most 2^n-1 combinations because at each index yo | Ayuj_Gupta | NORMAL | 2025-02-19T04:36:49.559899+00:00 | 2025-02-19T04:36:49.559899+00:00 | 38 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Eliminate unwanted string sets at each index.
- If you observe starting with each letter you can make at most 2^n-1 combinations because at each index you can choose from 2 options only.
- Ex if n=4 then there are atmax 8 combinations starting with a,b and c respectively. a-> (abab,abac,abca,abcb,acab,acac,acba,acbc).
- If we can somehow greedly narrow down the range of combinations at each index we can process it in linear complexity.
- Another thing to notice is at each index after first, we can check if the next char is in lower bound or upper bound because for lets say 8 combinations at 1st index, 4 of them start with b and other 4 with c. if k=5 then it belongs to upper bound. we add c and narrow our combinations for ac i.e. 4 possible combinations and reduce the k value.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(3*2)$$
# Code
```java []
class Solution {
static Map<Character, Character> lower = new HashMap<>() {
{
put('a', 'b');
put('b', 'a');
put('c', 'a');
}
};
static Map<Character, Character> upper = new HashMap<>() {
{
put('a', 'c');
put('b', 'c');
put('c', 'b');
}
};
public String getHappyString(int n, int k) {
int maxPos = (int) Math.pow(2, n - 1);
if (k > 3 * maxPos) {
return "";
}
int st = k / maxPos - (k % maxPos == 0 ? 1 : 0);
k %= maxPos;
StringBuilder sb = new StringBuilder();
sb.append((char)(st+'a'));
char last = (char)(st+'a');
while (maxPos != 1) {
maxPos /= 2;
if (k > maxPos || k == 0) {
last = upper.get(last);
} else {
last = lower.get(last);
}
k %= maxPos;
sb.append(last);
}
return sb.toString();
}
}
``` | 2 | 0 | ['Greedy', 'Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Easy Java Solution (Backtracking) | easy-java-solution-backtracking-by-joesh-2mdi | Intuition
A happy string is a string where no two adjacent characters are the same, and it consists of only the letters 'a', 'b', and 'c'. The task is to find t | joesharon | NORMAL | 2025-02-19T04:36:11.005939+00:00 | 2025-02-19T04:36:11.005939+00:00 | 82 | false | # Intuition
- A happy string is a string where no two adjacent characters are the same, and it consists of only the letters 'a', 'b', and 'c'. The task is to find the k-th lexicographically smallest happy string of length n.
- The natural approach is to generate all possible happy strings recursively, ensuring that adjacent characters are different. Once we have all valid strings, we return the k-th string.
# Approach
- Use backtracking to generate all possible happy strings of length n.
Maintain a list w to store the generated strings.
**- Use recursion:**
- If we reach length n, add the string to the list.
- Otherwise, try adding 'a', 'b', or 'c' to the string, ensuring that no two adjacent characters are the same.
- Stop recursion early if we have found k strings (optimization).
- If k is greater than the number of generated strings, return an empty string ("").
- Otherwise, return the k-th happy string.
# Complexity
**- Time complexity:**
- There are at most 𝑂(2^𝑛) valid happy strings.
- Since we generate and store these strings in a list, the worst-case time complexity is: 𝑂(2^𝑛)
**- Space complexity:**
- The recursion depth is at most O(n).
- The list w stores all valid happy strings, which is at most O(2^n).
- The StringBuilder r takes O(n) space.
- Overall, the worst-case space complexity is: O(2^n).
# Code
```java []
class Solution {
public void h(int n,int k,StringBuilder r,ArrayList<String> w)
{
if(w.size()==k)
{
return;
}
if(r.length()==n)
{
w.add(r.toString());
return;
}
char[] d={'a','b','c'};
for(char i:d)
{
if(r.length()==0||r.charAt(r.length()-1)!=i)
{
r.append(i);
h(n,k,r,w);
r.deleteCharAt(r.length()-1);
}
}
}
public String getHappyString(int n, int k) {
StringBuilder r=new StringBuilder();
ArrayList<String> w=new ArrayList<>();
//w->list to store combinations
h(n,k,r,w);
if(k>w.size())
return "";
return w.get(w.size()-1);
}
}
``` | 2 | 0 | ['String', 'Backtracking', 'Recursion', 'Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Beginner friendly || Beats 100% || Easy to Understand 🔥 | beginner-friendly-beats-100-easy-to-unde-u6af | IntuitionThe problem requires generating lexicographically ordered happy strings of length n using charactersa,b, andc, where no two adjacent characters are the | omkarsalunkhe3597 | NORMAL | 2025-02-19T04:26:40.832000+00:00 | 2025-02-19T04:26:40.832000+00:00 | 41 | false | # Intuition
The problem requires generating lexicographically ordered happy strings of length n using characters `a`, `b`, and `c`, where no two adjacent characters are the same. We need to find the `k-th` such string.
# Approach
We use a recursive backtracking approach to generate happy strings of length n.
1. Start with an empty string and recursively append `a`, `b`, or `c` while ensuring no two consecutive characters are the same.
2. Maintain a `count` of valid happy strings generated.
3. Once we reach the k-th happy string, we store it in ans and stop further recursion.
4. If k happy strings exist, return the stored string; otherwise, return an empty string.
# Complexity
- Time complexity: $$O(3^n)$$ (in the worst case, we generate all possible strings of length n)
- Space complexity: $$O(n)$$ (recursion depth for backtracking)
# Code
```cpp []
class Solution {
public:
int count; string ans;
bool findHappyString(int n,int k,string str)
{
if(str.length() == n){
count++;
if(count == k){
ans=str;return true;
}
return false;
}
for(char ch:{'a','b','c'})
{
if(str.empty() || str.back() != ch){
bool isFound=findHappyString(n,k,str+ch);
if(isFound)return true;
}
}
return false;
}
string getHappyString(int n, int k) {
count=0;
findHappyString(n,k,"");
return ans;
}
};
``` | 2 | 0 | ['String', 'Backtracking', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | My kotlin solution with time O(n) and space O(n) | my-kotlin-solution-with-time-on-and-spac-0rkw | One idea is to generate the happy strings in order up to the kth one and return it. However, a better way is to use the knowledge of permutations and decide the | hj-core | NORMAL | 2025-02-19T04:25:31.108638+00:00 | 2025-02-19T14:15:11.433034+00:00 | 73 | false | One idea is to generate the happy strings in order up to the kth one and return it. However, a better way is to use the knowledge of permutations and decide the characters one by one. Here are some suggestions to understand the idea:
1. Understand that the maximum k is 3 * 2^(n-1).
2. Understand how to choose the first character based on the values of k and n.
3. Apply point 2 to find the remaining characters one by one.
Below are my implementations,
```kotlin []
class Solution {
// Complexity:
// Time O(n) and Space O(n), treating the size of char set as constant.
fun getHappyString(
n: Int,
k: Int,
): String {
if (maxK(n) < k) {
return ""
}
val chars = "abc"
val result = StringBuilder()
var cnt = 0
var prev = chars.length
for (i in 1..n) {
val p = 1 shl (n - i) // The number of valid permutations by (n-i) chars
var q = (k - cnt - 1) / p
cnt += p * q
if (prev <= q) {
q++
}
result.append(chars[q])
prev = q
}
return result.toString()
}
private fun maxK(n: Int): Int {
require(n < 31) { "`n` will overflow Int" }
return 3 * (1 shl (n - 1))
}
}
```
```golang []
// Complexity:
// Time O(n) and Space O(n), treating the size of char set as constant.
func getHappyString(n int, k int) string {
if maxK(n) < k {
return ""
}
chars := "abc"
result := strings.Builder{}
cnt := 0
prev := len(chars)
for i := 1; i <= n; i++ {
p := 1 << (n - i) // The number of valid permutations by (n-i) chars
q := (k - cnt - 1) / p
cnt += p * q
if prev <= q {
q++
}
result.WriteByte(chars[q])
prev = q
}
return result.String()
}
func maxK(n int) int {
return 3 * (1 << (n - 1))
}
``` | 2 | 0 | ['Go', 'Kotlin'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Easy code in java, must try | easy-code-in-java-must-try-by-notaditya0-932e | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | NotAditya09 | NORMAL | 2025-02-19T04:09:25.356361+00:00 | 2025-02-19T04:09:25.356361+00:00 | 97 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public String getHappyString(int n, int k) {
Map<Character, String> nextLetters = Map.of('a', "bc", 'b', "ac", 'c', "ab");
Queue<String> q = new ArrayDeque<>(List.of("a", "b", "c"));
while (q.peek().length() != n) {
final String u = q.poll();
for (final char nextLetter : nextLetters.get(u.charAt(u.length() - 1)).toCharArray())
q.offer(u + nextLetter);
}
if (q.size() < k)
return "";
for (int i = 0; i < k - 1; ++i)
q.poll();
return q.poll();
}
}
``` | 2 | 0 | ['Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | A Backtracking Approach | 100% beats in time complexity | C++ | a-backtracking-approach-100-beats-in-tim-quqb | Intuition
A happy string is defined as a string consisting solely of the characters 'a', 'b', and 'c', with the additional constraint that no two adjacent chara | Mohamed_Hamdan_A | NORMAL | 2025-02-19T03:50:57.801158+00:00 | 2025-02-19T03:50:57.801158+00:00 | 13 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
- A happy string is defined as a string consisting solely of the characters 'a', 'b', and 'c', with the additional constraint that no two adjacent characters are the same. Notably, the total number of happy strings of length n is exactly
3 × 2<sup>n – 1</sup>
- since the first character can be any of three choices, while each subsequent position has exactly two valid options. This insight immediately lets us check if k is out of range. The main idea is to generate these strings in lexicographical order using a backtracking (recursive) approach and count until we hit the kth valid string.
# Approach
<!-- Describe your approach to solving the problem. -->
1. ### Recursive Backtracking:
The code uses a lambda function (or helper function) to recursively build the string one character at a time. At each recursion step:
- A loop iterates through the characters in "abc".
- A character is added only if it does not match the previous character (thus ensuring the happy string property).
2. ### Counting and Early Termination:
When a valid string of length n is built, a global counter is incremented. If the counter equals k, the recursion terminates early and the current string is returned immediately.
3. ### Result Construction:
The recursive function fills a character vector (or similar container) that is finally converted to a string when the kth happy string is found.
This approach avoids generating all possible strings (saving both time and memory) and only builds strings until the kth one is reached.
# Complexity
- Time complexity: In the worst case, you might generate up to k strings, each taking O(n) time to build, giving an average-case complexity of O(k × n). In the worst-case scenario (when k is near the total number of happy strings), it can approach O(3 × 2<sup>n – 1</sup> × n).
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: The space required is O(n) for the recursion stack and the temporary storage for the current string.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
int count=0;
vector<char> r(n,'a');
string st = "abc";
// Helper Function
function<bool(int,char)> helper = [&](int i,char c){
if(i>=n){
count+=1;
return true;
}
for(auto ch:st){
r[i]=ch;
if(ch!=c && helper(i+1,ch) && count==k) return true;
r[i]='d';
}
return false;
};
if(helper(0,'/')){
return string(r.begin(),r.end());
}
return "";
}
};
``` | 2 | 0 | ['Backtracking', 'Depth-First Search', 'C++'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | just an easy understandable solution in java using recursion | just-a-easy-understandable-solution-in-j-xzie | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | yasl1 | NORMAL | 2025-02-19T03:41:10.252782+00:00 | 2025-02-19T03:41:34.439947+00:00 | 79 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public String getHappyString(int n, int k) {
List<String> ll=new ArrayList<>();
happy(n,"",ll,0);
if(ll.size()<k){
return "";
}
return ll.get(k-1);
}
public static void happy(int n,String ans,List<String> ll,int len){
if(len==n){
ll.add(ans);
return;
}
for(char c:new char[]{'a','b','c'}){
if(ans.length()==0 || ans.charAt(ans.length()-1)!=c){
happy(n,ans+c,ll,len+1);
}
}
}
}
``` | 2 | 0 | ['String', 'Backtracking', 'Recursion', 'Java'] | 0 |
longest-substring-without-repeating-characters | ✅3 Method's || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | 3-methods-c-java-python-beginner-friendl-ck47 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind the 3 solutions is to iteratively find the longest substring witho | rahulvarma5297 | NORMAL | 2023-06-17T18:59:44.076656+00:00 | 2023-06-17T18:59:44.076673+00:00 | 526,077 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the 3 solutions is to iteratively find the longest substring without repeating characters by maintaining a sliding window approach. We use two pointers (`left` and `right`) to represent the boundaries of the current substring. As we iterate through the string, we update the pointers and adjust the window to accommodate new unique characters and eliminate repeating characters.\n\n# Approach 1 - Set\n<!-- Describe your approach to solving the problem. -->\n\n1. We use a set (`charSet`) to keep track of unique characters in the current substring.\n2. We maintain two pointers, `left` and `right`, to represent the boundaries of the current substring.\n3. The `maxLength` variable keeps track of the length of the longest substring encountered so far.\n4. We iterate through the string using the `right` pointer.\n5. If the current character is not in the set (`charSet`), it means we have a new unique character.\n6. We insert the character into the set and update the `maxLength` if necessary.\n7. If the character is already present in the set, it indicates a repeating character within the current substring.\n8. In this case, we move the `left` pointer forward, removing characters from the set until the repeating character is no longer present.\n9. We insert the current character into the set and continue the iteration.\n10. Finally, we return the `maxLength` as the length of the longest substring without repeating characters.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int n = s.length();\n int maxLength = 0;\n unordered_set<char> charSet;\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (charSet.count(s[right]) == 0) {\n charSet.insert(s[right]);\n maxLength = max(maxLength, right - left + 1);\n } else {\n while (charSet.count(s[right])) {\n charSet.erase(s[left]);\n left++;\n }\n charSet.insert(s[right]);\n }\n }\n \n return maxLength;\n }\n};\n```\n```Java []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int n = s.length();\n int maxLength = 0;\n Set<Character> charSet = new HashSet<>();\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (!charSet.contains(s.charAt(right))) {\n charSet.add(s.charAt(right));\n maxLength = Math.max(maxLength, right - left + 1);\n } else {\n while (charSet.contains(s.charAt(right))) {\n charSet.remove(s.charAt(left));\n left++;\n }\n charSet.add(s.charAt(right));\n }\n }\n \n return maxLength;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n n = len(s)\n maxLength = 0\n charSet = set()\n left = 0\n \n for right in range(n):\n if s[right] not in charSet:\n charSet.add(s[right])\n maxLength = max(maxLength, right - left + 1)\n else:\n while s[right] in charSet:\n charSet.remove(s[left])\n left += 1\n charSet.add(s[right])\n \n return maxLength\n\n```\n\n# Approach 2 - Unordered Map\n1. We improve upon the first solution by using an unordered map (`charMap`) instead of a set.\n2. The map stores characters as keys and their indices as values.\n3. We still maintain the `left` and `right` pointers and the `maxLength` variable.\n4. We iterate through the string using the `right` pointer.\n5. If the current character is not in the map or its index is less than `left`, it means it is a new unique character.\n6 We update the `charMap` with the character\'s index and update the `maxLength` if necessary.\n7. If the character is repeating within the current substring, we move the `left` pointer to the next position after the last occurrence of the character.\n8. We update the index of the current character in the `charMap` and continue the iteration.\n9. At the end, we return the `maxLength` as the length of the longest substring without repeating characters.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int n = s.length();\n int maxLength = 0;\n unordered_map<char, int> charMap;\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (charMap.count(s[right]) == 0 || charMap[s[right]] < left) {\n charMap[s[right]] = right;\n maxLength = max(maxLength, right - left + 1);\n } else {\n left = charMap[s[right]] + 1;\n charMap[s[right]] = right;\n }\n }\n \n return maxLength;\n }\n};\n```\n```Java []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int n = s.length();\n int maxLength = 0;\n Map<Character, Integer> charMap = new HashMap<>();\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (!charMap.containsKey(s.charAt(right)) || charMap.get(s.charAt(right)) < left) {\n charMap.put(s.charAt(right), right);\n maxLength = Math.max(maxLength, right - left + 1);\n } else {\n left = charMap.get(s.charAt(right)) + 1;\n charMap.put(s.charAt(right), right);\n }\n }\n \n return maxLength;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n n = len(s)\n maxLength = 0\n charMap = {}\n left = 0\n \n for right in range(n):\n if s[right] not in charMap or charMap[s[right]] < left:\n charMap[s[right]] = right\n maxLength = max(maxLength, right - left + 1)\n else:\n left = charMap[s[right]] + 1\n charMap[s[right]] = right\n \n return maxLength\n\n```\n\n# Approach 3 - Integer Array\n1. This solution uses an integer array `charIndex` to store the indices of characters.\n2. We eliminate the need for an unordered map by utilizing the array.\n3. The `maxLength`, `left`, and `right` pointers are still present.\n4. We iterate through the string using the `right` pointer.\n5. We check if the current character has occurred within the current substring by comparing its index in `charIndex` with `left`.\n6. If the character has occurred, we move the `left` pointer to the next position after the last occurrence of the character.\n7. We update the index of the current character in `charIndex`.\n8. At each step, we update the `maxLength` by calculating the length of the current substring.\n9. We continue the iteration until reaching the end of the string.\n10. Finally, we return the `maxLength` as the length of the longest substring without repeating characters.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int n = s.length();\n int maxLength = 0;\n vector<int> charIndex(128, -1);\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (charIndex[s[right]] >= left) {\n left = charIndex[s[right]] + 1;\n }\n charIndex[s[right]] = right;\n maxLength = max(maxLength, right - left + 1);\n }\n \n return maxLength;\n }\n};\n```\n```Java []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int n = s.length();\n int maxLength = 0;\n int[] charIndex = new int[128];\n Arrays.fill(charIndex, -1);\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (charIndex[s.charAt(right)] >= left) {\n left = charIndex[s.charAt(right)] + 1;\n }\n charIndex[s.charAt(right)] = right;\n maxLength = Math.max(maxLength, right - left + 1);\n }\n \n return maxLength;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n n = len(s)\n maxLength = 0\n charIndex = [-1] * 128\n left = 0\n \n for right in range(n):\n if charIndex[ord(s[right])] >= left:\n left = charIndex[ord(s[right])] + 1\n charIndex[ord(s[right])] = right\n maxLength = max(maxLength, right - left + 1)\n \n return maxLength\n\n```\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\n\n\n | 2,115 | 2 | ['Hash Table', 'String', 'C++', 'Java', 'Python3'] | 76 |
longest-substring-without-repeating-characters | 11-line simple Java solution, O(n) with explanation | 11-line-simple-java-solution-on-with-exp-ar3s | the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substr | cbmbbz | NORMAL | 2015-02-01T02:05:51+00:00 | 2018-10-25T02:01:33.610243+00:00 | 407,935 | false | the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward. \n\n public int lengthOfLongestSubstring(String s) {\n if (s.length()==0) return 0;\n HashMap<Character, Integer> map = new HashMap<Character, Integer>();\n int max=0;\n for (int i=0, j=0; i<s.length(); ++i){\n if (map.containsKey(s.charAt(i))){\n j = Math.max(j,map.get(s.charAt(i))+1);\n }\n map.put(s.charAt(i),i);\n max = Math.max(max,i-j+1);\n }\n return max;\n } | 1,914 | 25 | [] | 197 |
longest-substring-without-repeating-characters | 【Video】3 ways to solve this question - sliding window, set, hashing and the last position | video-3-ways-to-solve-this-question-slid-uupi | Solution Video⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️■ Subscribe URL
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1Subscr | niits | NORMAL | 2024-05-04T13:59:41.350430+00:00 | 2025-03-29T09:14:42.904527+00:00 | 143,475 | false | # Solution Video
https://youtu.be/n4zCTMh03_M
### ⭐️⭐️ Don't forget to subscribe to my channel! ⭐️⭐️
**■ Subscribe URL**
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
Subscribers: 3,982
Thank you for your support!
---
# Approach
We have two conditions to solve this question. The longest string should be
---
- Substring
- Without repeating characters
---
You just need to check that there are no repeated characters within a consecutive string of characters. To achieve this, you need to keep track of the characters currently forming the string. For this purpose, I considered three algorithms: one combining a sliding window and a set, and the second using a sliding window and a hash-based algorithm. The thrid is that the last position where each character was seen.
I'll explain them one by one.
# Solution 1 - Sliding Window & Set
First of all, we create
```
left = 0
max_length = 0 (returned value)
char_set = set()
```
`left` is pointer of sliding window.
`max_length` is a value we should return.
`char_set` is to keep current characters forming the longest string with the two conditions above.
We will iterate through all characters one by one and create `right pointer` of sliding window with for loop.
```
for right in range(len(s)):
```
Let's begin!
```
Input: s = "abcabcbb"
```
```
"abcabcbb"
r
l
l is left of sliding window
r is right of sliding window
```
We found `a`. Every time we check `char_set` if we have the same character or not. In this case, we don't have `a` in `char_set`, so add `a` to `char_set`.
```
char_set = {a}
```
After that, we check `max length`.
```
max_length = 0
current length = right - left + 1
```
##### Why +1?
That's because current length of string is `1` which is only `a`, so if we don't add `1`, we will calculate `0(right) - 0(left) = 0` which is wrong answer.
This happens because index number usually starts from `0` but actual count we do in daily life starts `1`. That's why we need to kind of convert an index number to a real number by adding `+1`.
Let's go back to the main point.
```
max_length = 1
```
Next, only right pointer move next. I'll speed up.
```
"abcabcbb"
lr
Do we have "b"? → No
char_set = {a, b}
max_length = 2 (right(1) - left(0) + 1)
```
Next, only right pointer move next.
```
"abcabcbb"
l r
Do we have "c"? → No
char_set = {a,b,c}
max_length = 3 (right(2) - left(0) + 1)
```
Next, only right pointer move next.
```
"abcabcbb"
l r
Do we have "a"? → Yes
```
In this case, we have duplicate number `a`, so we can't continue to expand the string. That's why it's time to move `left` to the next. And we have important point.
---
⭐️ Points
When we move `left` to `index 1`, `a` at `index 0` will be out of bounds, so we should remove `a` from `char_set`, so that we can keep unique characters forming the current string.
In this case, we use `while` loop, I'll explain why later.
---
```
"abcabcbb"
l r
- Do we have "a"? → Yes, remove "a" in char_set
char_set = {b,c}
- move left to the next
"abcabcbb"
l r
- There is no "a" in char_set, we stop while looping.
- And add crreunt "a" to char_set
char_set = {b,c,a}
max_length = 3 (right(3) - left(1) + 1)
```
Next, only right pointer move next.
```
"abcabcbb"
l r
- Do we have "b"? → Yes, remove "b" in char_set
char_set = {c,a}
- move left to the next
"abcabcbb"
l r
- There is no "b" in char_set, we stop while looping.
- And add crreunt "b" to char_set
char_set = {c,a,b}
max_length = 3 (right(4) - left(2) + 1)
```
Next, only right pointer move next.
```
"abcabcbb"
l r
- Do we have "c"? → Yes, remove "c" in char_set
char_set = {a,b}
- move left to the next
"abcabcbb"
l r
- There is no "c" in char_set, we stop while looping.
- And add crreunt "c" to char_set
char_set = {a,b,c}
max_length = 3 (right(5) - left(3) + 1)
```
Next, only right pointer move next.
```
"abcabcbb"
l r
- Do we have "b"? → Yes, remove "a" in char_set
```
Wait! Why do we have to remove `a` instead of `b`? That's because `b` is now duplicate character between `left` and `right`, so we have to remove chracters until we find `b` with `left` pointer.
---
⭐️ Points
Let's look at the string deeply.
```
"abcb"
l r
```
If we keep `a` in the string, we have to also keep the first `b` because `a` is outside of the first `b` in the string. If we want to remove the first `b`, we must remove `a` before we remove the first `b`. **This is substring.**
In the end,
```
"abcb"
lr
```
Let's look at the process.
```
"abcabcbb"
l r
- Do we have "b"? → Yes, remove "a" in char_set
char_set = {b,c}
- Move left to the next
"abcabcbb"
l r
- Do we have "b"? → Yes, remove "b" in char_set
char_set = {c}
- Move left to the next
"abcabcbb"
lr
- Do we have "b"? → No, now we stop while loop
- Add current "b" to char_set
- char_set = {c,b}
max_length = 3 > (right(6) - left(5) + 1)
```
I hope now you understand why we use while loop when remove charcters. **There is an case where we remove multiple characters.**
---
I stop rest of explanation because we will repeat the same process.
```
return 3
```
As you can see, we keep `char_set` the same as the string between left and right when we add a current character to `char_set`. That's why we can check if current character is duplicate or not.
Easy😆!
Let's see solution codes and step by step algorithm!
---
https://youtu.be/5_lYYnSsOGU
---
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
Constraints say "s consists of English letters, digits, symbols and spaces". I think we have fixed max size of characters consisting of the input string.
```python []
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left = max_length = 0
char_set = set()
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
```
```javascript []
var lengthOfLongestSubstring = function(s) {
let left = 0;
let maxLength = 0;
let charSet = new Set();
for (let right = 0; right < s.length; right++) {
while (charSet.has(s[right])) {
charSet.delete(s[left]);
left++;
}
charSet.add(s[right]);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
};
```
```java []
class Solution {
public int lengthOfLongestSubstring(String s) {
int left = 0;
int maxLength = 0;
HashSet<Character> charSet = new HashSet<>();
for (int right = 0; right < s.length(); right++) {
while (charSet.contains(s.charAt(right))) {
charSet.remove(s.charAt(left));
left++;
}
charSet.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
}
```
```C++ []
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int left = 0;
int maxLength = 0;
unordered_set<char> charSet;
for (int right = 0; right < s.length(); right++) {
while (charSet.find(s[right]) != charSet.end()) {
charSet.erase(s[left]);
left++;
}
charSet.insert(s[right]);
maxLength = max(maxLength, right - left + 1);
}
return maxLength;
}
};
```
## Step by step algorithm
1. **Initialization:**
```python
left = max_length = 0
char_set = set()
```
- `left`: Marks the start of the current substring.
- `max_length`: Tracks the length of the longest substring without repeating characters. Initialized to 0.
- `char_set`: Keeps track of unique characters encountered so far, initialized as an empty set.
2. **Iterating over the string characters:**
```python
for right in range(len(s)):
```
- `right`: Represents the end of the current substring. It moves from 0 to the end of the string.
3. **Checking for repeating characters:**
```python
while s[right] in char_set:
char_set.remove(s[left])
left += 1
```
- This loop executes when the character at the 'right' index is already in the `char_set`, meaning we have encountered a repeating character.
- It removes characters from the `char_set` and adjusts the 'left' pointer until the current character at 'right' is no longer in the `char_set`. This effectively removes the characters from the substring that are causing the repetition.
4. **Updating `char_set` and `max_length`:**
```python
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
```
- Adds the current character to `char_set` since it's unique now.
- Updates `max_length` by taking the maximum between the current `max_length` and the length of the current substring (`right - left + 1`).
5. **Returning `max_length`:**
```python
return max_length
```
- After iterating through the entire string, the function returns the maximum length of the substring without repeating characters.
---
https://youtu.be/K3MES6kEIMA
---
# Solution 2 - Sliding Window and Hashing
In solution 2, we use almost the same idea as solution 1 with Slinding Window and Hashing. In Python, we use `HashMap`.
In `HashMap`, we keep each character as a key and frequency of the characters as a value.
Every time we find a character, add `1 frequency` to `HashMap`. Since this question requires us to find the longest substring without repeating characters, so if we have more than `2 frequency` of the current character, we add `-1` to `HashMap` until we have `1 frequency` of the current character and move left pointer to the next at the same time.
After that, this is the same as solution 1. Just compare `max length`
```
max_length = max(max_length, right - left + 1)
```
Easy😄!
Let's see solution codes and step by step algorithm!
---
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
Constraints say "s consists of English letters, digits, symbols and spaces". I think we have fixed max size of characters consisting of the input string.
```python []
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_length = left = 0
count = {}
for right, c in enumerate(s):
count[c] = 1 + count.get(c, 0)
while count[c] > 1:
count[s[left]] -= 1
left += 1
max_length = max(max_length, right - left + 1)
return max_length
```
```javascript []
var lengthOfLongestSubstring = function(s) {
let maxLength = 0;
let left = 0;
let count = {};
for (let right = 0; right < s.length; right++) {
let c = s[right];
count[c] = (count[c] || 0) + 1;
while (count[c] > 1) {
count[s[left]] -= 1;
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
};
```
```java []
class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
int left = 0;
Map<Character, Integer> count = new HashMap<>();
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
count.put(c, count.getOrDefault(c, 0) + 1);
while (count.get(c) > 1) {
char leftChar = s.charAt(left);
count.put(leftChar, count.get(leftChar) - 1);
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
}
```
```C++ []
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLength = 0;
int left = 0;
unordered_map<char, int> count;
for (int right = 0; right < s.length(); right++) {
char c = s[right];
count[c] = count[c] + 1;
while (count[c] > 1) {
char leftChar = s[left];
count[leftChar] = count[leftChar] - 1;
left++;
}
maxLength = max(maxLength, right - left + 1);
}
return maxLength;
}
};
```
## Step by step algorithm
1. **Initialization:**
```python
max_length = left = 0
count = {}
```
- `max_length`: Represents the length of the longest substring without repeating characters found so far. Initialized to 0.
- `left`: Marks the start index of the current substring.
- `count`: A dictionary used to store the count of characters encountered in the current substring.
2. **Iterating Over the String:**
```python
for right, c in enumerate(s):
```
- `right`: Represents the end index of the current substring. It is updated using `enumerate(s)`, which returns both the index and the character at that index in the string.
- `c`: Represents the character at the current index.
3. **Updating the Character Count:**
```python
count[c] = 1 + count.get(c, 0)
```
- This line updates the count of the current character `c` in the `count` dictionary.
- If `c` is not present in the dictionary, it initializes its count to 1. Otherwise, it increments its count by 1.
4. **Adjusting the Left Pointer:**
```python
while count[c] > 1:
count[s[left]] -= 1
left += 1
```
- This while loop adjusts the `left` pointer as long as there are repeating characters in the current substring.
- It decreases the count of the character at index `left` and increments `left` by 1 until there are no repeating characters.
5. **Updating the Maximum Length:**
```python
max_length = max(max_length, right - left + 1)
```
- This line updates the maximum length (`max_length`) of the substring without repeating characters.
- It calculates the length of the current substring (`right - left + 1`) and compares it with the current maximum length (`max_length`). If the current substring is longer, it updates `max_length`.
6. **Returning the Result:**
```python
return max_length
```
- After iterating through the entire string, the function returns the maximum length of the substring without repeating characters.
In summary, this algorithm efficiently finds the length of the longest substring without repeating characters using two pointers (`left` and `right`) and a dictionary (`count`) to keep track of character counts. It iterates through the string once, making it a linear time complexity algorithm.
# Solution 3 - the last position where each character was seen
In the solution 3, we also iterate through all characters one by one. That is `right` pointer.
We update `left` pointer with `HashMap`. In `HashMap`, we keep each character as a key and the last position where each character was seen as a value.
Do you remember this example in solution 1?
```
"abcb"
l r
```
Let's call HashMap `last_seen`.
In this case, `last_seen` should have this
```
last_seen = {a:0, b:1, c:2}
last position of a is 0
last position of b is 1
last position of c is 2
current max length shold be 3 (= abc)
```
Now we find the second `b` at index `3`. As I explain in solution 1, we have to remove characters until we have unique characters between `left` and `right`.
`left` pointer is at index `0` and the last position where `b` was seen is index `1`, so that's why we should update `left` pointer with `1`.
One more important thing is that if we update `left` with `1`, we have `bcb` as a string which is including duplicate characters.
That's why we should update `left` pointer with `the last position + 1`.
```
left = last_seen[character(= b)] + 1
= 2
```
Then compare max length
```
max_length = max(max_length, right - left + 1)
```
Easy😄!
Let's see solution codes and step by step algorithm!
---
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
Constraints say "s consists of English letters, digits, symbols and spaces". I think we have fixed max size of characters consisting of the input string.
```python []
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
max_length = 0
left = 0
last_seen = {}
for right, c in enumerate(s):
if c in last_seen and last_seen[c] >= left:
left = last_seen[c] + 1
max_length = max(max_length, right - left + 1)
last_seen[c] = right
return max_length
```
```javascript []
var lengthOfLongestSubstring = function(s) {
let maxLength = 0;
let left = 0;
let lastSeen = {};
for (let right = 0; right < s.length; right++) {
let c = s.charAt(right);
if (c in lastSeen && lastSeen[c] >= left) {
left = lastSeen[c] + 1;
}
maxLength = Math.max(maxLength, right - left + 1);
lastSeen[c] = right;
}
return maxLength;
};
```
```java []
class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
int left = 0;
Map<Character, Integer> lastSeen = new HashMap<>();
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (lastSeen.containsKey(c) && lastSeen.get(c) >= left) {
left = lastSeen.get(c) + 1;
}
maxLength = Math.max(maxLength, right - left + 1);
lastSeen.put(c, right);
}
return maxLength;
}
}
```
```C++ []
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLength = 0;
int left = 0;
unordered_map<char, int> lastSeen;
for (int right = 0; right < s.length(); right++) {
char c = s[right];
if (lastSeen.find(c) != lastSeen.end() && lastSeen[c] >= left) {
left = lastSeen[c] + 1;
}
maxLength = max(maxLength, right - left + 1);
lastSeen[c] = right;
}
return maxLength;
}
};
```
## Step by step algorithm
1. **Initialization:**
```python
max_length = 0
left = 0
last_seen = {}
```
- `max_length`: Keeps track of the length of the longest substring without repeating characters.
- `left`: Marks the start index of the current substring.
- `last_seen`: A dictionary to store the last seen index of each character in the string.
2. **Iterating Over the String:**
```python
for right, c in enumerate(s):
```
- `right`: Represents the current index of the character `c` being processed.
- `c`: Represents the current character being processed.
3. **Checking for Repeating Characters:**
```python
if c in last_seen and last_seen[c] >= left:
left = last_seen[c] + 1
```
- If the character `c` is present in `last_seen` and its last seen index is greater than or equal to `left` (the start index of the current substring), it means that `c` is repeating within the current substring.
- In such a case, we update `left` to the index next to the last occurrence of `c`.
4. **Updating `max_length`:**
```python
max_length = max(max_length, right - left + 1)
```
- Update `max_length` with the maximum value between its current value and the length of the current substring (`right - left + 1`).
- `right - left + 1` represents the length of the current substring without repeating characters.
5. **Updating `last_seen`:**
```python
last_seen[c] = right
```
- Update the `last_seen` dictionary with the index `right` where the character `c` was last seen.
6. **Returning the Result:**
```python
return max_length
```
- After iterating through the entire string, return the maximum length of the substring without repeating characters.
---
Thank you for reading my post. Please upvote it and don't forget to subscribe to my channel!
⭐️ Subscribe URL
http://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1
https://youtu.be/HoQv7UR_NNI | 1,206 | 0 | ['Hash Table', 'Two Pointers', 'String', 'Sliding Window', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 15 |
longest-substring-without-repeating-characters | C++ code in 9 lines. | c-code-in-9-lines-by-lightmark-le6b | int lengthOfLongestSubstring(string s) {\n vector<int> dict(256, -1);\n int maxLen = 0, start = -1;\n for (int i = 0; i != s.le | lightmark | NORMAL | 2015-09-19T06:36:51+00:00 | 2018-10-23T02:36:21.517297+00:00 | 212,247 | false | int lengthOfLongestSubstring(string s) {\n vector<int> dict(256, -1);\n int maxLen = 0, start = -1;\n for (int i = 0; i != s.length(); i++) {\n if (dict[s[i]] > start)\n start = dict[s[i]];\n dict[s[i]] = i;\n maxLen = max(maxLen, i - start);\n }\n return maxLen;\n } | 1,122 | 12 | ['C++'] | 164 |
longest-substring-without-repeating-characters | [Java/C++] A reall Detailed Explanation | javac-a-reall-detailed-explanation-by-hi-c3q2 | So, the prerequisit of this problem is Sliding Window, if you know then it\'s a plus point. But, if you don\'t know don\'t worry I\'ll try to teach you.\n\nLet\ | hi-malik | NORMAL | 2022-06-10T05:34:17.651699+00:00 | 2022-06-10T05:50:45.746828+00:00 | 125,070 | false | So, the prerequisit of this problem is **Sliding Window**, if you know then it\'s a plus point. But, if you don\'t know don\'t worry I\'ll try to teach you.\n\nLet\'s understand first of all what the problem is saying!!\n```\nGiven a string s, find the length of the longest substring without repeating characters.\n```\nOkay, so from the given statement we will try to find out wether it is a **Sliding Window** problem or not>>\n\nSo, to check that out I\'m giving you a tempelate & it\'ll work in almost all of the questions of **sliding window**\n\n```\nTo, find out a sliding window problem :-\n> First thing is, we have given something like an "Array" | OR | "String"\n> Second thing is, they are talking about either "subsequence" | OR | "substring"\n> And third most thing is, either we have given a "window size i.e. k" | OR | we have to "manually find out window size" \n```\n\nNow, using above keys let\'s understand wether this problem is of a sliding window or not.\n```\n> Are they talking about, "Array" or "String" --> yes they are talking about "string" +1 point\n> Are they asking to find out "subsequence" or "substring" --> yes they are talking about "substring" +1 point\n> Do, we have given a window size --> No, we don\'t have\n\nTotal score is "2 / 3" so, it\'s a 100% sliding window problem. If your score lies from 2/3 to 3/3 that\'s a gauranteed sliding window problem \n```\n\nNow, let\'s talk about how we gonna implement sliding window in this problem, but before that I just want to tell you one more thing. There\'s exist basically 2 types of sliding window.\n1. Fix size sliding window **{means K is given}**\n\n\n2. Variable silze sliding window **{means K is not given}**\n\n**Before moving to the problem I want to give you a template which you can use in any sliding window `{Variable size}` problem**\n\n```\nwhile(j < size()){\n\n // Calculation\'s happen\'s here\n-----------------------------------------------\n if(condition < k){\n j++;\n }\n-----------------------------------------------\n\n-----------------------------------------------\n else if(condition == k){\n // ans <-- calculation\n j++;\n }\n----------------------------------------------\n\n----------------------------------------------\n else if(condition > k){\n while(condition > k){\n // remove calculation for i\n i++;\n }\n j++;\n }\n----------------------------------------------\n}\nreturn ans;\n```\n\nSo, in this problem we gonna deal with variable size sliding window. Let\'s take one example :-\n\n```\nInput: s = "abcabcbb"\nOutput: 3\n```\n\nSo, inorder to solve this, what I\'m thinking is, we should have to use one more Data Structure to store the occurence of these characters, I thing HashMap will be best to use.\n\n* Now, what I\'ll do is create 2 pointer\'s i & j initally they both start from 0\n* The j pointer will helps us to fill the array while the i pointer will helps in removing from the map {Don\'t know what I\'m talking about} just wait. You\'ll understand :)\n\n```\nLet\'s understand it visually :-\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n**Java**\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Map<Character, Integer> map = new HashMap<>();\n int i = 0;\n int j = 0;\n int max = 0;\n while(j < s.length()){\n map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0) + 1);\n if(map.size() == j - i + 1){\n max = Math.max(max, j - i + 1);\n j++;\n }\n else if(map.size() < j - i + 1){\n while(map.size() < j - i + 1){\n map.put(s.charAt(i), map.get(s.charAt(i)) - 1);\n if(map.get(s.charAt(i)) == 0) map.remove(s.charAt(i));\n i++;\n }\n j++;\n }\n }\n return max;\n }\n}\n```\n**C++**\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n if(s.length()==0)return 0; //if string of length zero comes simply return 0\n unordered_map<char,int> m; //create map to store frequency,(get to know all unique characters\n int i=0,j=0,ans=INT_MIN; \n while(j<s.length()) \n {\n m[s[j]]++; //increase the frequency of the element as you traverse the string\n if(m.size()==j-i+1) // whem map size is equal to the window size means suppose window size is 3 and map size is also three that means in map all unique characters are their\n {\n ans = max(ans,j-i+1); //compare the length of the maximum window size\n }\n else if(m.size()<j-i+1) //if the map size is less than the window size means there is some duplicate present like window size = 3 and map size = 2 means there is a duplicates\n {\n while(m.size()<j-i+1) //so till the duplicates are removed completely\n {\n m[s[i]]--; //remove the duplicates\n if(m[s[i]]==0) //if the frequency becomes zero \n {\n m.erase(s[i]);//delete it completely\n }\n i++; //go for next element \n }\n }\n j++; //go for the next element\n }\n return ans;\n }\n};\n``` | 1,042 | 3 | ['C', 'Java'] | 45 |
longest-substring-without-repeating-characters | Share my Java solution using HashSet | share-my-java-solution-using-hashset-by-6sr65 | The idea is use a hash set to track the longest substring without repeating characters so far, use a fast pointer j to see if character j is in the hash set or | jeantimex | NORMAL | 2015-09-27T00:36:56+00:00 | 2018-10-26T18:21:51.646803+00:00 | 122,706 | false | The idea is use a hash set to track the longest substring without repeating characters so far, use a fast pointer j to see if character j is in the hash set or not, if not, great, add it to the hash set, move j forward and update the max length, otherwise, delete from the head by using a slow pointer i until we can put character j to the hash set.\n\n public int lengthOfLongestSubstring(String s) {\n int i = 0, j = 0, max = 0;\n Set<Character> set = new HashSet<>();\n \n while (j < s.length()) {\n if (!set.contains(s.charAt(j))) {\n set.add(s.charAt(j++));\n max = Math.max(max, set.size());\n } else {\n set.remove(s.charAt(i++));\n }\n }\n \n return max;\n } | 948 | 7 | ['Java'] | 79 |
longest-substring-without-repeating-characters | Used HashSet in JAVA ✅ || Explained Approach | used-hashset-in-java-explained-approach-ifhi6 | Intuition\n Describe your first thoughts on how to solve this problem. \nif you know sliding window...then it can be intuitive. But if you don\'t know ...no wor | rachit615 | NORMAL | 2023-02-07T19:29:17.663863+00:00 | 2023-02-07T19:29:17.663906+00:00 | 158,706 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif you know sliding window...then it can be intuitive. But if you don\'t know ...no worry i will teach you...\nRefer below approach points.....\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use sliding window with hashset, use left and right pointers to move the window . \n2. If the set doesn\'t contains character then first add into the set and calculate the maxLength hand-in-hand... \n3. if character already present in the set that means you have to move your sliding window by 1 , before that you have to remove all the characters that are infront of the character that is present already in window before.\n4. Now you have to remove that character also and move the left pointer and also add the new character into the set.\n5. THAT\'S ALL........EASY APPROACH USING SIMPLE HASHSET+SLIDING WINDOW\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(k), where k is the number of distinctive characters prsent in the hashset.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Set<Character>set=new HashSet<>();\n int maxLength=0;\n int left=0;\n for(int right=0;right<s.length();right++){\n \n if(!set.contains(s.charAt(right))){\n set.add(s.charAt(right));\n maxLength=Math.max(maxLength,right-left+1);\n \n }else{\n while(s.charAt(left)!=s.charAt(right)){\n set.remove(s.charAt(left));\n left++;\n }\n set.remove(s.charAt(left));left++;\n set.add(s.charAt(right));\n }\n \n }\n return maxLength;\n }\n}\n```\n\n\n\n\n**PLEASE UPVOTE** .....if you find this solution useful , and if any suggestions to improve then please comment. | 933 | 3 | ['Hash Table', 'Sliding Window', 'Python', 'C++', 'Java'] | 37 |
longest-substring-without-repeating-characters | [Python3]: sliding window O(N) with explanation | python3-sliding-window-on-with-explanati-zont | Sliding window\nWe use a dictionary to store the character as the key, the last appear index has been seen so far as value.\nseen[charactor] = index\n\n move th | zhanweiting | NORMAL | 2019-07-31T07:54:07.671471+00:00 | 2019-12-19T07:41:39.958652+00:00 | 134,737 | false | **Sliding window**\nWe use a dictionary to store the character as the key, the last appear index has been seen so far as value.\nseen[charactor] = index\n\n move the pointer when you met a repeated character in your window.\n\n\t \n```\nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n ^ ^\n | |\n\t\tleft right\n\t\tseen = {a : 0, c : 1, b : 2, d: 3} \n\t\t# case 1: seen[b] = 2, current window is s[0:4] , \n\t\t# b is inside current window, seen[b] = 2 > left = 0. Move left pointer to seen[b] + 1 = 3\n\t\tseen = {a : 0, c : 1, b : 4, d: 3} \nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n\t\t\t\t\t\t ^ ^\n\t\t\t\t\t | |\n\t\t\t\t left right\t\t\nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n\t\t\t\t\t ^ ^\n\t\t\t\t\t | |\n\t\t\t\t left right\t\t\n\t\t# case 2: seen[a] = 0,which means a not in current window s[3:5] , since seen[a] = 0 < left = 3 \n\t\t# we can keep moving right pointer.\n```\n\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n seen = {}\n l = 0\n output = 0\n for r in range(len(s)):\n """\n If s[r] not in seen, we can keep increasing the window size by moving right pointer\n """\n if s[r] not in seen:\n output = max(output,r-l+1)\n """\n There are two cases if s[r] in seen:\n case1: s[r] is inside the current window, we need to change the window by moving left pointer to seen[s[r]] + 1.\n case2: s[r] is not inside the current window, we can keep increase the window\n """\n else:\n if seen[s[r]] < l:\n output = max(output,r-l+1)\n else:\n l = seen[s[r]] + 1\n seen[s[r]] = r\n return output\n```\n* Time complexity :O(n). \n\tn is the length of the input string.\n\tIt will iterate n times to get the result.\n\n* Space complexity: O(m)\n\tm is the number of unique characters of the input. \n\tWe need a dictionary to store unique characters.\n\n | 876 | 3 | ['Python', 'Python3'] | 50 |
longest-substring-without-repeating-characters | A Python solution - 85ms - O(n) | a-python-solution-85ms-on-by-google-1yh4 | class Solution:\n # @return an integer\n def lengthOfLongestSubstring(self, s):\n start = maxLength = 0\n usedChar = {}\n | google | NORMAL | 2015-04-09T00:16:40+00:00 | 2018-10-26T15:12:55.411653+00:00 | 184,061 | false | class Solution:\n # @return an integer\n def lengthOfLongestSubstring(self, s):\n start = maxLength = 0\n usedChar = {}\n \n for i in range(len(s)):\n if s[i] in usedChar and start <= usedChar[s[i]]:\n start = usedChar[s[i]] + 1\n else:\n maxLength = max(maxLength, i - start + 1)\n \n usedChar[s[i]] = i\n \n return maxLength | 642 | 8 | ['Python'] | 89 |
longest-substring-without-repeating-characters | CPP Solution for beginners | O(n) time | Longest Substring without repeating characters | cpp-solution-for-beginners-on-time-longe-vyds | A solution for beginners, which is straightforward, easy to understand, without too many complications and room to optimize once you understand the basic premis | sidthakur1 | NORMAL | 2019-09-06T22:39:00.036043+00:00 | 2019-09-09T03:28:55.479232+00:00 | 42,440 | false | A solution for beginners, which is straightforward, easy to understand, without too many complications and room to optimize once you understand the basic premise of the question. Hope this helps!\n\nTime Complexity: O(n)\nSpace Complexity: O(min of a,b) for the unordered set. a, is the upper bound of the space complexity.\nWhere a: Size of the string\nb: Size of the number of characters in the character-set\n\n\tclass Solution {\n\tpublic:\n\t\tint lengthOfLongestSubstring(string s) \n\t\t{\n\t\t\tunordered_set<char> set;\n \n\t\t\tint i = 0, j = 0, n = s.size(), ans = 0;\n \n\t\t\twhile( i<n && j<n)\n\t\t\t{\n\t\t\t\tif(set.find(s[j]) == set.end()) //If the character does not in the set\n\t\t\t\t{\n\t\t\t\t\tset.insert(s[j++]); //Insert the character in set and update the j counter\n\t\t\t\t\tans = max(ans, j-i); //Check if the new distance is longer than the current answer\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tset.erase(s[i++]); \n\t\t\t\t\t/*If character does exist in the set, ie. it is a repeated character, \n\t\t\t\t\twe update the left side counter i, and continue with the checking for substring. */\n\t\t\t\t}\n\t\t\t}\n \n\t\t\treturn ans;\n\t\t}\n\t}; | 519 | 3 | ['Sliding Window', 'C++'] | 43 |
longest-substring-without-repeating-characters | Simple Explanation | Concise | Thinking Process & Example | simple-explanation-concise-thinking-proc-n2zl | Lets start with the following example: \n\nAssume you had no repeating characters (In below example, just look at first three characters)\n\nWe take two pointer | ivankatrump | NORMAL | 2020-07-18T23:38:26.530759+00:00 | 2020-10-11T23:46:53.948437+00:00 | 27,114 | false | Lets start with the following example: \n\n**Assume you had no repeating characters** (In below example, just look at *first three* characters)\n\nWe take two pointers, `l` and `r`, both starting at `0`. At every iteration, we update the longest string with non-repeating characters found = `r-l+1` and just keep a note of which character we see at which index\n\n\n<img src="https://assets.leetcode.com/users/images/3e7b9848-1d57-42ed-9629-59f14cfcce89_1595114117.3901849.png" width=400/>\n\n\n```python\n def lengthOfLongestSubstringSimpler(self, s):\n seen = {}\n left, right = 0, 0\n longest = 1\n while right < len(s):\n longest = max(longest, right - left + 1)\n seen[s[right]] = right\n right += 1\n return longest\n```\n\nAfter 3 iterations, if you were keeping a map of when you last saw the character, you\'d have something like this:\n\n<img src="https://assets.leetcode.com/users/images/2f60312a-d377-4786-9449-4a95210f72e2_1595114189.5949714.png" width=300/>\n\nat this point, `longest = r-l+1 = 2 - 0 + 1 = 3`\n\nNow, lets face it - our string _does_ have repeating characters. We look at index 3, we\'re realizing we\'ve seen `a` before. So we now, we can\'t just calculate the value of `longest` like we were doing before. We need to make sure our left pointer, or `l`, is at least past the index where we last saw `a` , thus - we move `l ` to ` seen[right]+1`. We also update our map with last seen of `a` to `3`\n\n<img src="https://assets.leetcode.com/users/images/b7aaad14-993b-47e9-af01-441bbc5dfe20_1595114261.38747.png" width=300/>\n\nAnd this interplay goes on\n\n<img src="https://assets.leetcode.com/users/images/a22de24e-9e66-4e21-ab33-2ac06ce1d0cb_1595114354.4211376.png" width=300/>\n\n\n```python\n def lengthOfLongestSubstring(self, s):\n """\n :type s: str\n :rtype: int \n """\n if len(s) == 0:\n return 0\n seen = {}\n left, right = 0, 0\n longest = 1\n while right < len(s):\n if s[right] in seen:\n left = seen[s[right]]+1\n longest = max(longest, right - left + 1)\n seen[s[right]] = right\n right += 1\n return longest\n```\n\nLife was good, until this test case came into our lives:\n`abba`\n\n<img src="https://assets.leetcode.com/users/images/cce6e442-6d18-4971-bcf2-d2c59ea11a51_1595115276.967406.png" width=200/>\n\nAnd we realised, after 4 iterations, our left pointer was to be moved `seen[s[right]]+1 = seen[a] + 1 = 1` - wait what, left was to move back ? That doesn\'t sound correct - that\'d give us longest to be 3 (bba) which is NOT CORRECT\n\nThus, we need to ensure that `l` always goes to the right of it, or just stays at its position\n\nIn other words;\n\n```python\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n """\n :type s: str\n :rtype: int abcabcbb\n """\n if len(s) == 0:\n return 0\n seen = {}\n left, right = 0, 0\n longest = 1\n while right < len(s):\n if s[right] in seen:\n left = max(left,seen[s[right]]+1)\n longest = max(longest, right - left + 1)\n seen[s[right]] = right\n right += 1\n print(left, right, longest)\n return longest\n```\n\nThanks, and don\'t forget to upvote if it helped you !\n\n\n\n**BONUS** Trying to be a strong Java Developer ? Checkout this [awesome hands-on series](https://abhinandandubey.github.io/posts/tags/Advanced-Java-Series) with illustrations! \n | 388 | 13 | ['Python', 'Python3'] | 13 |
longest-substring-without-repeating-characters | ✅ best C++ fast solution | best-c-fast-solution-by-coding_menance-3hao | C++ Code\nC++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n if(s.length()==0)return 0; //if string of length zero comes | coding_menance | NORMAL | 2023-03-10T08:53:11.155472+00:00 | 2023-03-10T08:53:18.032984+00:00 | 65,381 | false | # C++ Code\n``` C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n if(s.length()==0)return 0; //if string of length zero comes simply return 0\n unordered_map<char,int> m; //create map to store frequency,(get to know all unique characters\n int i=0,j=0,ans=INT_MIN; \n while(j<s.length()) \n {\n m[s[j]]++; //increase the frequency of the element as you traverse the string\n if(m.size()==j-i+1) // whem map size is equal to the window size means suppose window size is 3 and map size is also three that means in map all unique characters are their\n {\n ans = max(ans,j-i+1); //compare the length of the maximum window size\n }\n else if(m.size()<j-i+1) //if the map size is less than the window size means there is some duplicate present like window size = 3 and map size = 2 means there is a duplicates\n {\n while(m.size()<j-i+1) //so till the duplicates are removed completely\n {\n m[s[i]]--; //remove the duplicates\n if(m[s[i]]==0) //if the frequency becomes zero \n {\n m.erase(s[i]);//delete it completely\n }\n i++; //go for next element \n }\n }\n j++; //go for the next element\n }\n return ans;\n }\n};\n```\n\n\n | 271 | 1 | ['C++'] | 7 |
longest-substring-without-repeating-characters | SLIDING WINDOW || O(n) || Faster than 90% and Memory usage less than 100% | sliding-window-on-faster-than-90-and-mem-haid | \nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n \n //SLIDING WINDOW - TIME COMPLEXITY O(2n)\n // | kush980 | NORMAL | 2021-01-13T14:35:43.589865+00:00 | 2021-01-14T08:41:51.107291+00:00 | 29,536 | false | ```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n \n //SLIDING WINDOW - TIME COMPLEXITY O(2n)\n // SPACE COMPLEXITY O(m) //size of array\n \n int store[256]={0}; //array to store the occurences of all the characters\n int l=0; //left pointer\n int r=0; //right pointer\n int ans=0; //initializing the required length as 0\n \n while(r<s.length()) //iterate over the string till the right pointer reaches the end of the string \n {\n store[s[r]]++; //increment the count of the character present in the right pointer \n \n while(store[s[r]]>1) //if the occurence become more than 1 means the char is repeated\n { \n store[s[l]]--; //reduce the occurence of temp as it might be present ahead also in the string\n l++; //contraction of the present window till the occurence of the \'t\' char becomes 1\n }\n \n ans = max(ans,r-l+1); //As the index starts from 0 , ans will be (right pointer-left pointer + 1)\n r++; // now will increment the right pointer \n }\n return ans;\n }\n};\n```\n**If you like it, Do upvote \nHappy Coding;**\n\n | 270 | 2 | ['C', 'Sliding Window', 'C++'] | 10 |
longest-substring-without-repeating-characters | JS | 98% | Sliding window | With exlanation | js-98-sliding-window-with-exlanation-by-4ymyu | \n\nWindow Sliding Technique is a computational technique which aims to reduce the use of nested loop and replace it with a single loop, thereby reducing the ti | Karina_Olenina | NORMAL | 2022-10-12T11:55:48.311868+00:00 | 2022-10-18T07:39:40.543988+00:00 | 49,554 | false | \n\n**Window Sliding Technique** is a computational technique which aims to reduce the use of nested loop and replace it with a single loop, thereby reducing the time complexity.\nThe Sliding window technique can reduce the time complexity to **O(n).**\n\n\n\n\n\n\nBelow are some basic tips for identifying this kind of problem where we could use the sliding window technique:\n\n* The problem will be based on an array, string, or list data structure.\n* You need to find the subrange in this array or string that should provide the longest, shortest, or target values.\n* A classic problem: to find the largest/smallest sum of given k (for example, three) consecutive numbers in an array.\n\nThe length can be **fixed**, as in the example above, or it can be **dynamic**, just like in this problem.\n\nSo to solve this problem, we can use the hash table and iterate over our term. Let\'s do two checks on 0 and 1 so as not to waste extra time. Now we can start, in the picture above you can see our **window** (blue rectangle) and its movement during the scan. We gradually add our letters to the **hash table**, and if it already contains this letter, we delete the letter corresponding to the leftmost index, do this until we get to the desired one and delete the repetition. Only after that we add our new element. \nThe maximum length is found by comparing our current length with the new one, using **Math.max**.\n\nIn the picture you can see all the movement of the window and the state of our hash table.\n\n\n```\nvar lengthOfLongestSubstring = function (s) {\n let set = new Set();\n let left = 0;\n let maxSize = 0;\n\n if (s.length === 0) return 0;\n if (s.length === 1) return 1;\n\n for (let i = 0; i < s.length; i++) {\n\n while (set.has(s[i])) {\n set.delete(s[left])\n left++;\n }\n set.add(s[i]);\n maxSize = Math.max(maxSize, i - left + 1)\n }\n return maxSize;\n}\n```\n\nI hope I was able to explain clearly.\n**Happy coding**! \uD83D\uDE43\n | 247 | 0 | ['Hash Table', 'Sliding Window', 'JavaScript'] | 28 |
longest-substring-without-repeating-characters | Shortest O(n) DP solution with explanations | shortest-on-dp-solution-with-explanation-20o5 | /**\n * Solution (DP, O(n)):\n * \n * Assume L[i] = s[m...i], denotes the longest substring without repeating\n * characters that ends up at s[i | dragonmigo | NORMAL | 2014-10-15T19:04:06+00:00 | 2018-10-21T19:30:09.865979+00:00 | 72,105 | false | /**\n * Solution (DP, O(n)):\n * \n * Assume L[i] = s[m...i], denotes the longest substring without repeating\n * characters that ends up at s[i], and we keep a hashmap for every\n * characters between m ... i, while storing <character, index> in the\n * hashmap.\n * We know that each character will appear only once.\n * Then to find s[i+1]:\n * 1) if s[i+1] does not appear in hashmap\n * we can just add s[i+1] to hash map. and L[i+1] = s[m...i+1]\n * 2) if s[i+1] exists in hashmap, and the hashmap value (the index) is k\n * let m = max(m, k), then L[i+1] = s[m...i+1], we also need to update\n * entry in hashmap to mark the latest occurency of s[i+1].\n * \n * Since we scan the string for only once, and the 'm' will also move from\n * beginning to end for at most once. Overall complexity is O(n).\n *\n * If characters are all in ASCII, we could use array to mimic hashmap.\n */\n\n int lengthOfLongestSubstring(string s) {\n // for ASCII char sequence, use this as a hashmap\n vector<int> charIndex(256, -1);\n int longest = 0, m = 0;\n\n for (int i = 0; i < s.length(); i++) {\n m = max(charIndex[s[i]] + 1, m); // automatically takes care of -1 case\n charIndex[s[i]] = i;\n longest = max(longest, i - m + 1);\n }\n\n return longest;\n }\n\n\nHope you like it :) | 204 | 16 | [] | 28 |
longest-substring-without-repeating-characters | 9 line JavaScript solution | 9-line-javascript-solution-by-linfongi-jjkl | function lengthOfLongestSubstring(s) {\n const map = {};\n var left = 0;\n \n return s.split('').reduce((max, v, i) => {\n | linfongi | NORMAL | 2015-08-16T02:03:54+00:00 | 2018-09-01T11:10:40.901014+00:00 | 33,939 | false | function lengthOfLongestSubstring(s) {\n const map = {};\n var left = 0;\n \n return s.split('').reduce((max, v, i) => {\n left = map[v] >= left ? map[v] + 1 : left;\n map[v] = i;\n return Math.max(max, i - left + 1);\n }, 0);\n } | 144 | 4 | ['JavaScript'] | 20 |
longest-substring-without-repeating-characters | Visual Explanation | Sliding Window JAVA | visual-explanation-sliding-window-java-b-k6qn | Logic:\nThis difficulty in this question is finding out where to pick our next substring once we\'ve spotted a duplicate character. Using two pointers and a sli | ciote | NORMAL | 2022-06-10T00:54:05.592016+00:00 | 2022-10-22T23:42:42.487283+00:00 | 13,596 | false | ### Logic:\nThis difficulty in this question is finding out where to pick our next substring once we\'ve spotted a duplicate character. Using two pointers and a sliding window, we can quite easily choose what substring we want to look at. In fact, finding the longest substring without repeating characters becomes even easier once you realise the following observation.\n\n**Key Observation:**\n> Once we\'ve landed on a character we\'ve seen before, we want to move the left pointer of our window to the index *after* the last occurrence of that character.\n\nPay attention to the following example with the input string `s = "babcadba"` to see this in action:\n\n\n\nAs you can see, our `nextIndex[]` array functions as both a hashset and a way to keep track of indexes. In particular, our array is storing the index AFTER the last occurrence of any character. That way, our left pointer can move directly there. \n___\n### How does this work in code?\nTurns out characters can function as integers. As such, we can use the characters themselves to access values of our `nextIndex[]` array. We\'ll need an array that has range: [0, 128) as that covers all ASCII characters that could be used in this question. \n\nSince we\'re working with two pointers, we can quite conveniently find the length of our current window using `r - l + 1`. We can update this anytime it\'s larger than our current maximum.\n\nAwesome. Now we\'re ready to start coding!\n\n___\n### Code\nIf you have any questions, suggestions or improvements, feel free to let me know. Thanks for reading!\n```java\npublic int lengthOfLongestSubstring(String s) {\n\tint n = s.length(), longest = 0;\n\tint[] nextIndex = new int[128]; \n\n\tfor (int r=0, l=0; r<n; r++) {\n\t\tl = Math.max(nextIndex[s.charAt(r)], l); \n\t\tlongest = Math.max(longest, r - l + 1);\n\t\tnextIndex[s.charAt(r)] = r + 1;\n\t}\n\n\treturn longest;\n}\n```\n**Time Complexity:** `O(n)` where `n` is the length of the string.\n**Space Complexity:** `O(128)` for the `nextIndex` array. | 123 | 0 | ['Sliding Window', 'Java'] | 12 |
longest-substring-without-repeating-characters | ✅Short||C++||Expained Solution|| 11 line code | shortcexpained-solution-11-line-code-by-7s5u6 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe have to find the length of longest substring which does not contain any repeating ch | divyanshu851_8 | NORMAL | 2022-11-11T21:43:13.965108+00:00 | 2022-11-19T17:55:24.609495+00:00 | 18,663 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have to find the length of longest substring which does not contain any repeating characters\n\nThe first thing which should come in our mind is to traverse in the string and store the frequence of each character in a map type of "map<char ,int>" and try to maintain frequency of all the characters present in the map to 1 and storing the maximum length \n\n\n# Approach\n1:- We will first iterate over the string and store the frequencies of all the character we have visited in a map of type "map<char ,int>"\n\n2:- In each iteration we will check if the frequency of character at ith index is greater than one.....if yes it means that that character is repeated twice in our map so we will start erasing all the characters from the starting jth index untill we delete the same character which is repeated twice...... from the left\n\nex :- `Input: s = "abcabcbb"`\n\n`i=0 mp:{[a:1]}`\n|| length =1 , maxlength = 1 \n\n`i=1 mp:{[a:1] , [b:1]}`\n|| length =2 , maxlength = 2\n\n`i=2 mp:{[a:1] , [b:1] , [c:1]}`\n|| length =3 , maxlength = 3\n\n`i=3 mp:{[a:2] , [b:1] , [c:1]}`\n|| length =4 , maxlength =3\n\n\'a\' appeared 2 times , so we will start removing characters from the left untill the frequency of \'a\' becomes 1 again.\nwhile(mp[a]>1) , we will decrease the frequency of all the characters from left i.e. "mp[s[j++]]--" ......Variable j stores the starting index of our subarray , Initially it is 0 but as we start deleting characters from left , this j will be get increment....that is why we did j++ there.\nwhen j=0 , mp[s[j++]] will get decrease by one and the frequency of a will again be equal to 1\n\n`i=3 mp:{[a:1] , [b:1] , [c:1]}`\n|| length =3 , maxlength =3\n\n3:- In each iteration we will take the maximum of (maxlength ,length) and store it in max length\n\nThis process will continue till we reach the end of the string and will return maxlength which is the length of longest substring with no repeating characters in it \n\n\n\n\n# Code\n```\n int lengthOfLongestSubstring(string s) {\n int length=0 , maxlength=0,j=0;\n map<char ,int> mp;\n for(int i=0 ;i<s.size(); i++){\n mp[s[i]]++;\n length++;\n while(mp[s[i]]>1){\n mp[s[j++]]--;\n length--;\n }\n maxlength = max(maxlength,length);\n }\n return maxlength;\n }\n```\n\n# Please do upvote if you like the Explanation | 117 | 0 | ['Two Pointers', 'String', 'Sliding Window', 'C++', 'Java'] | 10 |
longest-substring-without-repeating-characters | ✅ best JAVA fast solution | best-java-fast-solution-by-coding_menanc-airr | JAVA Code\nJAVA []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Set<Character>set=new HashSet<>();\n int maxLength=0;\ | coding_menance | NORMAL | 2023-03-10T05:18:42.132342+00:00 | 2023-03-10T05:18:42.132377+00:00 | 25,799 | false | # JAVA Code\n``` JAVA []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Set<Character>set=new HashSet<>();\n int maxLength=0;\n int left=0;\n for(int right=0;right<s.length();right++){\n \n if(!set.contains(s.charAt(right))){\n set.add(s.charAt(right));\n maxLength=Math.max(maxLength,right-left+1);\n \n }else{\n while(s.charAt(left)!=s.charAt(right)){\n set.remove(s.charAt(left));\n left++;\n }\n set.remove(s.charAt(left));left++;\n set.add(s.charAt(right));\n }\n \n }\n return maxLength;\n }\n}\n```\n\n### hey friend, why not upvote? \uD83E\uDD72\n\n\n | 103 | 0 | ['Java'] | 4 |
longest-substring-without-repeating-characters | Python solution with comments. | python-solution-with-comments-by-oldcodi-znnd | \n def lengthOfLongestSubstring(self, s):\n dic, res, start, = {}, 0, 0\n for i, ch in enumerate(s):\n if ch in dic:\n | oldcodingfarmer | NORMAL | 2015-08-12T13:52:34+00:00 | 2020-09-14T11:14:16.730549+00:00 | 40,658 | false | \n def lengthOfLongestSubstring(self, s):\n dic, res, start, = {}, 0, 0\n for i, ch in enumerate(s):\n if ch in dic:\n res = max(res, i-start) # update the res\n start = max(start, dic[ch]+1) # here should be careful, like "abba"\n dic[ch] = i\n return max(res, len(s)-start) # return should consider the last non-repeated substring | 94 | 4 | ['Python'] | 16 |
longest-substring-without-repeating-characters | ✅ [Python/C++/Java/Rust] 0 ms, position difference (with detailed comments) | pythoncjavarust-0-ms-position-difference-sxit | \u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.\n*\nThis solution employs storage of positions and calculation of their differences for repeated characters. Ti | stanislav-iablokov | NORMAL | 2022-10-24T13:46:35.027892+00:00 | 2022-10-24T13:48:06.683681+00:00 | 15,640 | false | **\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs storage of positions and calculation of their differences for repeated characters. Time complexity is linear: **O(N)**. Space complexity is constant: **O(1)**. \n\n| Language | [**Python**](https://leetcode.com/submissions/detail/829196177/) | [**C++**](https://leetcode.com/submissions/detail/829199746/) | [**Java**](https://leetcode.com/submissions/detail/829275351/) | [**Rust**](https://leetcode.com/submissions/detail/829192202/) | \n|---|---|---|---|---|\n| Runtime | **62 ms (95.17%)** | **0 ms (100.00%)** | **2 ms (100.00%)** | **0 ms (100.00%)** |\n| Memory | **14.0 MB (93.06%)** | **7.6 MB (87.55%)** | **42.1 MB (98.23%)** | **7.6 MB (87.55%)** |\n\n<iframe src="https://leetcode.com/playground/U5pR5wcg/shared" frameBorder="0" width="800" height="600"></iframe> | 87 | 0 | ['C', 'Python', 'Java', 'Rust'] | 8 |
longest-substring-without-repeating-characters | C++ Solution using Set | c-solution-using-set-by-sheldonbang-h4fd | ```\n int lengthOfLongestSubstring(string s) {\n int n=s.length();\n if(n==0)\n return 0;\n set st;\n int maxsize=0;\n | sheldonbang | NORMAL | 2020-04-13T04:05:07.043365+00:00 | 2020-04-13T04:09:26.383439+00:00 | 12,729 | false | ```\n int lengthOfLongestSubstring(string s) {\n int n=s.length();\n if(n==0)\n return 0;\n set<char> st;\n int maxsize=0;\n int i=0,j=0;\n while(j<n)\n {\n if(st.count(s[j])==0)\n {\n st.insert(s[j]);\n maxsize=max(maxsize,(int)st.size());\n j++;\n }\n else\n {\n st.erase(s[i]);\n i++;\n }\n }\n return maxsize;\n }\n\t | 85 | 3 | ['C', 'Ordered Set', 'C++'] | 12 |
longest-substring-without-repeating-characters | C++ | All approaches: brute force, Sliding Window | 12ms | map | Solution for Longest Substring | c-all-approaches-brute-force-sliding-win-nnmk | Dear All,\n\nI solved this issue with different approaches and happy to share with you. Probably looking to all of them and comparing you will understand which | YevRad | NORMAL | 2021-03-18T14:40:52.986320+00:00 | 2021-03-29T14:32:52.126099+00:00 | 10,892 | false | Dear All,\n\nI solved this issue with different approaches and happy to share with you. Probably looking to all of them and comparing you will understand which one is better and why. All solutions containes comments for your better understanding of algorithm. Hope you will enjoy =)\n\nPlease find below my last and best solution with Sliding Window approach. Here we have O(n) time complexity(where n is a length of string) and O(k) space complexity(where k is unique characters from the string). You can notice that find() takes additional affort and Time Complexity won\'t be equal to O(n). I will try to explain: In general Time Complexity of searching elements in map is O(log n) in worst case. But exactly in our case it\'s very close to O(1) because we add only unique characters and range of possible characters is very small compared to string length. Let\'s imagine that our string contains 1 000 000 characters. But in Hash Table will be maximum 128 characters(in real life even less because some specific characters won\'t not used). Method find() in our case will be O(log 128) = 7 - very close to constant time. So, on each step logic will do maximum 7 additional steps. That\'s why it\'s very close to O(n). We can say that TC is O(n * log m), where n - length of string, m - number of unique characters from string. But since we know that m not more than 128, and log m not more than 7 - is very close to constant and we can ignore it.\nWe can try to use unordered_map that TC of find is O(1). The reason why I use map instead - unordered_map is not stable. In worst case TC will be O(n), not O(1). It happens when hash function will generate same hash index that calls collisions. Also unordered_map required for extra space for Hash Table. map - always O(log n). Since we know that log n = 7 in worse case - make sense use map.\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) \n { \n // Return 0 if string is empty\n if( s == "") { return 0; }\n \n // Hash table for storing characters and indexes\n map<char, int> characters; \n \n // Longest sequence that will be returned in the end: for sure will be > 1 because 0 result was checked in the beginning\n int longest = 1;\n int j = 0;\n \n // Each character from string add to HashTable with his index. If we reach same character again - update index\n for (int i = 0; i < s.length(); ++i)\n {\n // If current character already exist in the HashTable \n if ( characters.find(s[i]) != characters.end() )\n {\n // Take larger index for future calculation between old and current+1 in HashTable\n j = j >= characters.find(s[i])->second + 1 ? j : characters.find(s[i])->second + 1;\n }\n // Add character with current index to HashTable\n characters[s[i]] = i;\n // longest will be chosen between larger value: old longest OR current sequance between i and j indexes + 1\n longest = longest >= i - j + 1 ? longest : i - j + 1;\n }\n \n return longest;\n }\n};\n```\n\nNext will be my first try with brute force solution that has O(n^3) complexity. This approach will work here in LeetCode for small strings, but for big you will receive status \'Time Limit Exceeded\'. In your IDE it will work even for big strings but very slowly. Iterator used just for practice. New method was created in private section for checking dublicates in substring - `bool dublicatesInSubstring(string& s, const int substringBegin, const int substringEnd)`.\n```\nclass Solution {\nprivate:\n // Method for dublicates check in substring\n bool dublicatesInSubstring(string& s, const int substringBegin, const int substringEnd)\n {\n std::map<char, int> charactersOfSubstr;\n std::map<char, int>::iterator it;\n \n // Check substring for dublicates\n for(int i = substringBegin; i <= substringEnd; ++i )\n {\n // Add character to HashTable\n it = charactersOfSubstr.find(s[i]);\n if ( it != charactersOfSubstr.end() )\n {\n it->second++;\n }\n else\n {\n charactersOfSubstr.insert(std::pair<char,int>(s[i], 0));\n }\n // In case HashTable has more that one such character - return true that means dublicates exist in substring\n if( it->second > 0 )\n {\n return true;\n }\n }\n \n return false;\n }\n \npublic:\n int lengthOfLongestSubstring(string s) \n {\n // Return 0 if string is empty\n if( s == "") { return 0; }\n \n // Longest sequence that will be returned in the end\n int longest = 0;\n \n // For each character from string - ckech longest sequence untin end of the string\n for (int i = 0; i < s.length(); ++i)\n {\n for(int j = i; j < s.length(); ++j)\n {\n // In case no dublicates - function return false and longest substring should be calculated\n if ( !dublicatesInSubstring(s, i, j) )\n {\n longest = longest >= j - i + 1 ? longest : j - i + 1;\n }\n }\n }\n \n return longest;\n }\n};\n```\n\nMy next try was approach with O(n^2) complexity that much faster than previous and LeetCode finished all test cases without \'Time Limit Exceeded\' status. Iterator also used only for practice.\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) \n { \n // Return 0 if string is empty\n if( s == "") { return 0; }\n \n std::map<char, int> charactersOfSubstr;\n std::map<char, int>::iterator it; \n \n // Longest sequence that will be returned in the end\n int longest = 0;\n \n // For each character from string - check longest sequence until encountered dublicate\n for (int i = 0; i < s.length(); ++i)\n {\n // HashTable should be cleared before starting with new substring analyzing\n charactersOfSubstr.clear();\n for(int j = i; j < s.length(); ++j)\n {\n // Try to find character in the HashTable\n it = charactersOfSubstr.find(s[j]);\n \n // If current character already exist in the HashTable - quit from j-loop to get next character for analyze\n if (it != charactersOfSubstr.end())\n {\n break;\n }\n // If character doesn\'t exist in HashTable - add it and recount unique sequence lenght\n else\n {\n charactersOfSubstr.insert(pair<char, int>(s[j], 1));\n \n // longest will be chose\u0442 between larger value: old longest OR current sequance (j - i + 1)\n longest = longest >= j - i + 1 ? longest : j - i + 1;\n } \n }\n }\n \n return longest;\n }\n};\n```\n\nNext try was very close to O(n) but still loop inside loop used. After this approach I thought that it\'s possible to get rid of nested loop.\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) \n { \n // Return 0 if string is empty\n if( s == "") { return 0; }\n \n // Hash table for storing characters and count dublicates\n std::map<char, int> charactersOfSubstr; \n \n // Longest sequence that will be returned in the end\n int longest = 0;\n int j = 0;\n \n // Each character from string add to HashTable: for dublicates increase value that used in result calculation\n for (int i = 0; i < s.length(); ++i)\n {\n // Try to find character in the HashTable\n // If current character already exist in the HashTable - increment value\n if ( charactersOfSubstr.find(s[i]) != charactersOfSubstr.end() )\n {\n charactersOfSubstr.find(s[i])->second++;\n }\n // Othervise add it to HashTable\n else\n {\n charactersOfSubstr.insert(pair<char, int>(s[i], 1));\n }\n \n // ONLY if in HashTable exist several same characters:\n // decrease ALL characters between j and i in HashTable AND increase j for calculation while s[i] value in Hash table > 1\n while ( charactersOfSubstr.find(s[i])->second > 1 )\n {\n // Descrease value of existing character\n charactersOfSubstr.find(s[j])->second--;\n // Increase j for future calculation\n ++j;\n }\n \n // longest will be chosen between larger value: old longest OR current sequance (i - j + 1)\n longest = longest >= i - j + 1 ? longest : i - j + 1;\n }\n \n return longest;\n }\n};\n```\n\nHope you read until the end and enjoyed =)\nIf you know how to improve the code - please let me know I will be very grateful.\nIf you like solution please vote - I will be pleased.\n\nThanks and have a good day.\n\nBest Regards, Yevhen.\n | 83 | 3 | ['C', 'Sliding Window', 'Iterator', 'C++'] | 5 |
longest-substring-without-repeating-characters | JavaScript Clean Heavily Commented Solution | javascript-clean-heavily-commented-solut-mshw | Time Complexity = O(N)\nSpace Complexity = O(N)\njavascript\nvar lengthOfLongestSubstring = function(s) {\n // keeps track of the most recent index of each l | control_the_narrative | NORMAL | 2020-07-12T04:05:25.403290+00:00 | 2020-07-12T04:07:03.555514+00:00 | 14,979 | false | Time Complexity = `O(N)`\nSpace Complexity = `O(N)`\n```javascript\nvar lengthOfLongestSubstring = function(s) {\n // keeps track of the most recent index of each letter.\n const seen = new Map();\n // keeps track of the starting index of the current substring.\n let start = 0;\n // keeps track of the maximum substring length.\n let maxLen = 0;\n \n for(let i = 0; i < s.length; i++) {\n // if the current char was seen, move the start to (1 + the last index of this char)\n // max prevents moving backward, \'start\' can only move forward\n if(seen.has(s[i])) start = Math.max(seen.get(s[i]) + 1, start)\n seen.set(s[i], i);\n // maximum of the current substring length and maxLen\n maxLen = Math.max(i - start + 1, maxLen);\n } \n \n return maxLen; \n};\n``` | 76 | 0 | ['JavaScript'] | 11 |
longest-substring-without-repeating-characters | O(n) | Beats 100 % | Sliding Window | Java | C++ | Python | Go | Rust | JavaScript | on-beats-100-sliding-window-java-c-pytho-8kf6 | Intuition\n\nThe problem asks us to find the length of the longest substring without repeating characters. It might sound a bit technical at first, but we can b | kartikdevsharma_ | NORMAL | 2024-09-21T16:06:17.735940+00:00 | 2024-09-22T16:35:45.780654+00:00 | 12,090 | false | ## Intuition\n\nThe problem asks us to find the length of the **longest substring without repeating characters**. It might sound a bit technical at first, but we can break it down: \nImagine you\u2019re given a string, like "abcabcbb". What we\u2019re really being asked is, "What\u2019s the longest continuous chunk of this string where no characters repeat?" For example, in "abcabcbb", the substring "abc" is the longest part where every character is different. So, in this case, the answer would be 3 because "abc" is made up of 3 unique characters.\nWe\'re looking for the longest substring without repeating characters - seems simple enough, right? But We need to find a stretch of characters where each character appears only once it gets tricky when you have repeating characters in the string, like in the case of "abcabcbb". As soon as you hit the second \'a\', the substring is no longer valid because the \'a\' already appeared earlier. So, we\u2019ll need to figure out how to handle those situations without missing the longest valid substring. That\'s our target. The challenge here is that we need to do this efficiently - we can\'t just check every possible substring, especially if the string is really long.\n\nOur first instinct might be to use a brute force approach. We could check every possible substring, right? Start with the first character, then look at the first two, then the first three, and so on. For each substring, we\'d check if it has any repeating characters. But let\'s think about this for a moment. For a string of length n, we\'d be checking n(n+1)/2 substrings, and for each substring, we\'d need to scan through its characters to check for duplicates. That\'s an O(n^3) time complexity - definitely not efficient, especially for longer strings!\n\nSo, we need to refine our approach. This is where the concept of a sliding window comes in handy. Instead of checking every substring from scratch, what if we "slide" over the string, expanding or shrinking our window as we go? The window represents the current substring we\'re looking at, and we try to keep it as long as possible while ensuring there are no repeating characters inside it.\n\nLet\'s walk through this with an example, say "abcabcbb":\n\n1. We start with \'a\'. Our window is just "a" - no repeats, so we\'re good.\n2. We move to \'b\'. Window becomes "ab" - still no repeats.\n3. Next is \'c\'. Window is "abc" - all unique so far.\n4. Now we hit another \'a\'. Here\'s where it gets interesting. We can\'t just add this \'a\' to our window because it would create a repeat. So, we need to shrink our window from the left until we remove the first \'a\'.\n\nThis is a key insight: when we see a repeating character, we don\'t need to start all over. We can just adjust our window by moving the left boundary. This lets us keep track of longer substrings without recomputing everything from scratch.\n\n\n\n\nBut Every time we hit a repeat, we\'re sliding the left side of the window one character at a time until the repeat is gone. What if we could jump directly to the right position instead of sliding one by one? We need a way to quickly know where we last saw each character. A hash map could work, but remember, we\'re dealing with characters here. There\'s only a limited number of possible characters. we can use an array instead of a hash map, with each index representing a character. It\'s like having a direct line to where we last saw each character. This array will store the last seen position of each character we encounter.\n\n\n\n\nNow, let\'s think about how we\'d use this array. As we move through the string with our end pointer, we\'re updating our array with the latest position of each character. But here\'s the magic - we can use this same array to update our start pointer. When we hit a repeated character, instead of slowly shrinking the window, we can jump our start pointer directly to the position after where we last saw the repeated character.\n\nBut what if we\'ve already moved past the last occurrence of the repeated character? We don\'t want to jump backwards, do we? This is where we use a max operation. We set our start pointer to the max of its current position and the position after where we last saw the repeated character. This ensures we\'re always moving forward, never backward.\n\n\n\n\nAs we\'re doing all this, we\'re constantly updating our max length. Every time we move our end pointer, we check if this new substring is longer than our current max. It\'s like we\'re always ready to capture the longest substring at any moment.\n\nLet\'s think about edge cases for a moment. What if the string is empty? Or what if it\'s all the same character? Our approach handles these naturally. If it\'s empty, we never enter our loop. If it\'s all the same character, our max length will be 1.\n\nSo:\n\n>1. We keep two pointers - start and end - representing our current window.\n>2. We maintain an array (let\'s call it lastIndex) to store the last seen position of each character.\n>3. As we move the end pointer through the string:\n\t - If the character at end is already in lastIndex and its position is after or at start, we need to jump start to skip over it.\n\t - We update lastIndex with the current position of the character.\n\t - We calculate the length of the current valid window (end - start + 1) and update our max length if needed.\n>4. We continue this until end reaches the end of the string.\n\nIt only requires one pass through the string. We\'re doing all our work - updating last seen positions, moving our start pointer, and calculating our max length - all in one smooth motion through the string. In terms of space complexity, we\'re using a fixed-size array for our characters. This is much more efficient than storing substrings or using a variable-size data structure. Our time complexity is O(n) because we\'re only scanning through the string once, making this solution efficient even for very long strings.\n\n## Approach\n\nAs i have already told in the intuition that core idea behind our solution is to use a sliding window approach combined with character indexing. This allows us to efficiently scan through the string once while keeping track of the longest valid substring we\'ve encountered so far.\n\nThe sliding window technique involves maintaining two pointers:\n1. A \'start\' pointer that marks the beginning of our current substring.\n2. An \'end\' pointer that we move through the string, expanding our substring.\n\nAs we move the \'end\' pointer, we\'re essentially expanding our window. When we encounter a repeated character, we need to contract our window by moving the \'start\' pointer.\n\nTo handle repeated characters, we use an array to keep track of the last seen position of each character. This allows us to quickly jump our \'start\' pointer to the correct position when we encounter a repeat, rather than moving it incrementally.\n\n\n\n\n### Initialization\n\n```\nn = length of s\nmaxLength = 0\nlastIndex = array of 128 integers, all initialized to 0\nstart = 0\n```\n\n- We store the length of the input string in `n` for easy reference.\n- `maxLength` will keep track of the longest valid substring we\'ve seen so far.\n- `lastIndex` is an array used to store the last seen position of each character. We use 128 as the size because it covers all ASCII characters. Each index in this array represents a character, and the value at that index represents the last position where we saw that character.\n- `start` is initialized to 0, representing the start of our sliding window.\n\n### Main Loop\n\n```\nfor end = 0 to n-1:\n currentChar = s[end]\n start = max(start, lastIndex[currentChar])\n maxLength = max(maxLength, end - start + 1)\n lastIndex[currentChar] = end + 1\n```\n\n We iterate through the string, moving our \'end\' pointer from left to right.\n\n1. `currentChar = s[end]`: We get the current character at the \'end\' position.\n\n2. `start = max(start, lastIndex[currentChar])`: This is a crucial step. We update our \'start\' pointer to be the maximum of its current value and the last seen position of the current character plus one.\n\n - If we haven\'t seen this character before (or if we\'ve seen it, but it\'s outside our current window), `lastIndex[currentChar]` will be less than `start`, so `start` remains unchanged.\n - If we have seen this character within our current window, `lastIndex[currentChar]` will be greater than or equal to `start`. In this case, we move `start` to the position just after where we last saw this character.\n\n This step effectively "jumps" our start pointer to the correct position when we encounter a repeat, ensuring our window always contains unique characters.\n\n3. `maxLength = max(maxLength, end - start + 1)`: We update `maxLength` if our current window is longer than the previous longest substring.\n\n4. `lastIndex[currentChar] = end + 1`: We update the last seen position of the current character. We use `end + 1` instead of `end` because it simplifies our logic in step 2 - it allows us to move `start` directly to the correct position without needing to add 1.\n\n## Pseudo-code Algorithm\n\n\n```\nfunction lengthOfLongestSubstring(s):\n n = length of s\n maxLength = 0\n lastIndex = array of 128 integers, all initialized to 0\n start = 0\n \n for end = 0 to n-1:\n currentChar = s[end]\n start = max(start, lastIndex[currentChar])\n maxLength = max(maxLength, end - start + 1)\n lastIndex[currentChar] = end + 1\n \n return maxLength\n```\n\n\n The longest substring without repeating characters ending at any position must be built from a valid substring ending at the previous position. By maintaining a sliding window, we\'re always building on our previous valid substrings. By using the `lastIndex` array, we can update our `start` pointer in constant time whenever we encounter a repeat. This is much more efficient than scanning back through the substring to find the repeated character. We only need to go through the string once. At each step, we\'re making a constant number of operations (updating `start`, `maxLength`, and `lastIndex`), resulting in a linear time complexity. We\'re using a fixed-size array for `lastIndex`, regardless of the input size. This gives us constant space complexity.\n\n## Time and Space Complexity\n\n- **Time Complexity: $O(n)$**, where n is the length of the input string. We make a single pass through the string, performing constant-time operations at each step.\n- **Space Complexity: $O(1)$**. We use a fixed-size array of 128 integers, regardless of the input size. This is considered constant space.\n\n\n\n## Code\n```java []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int n = s.length();\n int maxLength = 0;\n int[] lastIndex = new int[128];\n \n for (int start = 0, end = 0; end < n; end++) {\n char currentChar = s.charAt(end);\n start = Math.max(start, lastIndex[currentChar]);\n maxLength = Math.max(maxLength, end - start + 1);\n lastIndex[currentChar] = end + 1;\n }\n \n return maxLength;\n }\n}\n//KDS\n```\n\n```C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int n = s.length();\n int maxLength = 0;\n vector<int> lastIndex(128, 0);\n \n for (int start = 0, end = 0; end < n; end++) {\n char currentChar = s[end];\n start = max(start, lastIndex[currentChar]);\n maxLength = max(maxLength, end - start + 1);\n lastIndex[currentChar] = end + 1;\n }\n \n return maxLength;\n }\n};\n```\n```Python []\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n n = len(s)\n max_length = 0\n last_index = {}\n \n start = 0\n for end in range(n):\n current_char = s[end]\n start = max(start, last_index.get(current_char, 0))\n max_length = max(max_length, end - start + 1)\n last_index[current_char] = end + 1\n \n return max_length\n```\n```Go []\nfunc lengthOfLongestSubstring(s string) int {\n n := len(s)\n maxLength := 0\n lastIndex := make([]int, 128)\n \n start := 0\n for end := 0; end < n; end++ {\n currentChar := s[end]\n if lastIndex[currentChar] > start {\n start = lastIndex[currentChar]\n }\n if end-start+1 > maxLength {\n maxLength = end - start + 1\n }\n lastIndex[currentChar] = end + 1\n }\n \n return maxLength\n}\n```\n```Rust []\nimpl Solution {\n pub fn length_of_longest_substring(s: String) -> i32 {\n let mut max_length = 0;\n let mut last_index = [0; 128];\n let mut start = 0;\n \n for (end, ch) in s.chars().enumerate() {\n start = start.max(last_index[ch as usize]);\n max_length = max_length.max(end - start + 1);\n last_index[ch as usize] = end + 1;\n }\n \n max_length as i32\n }\n}\n```\n```JavaScript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar lengthOfLongestSubstring = function(s) {\n let n = s.length;\n let maxLength = 0;\n let lastIndex = new Map();\n \n let start = 0;\n for (let end = 0; end < n; end++) {\n let currentChar = s[end];\n start = Math.max(start, lastIndex.get(currentChar) || 0);\n maxLength = Math.max(maxLength, end - start + 1);\n lastIndex.set(currentChar, end + 1);\n }\n \n return maxLength;\n};\n```\n\n\n## Example\n#### Example 1: **"abcabcbb"**\n\n\n\n| Step | `end` | `start` | `currentChar` | `lastIndex[currentChar]` | `new start` | `window` | `maxLength` |\n|------|-------|---------|---------------|--------------------------|-------------|----------|-------------|\n| 1 | 0 | 0 | \'a\' | 0 | 0 | "a" | 1 |\n| 2 | 1 | 0 | \'b\' | 0 | 0 | "ab" | 2 |\n| 3 | 2 | 0 | \'c\' | 0 | 0 | "abc" | 3 |\n| 4 | 3 | 0 | \'a\' | 1 | 1 | "bca" | 3 |\n| 5 | 4 | 1 | \'b\' | 2 | 2 | "cab" | 3 |\n| 6 | 5 | 2 | \'c\' | 3 | 3 | "abc" | 3 |\n| 7 | 6 | 3 | \'b\' | 5 | 5 | "b" | 3 |\n| 8 | 7 | 5 | \'b\' | 6 | 6 | "b" | 3 |\n\n**Result:** The maximum valid window without repeating characters is `"abc"`, with a length of `3`.\n\n\n#### Example 2: **"bbbbb"**\n\n\n\n\n| Step | `end` | `start` | `currentChar` | `lastIndex[currentChar]` | `new start` | `window` | `maxLength` |\n|------|-------|---------|---------------|--------------------------|-------------|----------|-------------|\n| 1 | 0 | 0 | \'b\' | 0 | 0 | "b" | 1 |\n| 2 | 1 | 0 | \'b\' | 1 | 1 | "b" | 1 |\n| 3 | 2 | 1 | \'b\' | 2 | 2 | "b" | 1 |\n| 4 | 3 | 2 | \'b\' | 3 | 3 | "b" | 1 |\n| 5 | 4 | 3 | \'b\' | 4 | 4 | "b" | 1 |\n\n**Result:** The longest substring without repeating characters is `"b"`, with a length of `1`.\n\n\n\n\n#### Example 3: **"pwwkew"**\n\n\n\n\n| Step | `end` | `start` | `currentChar` | `lastIndex[currentChar]` | `new start` | `window` | `maxLength` |\n|------|-------|---------|---------------|--------------------------|-------------|----------|-------------|\n| 1 | 0 | 0 | \'p\' | 0 | 0 | "p" | 1 |\n| 2 | 1 | 0 | \'w\' | 0 | 0 | "pw" | 2 |\n| 3 | 2 | 0 | \'w\' | 2 | 2 | "w" | 2 |\n| 4 | 3 | 2 | \'k\' | 0 | 2 | "wk" | 2 |\n| 5 | 4 | 2 | \'e\' | 0 | 2 | "wke" | 3 |\n| 6 | 5 | 2 | \'w\' | 3 | 3 | "kew" | 3 |\n\n**Result:** The longest substring without repeating characters is `"wke"` or `"kew"`, both with a length of `3`. | 67 | 0 | ['Hash Table', 'Sliding Window', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript'] | 8 |
longest-substring-without-repeating-characters | Python easy solution with comment 90% O(n) speed & 98% space | python-easy-solution-with-comment-90-on-qdnm4 | \nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n seen = \'\'\n mx = 0\n\t\t#1. for each character in s\n for c in s: | kevinko1788 | NORMAL | 2019-09-24T16:12:04.712395+00:00 | 2021-09-12T04:22:11.694672+00:00 | 9,175 | false | ```\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n seen = \'\'\n mx = 0\n\t\t#1. for each character in s\n for c in s:\n\t\t\t#2. check if c is seen\n if c not in seen:\n\t\t\t#3. if not seen, add to seen list \n seen+=c\n #4 if seen, slice seen list to previous c\n # for example, if c is \'a\' and seen list is \'abc\'\n # you will be slicing previous \'a\'(seen.index(c)+1), thus seen list become \'bc\'\n # then add the current \'a\' bc + a, seenlist = \'bca\'\n else:\n seen = seen[seen.index(c) + 1:] + c\n #5 check max length between current max with new length of seen\n mx = max(mx, len(seen))\n return mx\n```\n\nUpdate 09/11/21.\nAnother way of doing it. (not super fast but just for the record)\nusing left and right index with help of dictionary\n\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n seen = {}\n mx = left = 0\n #1. for each character in s\n for right, c in enumerate(s):\n #2. check if c is seen\n if c in seen:\n #3. if seen, advance left index\n left = max(left, seen[c] + 1)\n #4. regardless the character seen or not seen,\n # it will update the index of the charater.\n seen[c] = right\n #5. check max length between current left index and right index + 1\n mx = max(mx, right-left+1)\n return mx\n```\n\nw/o comments\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n seen = {}\n mx = left = 0\n for right, c in enumerate(s):\n if c in seen:\n left = max(left, seen[c] + 1)\n seen[c] = right\n mx = max(mx, right-left+1)\n return mx\n\n``` | 67 | 3 | ['Python'] | 10 |
longest-substring-without-repeating-characters | ✅ [Accepted] Solution for Swift | accepted-solution-for-swift-by-asahiocea-jsiu | \nDisclaimer: By using any content from this post or thread, you release the author(s) from all liability and warranty of any kind. You are free to use the cont | AsahiOcean | NORMAL | 2021-03-30T20:31:01.920651+00:00 | 2023-12-29T22:06:49.585162+00:00 | 9,989 | false | <blockquote>\n<b>Disclaimer:</b> By using any content from this post or thread, you release the author(s) from all liability and warranty of any kind. You are free to use the content freely and as you see fit. Any suggestions for improvement are welcome and greatly appreciated! Happy coding!\n</blockquote>\n\n```swift\nclass Solution {\n func lengthOfLongestSubstring(_ s: String) -> Int {\n var len = 0, chars = [Character]()\n for c in s {\n if let idx = chars.firstIndex(of: c) {\n chars.removeSubrange(0...idx)\n }\n chars.append(c)\n len = max(len, chars.count)\n }\n return len\n }\n}\n```\n\n<b>Playground and test cases: https://leetcode.com/playground/RCFf98E3</b> | 60 | 3 | ['Swift'] | 4 |
longest-substring-without-repeating-characters | Java | TC: O(N) | SC: O(1) | Sliding Window using HashMap & Two Pointers | java-tc-on-sc-o1-sliding-window-using-ha-k4qb | java\n/**\n * Use HashMap to keep char and its index map. When we find a repeating char\n * update the start point.\n *\n * Time Complexity: O(N)\n *\n * Space | NarutoBaryonMode | NORMAL | 2021-10-03T10:42:07.313990+00:00 | 2021-10-07T07:57:27.034560+00:00 | 7,059 | false | ```java\n/**\n * Use HashMap to keep char and its index map. When we find a repeating char\n * update the start point.\n *\n * Time Complexity: O(N)\n *\n * Space Complexity: O(min(M,N)) = O(1) since there are 26 alphabets.\n *\n * N = Length of input string. M = Size of the character set\n */\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n if (s == null) {\n throw new IllegalArgumentException("Input string is null");\n }\n\n int len = s.length();\n if (len <= 1) {\n return len;\n }\n\n HashMap<Character, Integer> map = new HashMap<>();\n int start = 0;\n int maxLen = 0;\n\n for (int end = 0; end < len; end++) {\n char eChar = s.charAt(end);\n if (map.containsKey(eChar)) {\n start = Math.max(start, map.get(eChar) + 1);\n }\n map.put(eChar, end);\n maxLen = Math.max(maxLen, end - start + 1);\n }\n\n return maxLen;\n }\n}\n```\n\n---\n\nSolutions to other Sliding Window questions on LeetCode:\n- [76. Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/discuss/1496754/Java-or-TC:-O(S+T)-or-SC:-O(T)-or-Space-optimized-Sliding-Window-using-Two-Pointers)\n- [340. Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/discuss/1496838/Java-or-TC:-O(N)-or-SC:-O(K)-or-One-Pass-Sliding-Window-using-LinkedHashMap)\n- [159. Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/discuss/1496840/Java-or-TC:-O(N)-or-SC:-O(1)-or-One-Pass-Sliding-Window-using-LinkedHashMap)\n- [438. Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1500039/Java-or-TC:-O(S+P)-or-SC:-O(1)-or-Sliding-window-solution)\n- [209. Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1500877/Java-or-Both-O(N)-and-O(N-logN)-solutions-with-O(1)-space-or-Sliding-Window-and-Binary-Search-solutions)\n- [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/discuss/1500887/Java-or-TC:-O(N)-or-SC:-O(min(N-K))-or-Sliding-Window-using-HashSet)\n- [220. Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/discuss/1500895/Java-or-TC:-O(N)-or-SC:-O(min(NK))-or-Sliding-Window-using-Buckets)\n- [567. Permutation in String](https://leetcode.com/problems/permutation-in-string/discuss/1500902/Java-or-TC:-O(S2)-or-SC:-O(1)-or-Constant-space-Sliding-Window-solution)\n- [239. Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/discuss/1506048/Java-or-TC:-O(N)-or-SC:-O(K)-or-Using-Deque-as-Sliding-Window)\n- [480. Sliding Window Median](https://leetcode.com/problems/sliding-window-median/discuss/1507981/Java-or-TC:-O(N*logK)-or-SC:-(K)-or-Optimized-sliding-window-using-TreeSet)\n- [487. Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii/discuss/1508045/Java-or-TC:-O(N)-or-SC:-O(1)-or-Four-solutions-with-Follow-up-handled)\n- [1004. Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1508044/Java-or-TC:-O(N)-or-SC:-O(1)-or-One-Pass-Optimized-Sliding-Window)\n | 58 | 1 | ['Two Pointers', 'String', 'Sliding Window', 'Java'] | 3 |
longest-substring-without-repeating-characters | 4ms C code in 12 lines | 4ms-c-code-in-12-lines-by-tongxing-kcrx | int lengthOfLongestSubstring(char* s)\n {\n \tint len=0;\n char *end=s,*temp;\n \tchar* addressTable[128]={NULL};\n \twhile(*end){\n \t\tt | tongxing | NORMAL | 2015-07-30T17:27:55+00:00 | 2018-10-24T01:27:41.214611+00:00 | 17,328 | false | int lengthOfLongestSubstring(char* s)\n {\n \tint len=0;\n char *end=s,*temp;\n \tchar* addressTable[128]={NULL};\n \twhile(*end){\n \t\ttemp = addressTable[*end];\n \t\taddressTable[*end]=end;\n \t\tif(temp>=s){\n \t\tlen=end-s>len?end-s:len;\n \t\ts = temp+1;\n \t\t}end++;\n \t}\n \tlen=end-s>len?end-s:len;\n \treturn len;\n } | 55 | 2 | [] | 15 |
longest-substring-without-repeating-characters | Fast(>98%) and simple code in Javascript solution | fast98-and-simple-code-in-javascript-sol-jrw7 | javascript\nvar lengthOfLongestSubstring = function(s) {\n var sLen = s.length,\n maxLen = 0,\n maxStr = '',\n tmpStr,\n posIndex,\n i;\n\n for | arrowing | NORMAL | 2017-06-23T07:47:29.797000+00:00 | 2017-06-23T07:47:29.797000+00:00 | 10,845 | false | ```javascript\nvar lengthOfLongestSubstring = function(s) {\n var sLen = s.length,\n maxLen = 0,\n maxStr = '',\n tmpStr,\n posIndex,\n i;\n\n for( i = 0 ; i < sLen; i++ ){\n\n tmpStr = s[i];\n posIndex = maxStr.indexOf(tmpStr);\n\n if(posIndex > -1){\n maxStr = maxStr.substring(posIndex + 1);\n }\n\n maxStr += tmpStr;\n maxLen = Math.max(maxLen, maxStr.length);\n }\n\n return maxLen;\n};\n``` | 53 | 1 | ['JavaScript'] | 9 |
longest-substring-without-repeating-characters | Java | 2 approaches | using string functions | Hashset | java-2-approaches-using-string-functions-0zf5 | \nPLEASE UPVOTE IF IT HELPS YOU :)\n\n\nApproach 1: Using basic string functions\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n | tarushi0503 | NORMAL | 2022-01-31T13:35:20.346054+00:00 | 2022-01-31T14:30:28.631409+00:00 | 3,538 | false | ```\nPLEASE UPVOTE IF IT HELPS YOU :)\n\n\nApproach 1: Using basic string functions\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n if(s.length()==0)\n return 0;\n char ch=s.charAt(0);\n String ans="";\n ans=ans+ch;\n int max=1;\n for(int i=1;i<s.length();i++){\n ch=s.charAt(i);\n int index=ans.indexOf(ch);\n if(index == -1){\n ans=ans+ch;\n max=Math.max(max,ans.length());\n }\n else{\n ans=ans.substring(index+1)+ch; //if s="dvdf", and when we encounter 2nd d, we need the new ans as "vd" and not just "d"\n }\n }\n return max;\n }\n}\n//TC: O(n)\n\n\nApproach 2: Acquire and Release(Sliding WIndow)\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int acquire=0;\n int release=0;\n int max=0;\n HashSet<Character> hash=new HashSet();\n while(acquire<s.length()){\n if(!hash.contains(s.charAt(acquire))){\n hash.add(s.charAt(acquire));\n acquire++;\n max=Math.max(hash.size(),max);\n }\n else{\n hash.remove(s.charAt(release));\n release++;\n }\n }\n return max;\n }\n}\n``` | 47 | 1 | ['Sliding Window', 'Java'] | 5 |
longest-substring-without-repeating-characters | C++ Sliding Window & Hash Map Easy Solution | c-sliding-window-hash-map-easy-solution-84oqp | \nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n \n unordered_map<char,int> index;\n int start=0,res=0;\n | hitengoyal18 | NORMAL | 2021-04-26T06:30:40.639634+00:00 | 2021-04-26T06:30:40.639665+00:00 | 6,376 | false | ```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n \n unordered_map<char,int> index;\n int start=0,res=0;\n for(int i=0;i<s.length();i++){\n \n if (index.find(s[i]) != index.end() && index[s[i]] >= start)\n start = index[s[i]] + 1;\n \n index[s[i]] = i;\n res=max(res,i-start+1);\n }\n \n return res;\n }\n};\n``` | 47 | 2 | ['C', 'Sliding Window', 'C++'] | 2 |
longest-substring-without-repeating-characters | Well-commented JavaScript Sliding Window solution with Set - O(n) time O(n) space | well-commented-javascript-sliding-window-8zwa | right and left are pointers in the string -- for the maxLength = Math.max.... line we could also do ...Math.max(maxLength, right - left + 1) but set.size could | albertchanged | NORMAL | 2020-11-07T20:51:02.325185+00:00 | 2020-11-07T21:14:08.823343+00:00 | 2,694 | false | ```right``` and ```left``` are pointers in the string -- for the ```maxLength = Math.max....``` line we could also do ```...Math.max(maxLength, right - left + 1)``` but ```set.size``` could make more sense for some people.\n\nExplanation is under the code.\n\n```\nvar lengthOfLongestSubstring = function(s) {\n if (!s.length) return 0;\n \n let left = 0, right = 0;\n let maxLength = -Infinity;\n const set = new Set();\n\n while (right < s.length) {\n // If s[right] has not been seen yet\n if (!set.has(s[right])) {\n // Add it to the set\n set.add(s[right]);\n // Increase size of window to right\n right++;\n // Update maxLength; set size represents length of unique substring\n maxLength = Math.max(maxLength, set.size);\n } else {\n // We\'ve seen s[right] so we need to shrink the window\n // Delete s[left] from set\n set.delete(s[left]);\n // Shrink window from left\n left++;\n }\n }\n\n return maxLength;\n}\n```\n\nFor example, in "abbc":\n\n1. left = 0, right = 0, ```s[right]``` = a, ```s[left]``` = a\n\t- set does not contain a, add to set\n```set = [a]```\n\t- Update maxLength to 1\n\t- Increment right\n2. left = 0, right = 1, ```s[right]``` = b, ```s[left]``` = a\n\t- set does not contain b, add to set\n```set = [a, b]```\n\t- Update maxLength to 2\n\t- Increment right\n3. left = 0, right = 2, ```s[right]``` = b, ```s[left]``` = a\n\t- set already contains b\n\t- Delete ```s[left]``` from set\n\t```set = [b]```\n\t- Increment left\n\n4. left = 1, right = 2, ```s[right]``` = b, ```s[left]``` = b\n\t- set already contains b\n\t- Delete ```s[left]``` from set\n\t```set = []```\n\t- Increment left\n5. left = 2, right = 2, ```s[right]``` = b, ```s[left]``` = b\n\t- set does not contain b, add to set\n\t```set = [b]```\n\t- maxLength does not change, since 1 < 2\n\t- Increment right\n6. left = 2, right = 3, ```s[right]``` = c, ```s[left]``` = b\n\t- set does not contain c, add to set\n\t```set = [b, c]```\n\t- maxLength does not change, since 2 === 2\n\t- Increment right\n\n7. right = 4, which is out of bounds of the while loop\n8. Exit loop and return maxLength\n\n | 43 | 0 | ['Sliding Window', 'JavaScript'] | 3 |
longest-substring-without-repeating-characters | JavaScript Sliding Window | javascript-sliding-window-by-daleighan-7lrj | \nfunction lengthOfLongestSubstring(s) {\n let seen = new Set();\n let longest = 0;\n let l = 0;\n for (let r = 0; r < s.length; r++) {\n while (seen.has | daleighan | NORMAL | 2020-01-10T03:47:16.267601+00:00 | 2020-01-10T03:47:16.267635+00:00 | 7,027 | false | ```\nfunction lengthOfLongestSubstring(s) {\n let seen = new Set();\n let longest = 0;\n let l = 0;\n for (let r = 0; r < s.length; r++) {\n while (seen.has(s[r])) {\n seen.delete(s[l]);\n l++;\n }\n seen.add(s[r]);\n longest = Math.max(longest, r - l + 1);\n }\n return longest;\n};\n``` | 41 | 0 | ['Sliding Window', 'JavaScript'] | 5 |
longest-substring-without-repeating-characters | My O(n) Solution | my-on-solution-by-heiyanbin-m5p0 | if only use DP, it's an O(n*n) solution, adding a map to get O(n).\n \n class Solution {\n public:\n int lengthOfLongestSubstring(string | heiyanbin | NORMAL | 2014-06-12T11:02:24+00:00 | 2014-06-12T11:02:24+00:00 | 24,095 | false | if only use DP, it's an O(n*n) solution, adding a map to get O(n).\n \n class Solution {\n public:\n int lengthOfLongestSubstring(string s) {\n if(s.size()<2) return s.size();\n int d=1, maxLen=1;\n unordered_map<char,int> map;\n map[s[0]]=0;\n for(int i=1;i<s.size();i++)\n {\n if(map.count(s[i])==0 || map[s[i]]<i-d)\n d++;\n else\n d= i- map[s[i]];\n map[s[i]]=i;\n if(d>maxLen)\n maxLen = d;\n }\n return maxLen;\n }\n }; | 40 | 3 | [] | 12 |
longest-substring-without-repeating-characters | Simple Javascript Code | simple-javascript-code-by-nilath-a84b | Currently, migrating my c++ code to Javascript code.\n\n\n var lengthOfLongestSubstring = function(s) {\n var start = 0, maxLen = 0;\n var map = ne | nilath | NORMAL | 2016-12-22T16:07:48.236000+00:00 | 2016-12-22T16:07:48.236000+00:00 | 12,424 | false | Currently, migrating my c++ code to Javascript code.\n\n\n var lengthOfLongestSubstring = function(s) {\n var start = 0, maxLen = 0;\n var map = new Map();\n \n for(var i = 0; i < s.length; i++) {\n var ch = s[i];\n \n if(map.get(ch) >= start) start = map.get(ch) + 1;\n map.set(ch, i);\n \n if(i - start + 1 > maxLen) maxLen = i - start + 1;\n }\n \n return maxLen;\n }; | 38 | 2 | [] | 8 |
longest-substring-without-repeating-characters | 8 Lines of Python code , TC: O(N) =>The easiest way anyone can understand, with 97% TC and 99% SC | 8-lines-of-python-code-tc-on-the-easiest-wo6e | \nresult =""\nmax_length = 0\nfor i in s:\n\tif i in result:\n\t\tresult = result[result.index(i)+1:]\n\t\t"""if abcdas is the string, here after abcd the lengt | sudharshan1706 | NORMAL | 2021-09-06T15:03:55.302101+00:00 | 2022-08-10T04:33:20.765587+00:00 | 2,456 | false | ```\nresult =""\nmax_length = 0\nfor i in s:\n\tif i in result:\n\t\tresult = result[result.index(i)+1:]\n\t\t"""if abcdas is the string, here after abcd the length would be 4 and result will be replaced as bcda"""\n\tresult += i\n\tmax_length = max(max_length, len(result))\nreturn (max_length)\n```\n\n\nif you understand, please upvote :).\nwill build my confidence\nthank you :) | 35 | 1 | ['Python'] | 6 |
longest-substring-without-repeating-characters | [Python] O(n) sliding window, explained | python-on-sliding-window-explained-by-db-evto | This is classical problem for sliding window. Let us keep window with elements [beg: end), where first element is included and last one is not. For example [0, | dbabichev | NORMAL | 2021-01-07T08:15:30.320934+00:00 | 2021-01-07T08:15:30.320979+00:00 | 1,783 | false | This is classical problem for sliding window. Let us keep window with elements `[beg: end)`, where first element is included and last one is not. For example `[0, 0)` is empty window, and `[2, 4)` is window with `2` elements: `2` and `3`.\nLet us discuss our algorithm now:\n1. `window` is set of symbols in our window, we use set to check in `O(1)` if new symbol inside it or not.\n2. `beg = end = 0` in the beginning, so we start with empty window, also `ans = 0` and `n = len(s)`.\n3. Now, we continue, until one of two of our pointers reaches the end. First, we try to extend our window to the right: check `s[end] in window` and if we can, add it to set, move `end` pointer to the right and update `ans`. If we can not add new symbol to set, it means it is already in `window` set, and we need to move left pointer and move `beg` pointer to the right.\n\n**Complexity**: we move both of our pointers only to the left, so time complexity is `O(n)`. Space complexity is `O(1)`.\n\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s):\n window = set()\n beg, end, ans, n = 0, 0, 0, len(s)\n \n while beg < n and end < n:\n if s[end] not in window:\n if end + 1 < n: window.add(s[end])\n end += 1\n ans = max(ans, end - beg)\n else:\n window.remove(s[beg])\n beg += 1\n \n return ans\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 35 | 0 | ['Two Pointers', 'Sliding Window'] | 7 |
longest-substring-without-repeating-characters | My easy solution in JAVA (O(N)) . | my-easy-solution-in-java-on-by-ink213-xxij | public class Solution {\n public int lengthOfLongestSubstring(String s) {\n int[] mOccur = new int[256];\n int maxL = 0;\n | ink213 | NORMAL | 2015-08-21T09:09:16+00:00 | 2018-08-17T17:01:56.512081+00:00 | 13,733 | false | public class Solution {\n public int lengthOfLongestSubstring(String s) {\n int[] mOccur = new int[256];\n int maxL = 0;\n for(int i = 0, j = 0; i < s.length(); ++i){\n char ch = s.charAt(i);\n ++mOccur[ch];\n while(mOccur[ch] > 1){\n --mOccur[s.charAt(j++)];\n }\n maxL = Math.max(maxL, i - j + 1);\n }\n return maxL;\n }\n } | 34 | 2 | ['Hash Table', 'Java'] | 4 |
longest-substring-without-repeating-characters | 2 Straightforward C# Solutions w/ explanation + Sliding Window | 2-straightforward-c-solutions-w-explanat-mbj1 | Approach 1: Sliding Window\n\nImplementation\n\npublic int LengthOfLongestSubstring(string s) {\n\tvar letters = new Dictionary<char, int>(); // key:letter, val | minaohhh | NORMAL | 2021-05-19T10:46:44.086186+00:00 | 2022-08-15T11:41:32.430872+00:00 | 6,741 | false | ### **Approach 1: Sliding Window**\n\n**Implementation**\n```\npublic int LengthOfLongestSubstring(string s) {\n\tvar letters = new Dictionary<char, int>(); // key:letter, val: latest index\n\tint maxCount = 0, left = 0, right;\n\n\tfor (right = 0; right < s?.Length; right++) {\n\t\tchar letter = s[right];\n\n\t\tif (letters.ContainsKey(letter)) { // End the window\n\t\t\tleft = Math.Max(left, letters[letter] + 1); // Update left of window\n\t\t}\n\n\t\tletters[letter] = right; //Update index of letter on map\n\n\t\tmaxCount = Math.Max(maxCount, right - left + 1); // Get the longest window length \n\t}\n\n\treturn maxCount;\n}\n```\n\n---\n\n### **Approach 2: Using a list to remember the substring length**\n*(faster than 89%, memory less than 99%) *\n\n**Algorithm**\n* Use a list `letters` to remember the substrings with unique characters\n* If a duplicate is detected,\n\t* Get the substring `length` and determine the `maxLength`\n\t* Remove the preceding characters up to the duplicate letter from the list using `RemoveRange`\n* Continue until the end \n\n**Complexity**\n* Time: `O(n)`, where `n` is the length of the string `s`\n* Space: `O(n)` since we created the list `letters` that will contain a maximum of all the letters in the entire string `s`\n\n**Implementation**\n```csharp\npublic class Solution {\n public int LengthOfLongestSubstring(string s) {\n List<char> letters = new List<char>();\n int maxLength = 0;\n \n foreach (char c in s) {\n if (!letters.Contains(c)) {\n letters.Add(c);\n }\n else {\n maxLength = Math.Max(maxLength, letters.Count);\n \n // remove preceding characters up to the duplicate letter\n int idx = letters.IndexOf(c);\n letters.RemoveRange(0, idx+1);\n\n letters.Add(c);\n }\n }\n \n return Math.Max(maxLength, letters.Count); \n }\n}\n```\n\n**If you like the solution, please upvote \uD83D\uDD3C** | 33 | 0 | ['Sliding Window', 'C#'] | 4 |
longest-substring-without-repeating-characters | Java simple | java-simple-by-georgcantor-gy0d | \npublic int lengthOfLongestSubstring(String s) {\n int start = 0;\n int end = 0;\n int max = 0;\n Set<Character> set = new HashSet< | GeorgCantor | NORMAL | 2021-01-30T10:37:24.695595+00:00 | 2022-03-01T15:36:55.129271+00:00 | 4,261 | false | ```\npublic int lengthOfLongestSubstring(String s) {\n int start = 0;\n int end = 0;\n int max = 0;\n Set<Character> set = new HashSet<>();\n while (end < s.length()) {\n if (!set.contains(s.charAt(end))) {\n set.add(s.charAt(end));\n end++;\n max = Math.max(set.size(), max);\n } else {\n set.remove(s.charAt(start));\n start++;\n }\n }\n\n return max;\n }\n``` | 33 | 2 | ['Java'] | 8 |
longest-substring-without-repeating-characters | C++ | Short & Easy Solutions ✅ | c-short-easy-solutions-by-prantik0128-5kq1 | Please upvote if you like the solution & post :)\n\nSliding-window + Unordered_set Solution:\n\nclass Solution {\npublic:\n\tint lengthOfLongestSubstring(string | prantik0128 | NORMAL | 2022-06-10T03:49:15.789465+00:00 | 2022-06-10T04:19:10.484451+00:00 | 3,404 | false | **`Please upvote if you like the solution & post :)`**\n\n**`Sliding-window + Unordered_set` Solution:**\n```\nclass Solution {\npublic:\n\tint lengthOfLongestSubstring(string s) {\n\t\tunordered_set<char> set;\n\t\tint i = 0, j = 0, n = s.size(), ans = 0;\n\t\twhile(j<n){\n\t\t\tif(set.find(s[j]) == set.end()){ //If the character does not in the set\n\t\t\t\tset.insert(s[j++]); //Insert the character in set and update the j counter\n\t\t\t\tans = max(ans, j-i); //Check if the new distance is longer than the current answer\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//If character does exist in the set, ie. it is a repeated character, \n\t\t\t\t//we update the left side counter i, and continue with the checking for substring. \n\t\t\t\tset.erase(s[i++]); \n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n};\n```\n\n**Time Complexity :** `O(n)`\n**Space Complexity :** `O(min(a,b))` for the `unordered_set`, `a` is the upper bound & is the `size` of the string while `b` is the size of number of `characters` in the character set\n\n****\n**`Using Frequency Array` Solution:**\n```\nint lengthOfLongestSubstring(string s) {\n int freq[256]={0};\n int l=0,r=0,ans=0,n=s.size();\n while(r<n){\n freq[s[r]]++;\n while(freq[s[r]]>1){\n freq[s[l]]--;\n l++;\n }\n ans = max(ans,r-l+1);\n r++;\n }\n return ans;\n }\n```\n**Time Complexity :** `O(n)`\n**Space Complexity :** `O(n)`\n**** | 32 | 3 | ['C', 'Sliding Window'] | 4 |
longest-substring-without-repeating-characters | ✅ [Python] Simple Solution w/ Explanation | Brute-Force + Sliding Window | python-simple-solution-w-explanation-bru-75l4 | We are given a string s. We need to find the length of the longest substring without repeating characters.\n\n\n\u2705 Solution I - Brute-Force [Accepted]\n\nSt | r0gue_shinobi | NORMAL | 2022-06-10T02:08:17.743152+00:00 | 2022-06-10T02:48:50.359521+00:00 | 5,381 | false | We are given a string `s`. We need to find the length of the **longest substring** without repeating characters.\n___\n___\n\u2705 **Solution I - Brute-Force [Accepted]**\n\nStarting with each index, we can check all substrings till we find a repeating character.\n\n```python\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n res = 0\n seen = set()\n for start_idx in range(len(s)):\n seen.clear()\n end_idx = start_idx\n while end_idx < len(s):\n if s[end_idx] in seen:\n break\n seen.add(s[end_idx])\n end_idx += 1\n res = max(res, end_idx - start_idx)\n return res\n```\n\n- **Time Complexity:** `O(n\xB2)`\n- **Space Complexity:** `O(1)`\n___\n\u2705 **Solution II - Sliding Window [Accepted]**\n\nIn the above solution, we are doing many redundant operations. After finding a repeating character, we break the inner loop and again check for all substrings from the next index.\nThe following example will make it clear what I mean by redundant operations:\n\n```text\ns = "redundant"\nLet start_idx = 0\nWhen end_idx becomes 5, it sees that "d" had already come before.\nSo, should we start again with index 1?\nNo, because all substrings starting with "e" and later (till "d" or the character which was repeated) will have less length than that of "redun".\nWe can start from "u"\n```\n\nWe can create a sliding window: `[start_idx: end_idx]` where `end_idx` will move forward continuously and `start_idx` will change only if the character at `end_idx` is already present within this window. To know whether this character is already present, we need to store information about the index of characters.\n\n```python\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n prev = [-1] * 128\n res, start_idx = 0, 0\n for end_idx, char in enumerate(s):\n if prev[ord(char)] >= start_idx:\n start_idx = prev[ord(char)] + 1\n prev[ord(char)] = end_idx\n res = max(res, end_idx - start_idx + 1)\n \n return res\n```\n\n- **Time Complexity:** `O(n)`\n- **Space Complexity:** `O(1)`\n\n___\n___\nIf you like the solution, please **upvote** \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n | 32 | 1 | ['Two Pointers', 'Sliding Window', 'Python', 'Python3'] | 6 |
longest-substring-without-repeating-characters | O(n) time O(1) space solution using Kadane's algo in Java | on-time-o1-space-solution-using-kadanes-9zctm | Idea is that, while we traverse form left to right if we see a character at position j is a duplicate of a character at a position i < j on the left then we kno | zahid2 | NORMAL | 2015-10-06T22:54:31+00:00 | 2018-09-22T23:39:15.493105+00:00 | 12,668 | false | Idea is that, while we traverse form left to right if we see a character at position j is a duplicate of a character at a position i < j on the left then we know that we can't start the substring from i anymore. So, we need to start a new substring from i+1 position. While doing this we also need to update the length of current substring and start of current substring. Important part of this process is to make sure that we always keep the latest position of the characters we have seen so far. Below is a simple O(n) implementation of this logic.\n\n\n public class Solution {\n public int lengthOfLongestSubstring(String s) {\n int lastIndices[] = new int[256];\n for(int i = 0; i<256; i++){\n lastIndices[i] = -1;\n }\n \n int maxLen = 0;\n int curLen = 0;\n int start = 0;\n int bestStart = 0;\n for(int i = 0; i<s.length(); i++){\n char cur = s.charAt(i);\n if(lastIndices[cur] < start){\n lastIndices[cur] = i;\n curLen++;\n }\n else{\n int lastIndex = lastIndices[cur];\n start = lastIndex+1;\n curLen = i-start+1;\n lastIndices[cur] = i;\n }\n \n if(curLen > maxLen){\n maxLen = curLen;\n bestStart = start;\n }\n }\n \n return maxLen;\n }\n } | 31 | 2 | [] | 16 |
longest-substring-without-repeating-characters | LengthOfLongestSubstring in C# using Sliding window approach. O(n) | lengthoflongestsubstring-in-c-using-slid-wojh | \n# Approach\n Describe your approach to solving the problem. \nThis solution uses a sliding window approach to find the longest\nsubstring without repeating ch | daniel-m | NORMAL | 2023-01-26T18:06:04.036467+00:00 | 2023-01-26T18:06:04.036524+00:00 | 8,135 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis solution uses a sliding window approach to find the longest\nsubstring without repeating characters.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(min(n, m))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int LengthOfLongestSubstring(string s) {\n var charSet = new HashSet<char>();\n int left = 0, right = 0, maxLength = 0;\n while(right < s.Length)\n {\n if (!charSet.Contains(s[right]))\n {\n charSet.Add(s[right]);\n right++;\n maxLength = Math.Max(maxLength, charSet.Count);\n }\n else\n {\n charSet.Remove(s[left]);\n left++;\n }\n }\n return maxLength;\n }\n}\n``` | 29 | 0 | ['C#'] | 5 |
longest-substring-without-repeating-characters | O(n) JavaScript + TypeScript with detailed explanatory comments | on-javascript-typescript-with-detailed-e-emfg | \n// We can solve this using a dynamic "sliding window" that \n// shrinks or grows whenever certain conditions are met\n\nconst lengthOfLongestSubstring = funct | christopher4lis | NORMAL | 2021-10-19T20:11:06.493616+00:00 | 2021-10-19T20:11:31.351283+00:00 | 4,097 | false | ```\n// We can solve this using a dynamic "sliding window" that \n// shrinks or grows whenever certain conditions are met\n\nconst lengthOfLongestSubstring = function(characters: string) {\n // Setting to 0 takes care of the edge case where "characters" is \'\'\n let length = 0\n \n // Map will store each character and the last index they were looped over at\n let characterMap = new Map()\n \n // We declare a left index since a sliding window requires two indices\n // (left and right) to track the window of elements the indices surround\n let leftIndex = 0\n \n // Begin looping through each character in the string.\n // rightIndex will always be greater the leftIndex to create a "window" of elements\n for (let rightIndex = 0; rightIndex < characters.length; rightIndex++) {\n \n // Get current character for better readability\n const character = characters[rightIndex]\n \n // Check if character exists and if its last index is greater than the\n // current leftIndex. If we don\'t check it\'s leftIndex, we\'re setting\n // it to a previous result which\'ll provide incorrect values \n // when calculating the window length\n if (characterMap.has(character) && characterMap.get(character) >= leftIndex) {\n // set left index to last index where the character was found plus one\n leftIndex = characterMap.get(character) + 1\n }\n \n // Which is greater, the last iteration\'s window length, or the current\n // interation\'s window length? We decide here, then set our result length\n // to that number. We add 1 since we need to take into account every element\n // within the window (2 - 0 = 2, although there are three elements, so add 1) \n length = Math.max(length, rightIndex - leftIndex + 1)\n \n // Add character and its index to map, or, if it exists,\n // automatically overwrite its index with the current\n characterMap.set(character, rightIndex)\n }\n \n return length\n};\n``` | 29 | 0 | ['Sliding Window', 'TypeScript', 'JavaScript'] | 7 |
longest-substring-without-repeating-characters | C++ | O(N) | Using Frequency Map | | c-on-using-frequency-map-by-persistentbe-b5tx | Use Sliding Window approach using frequency map.\n As soon as frequency of any character becomes more than one, contract window till frequency of that character | persistentBeast | NORMAL | 2022-06-10T06:11:33.175975+00:00 | 2022-06-11T07:45:14.350588+00:00 | 4,265 | false | * Use Sliding Window approach using frequency map.\n* As soon as frequency of any character becomes more than one, contract window till frequency of that character reduces to 1.\n* Window is marked by `st` and `end` index.\n* Update `ans` at each `end` index.\n* **TC : O(N)**\n```\nclass Solution {\npublic: \n int lengthOfLongestSubstring(string s) { \n unordered_map<char, int> freq; \n int n = s.length(), st = 0, end = 0, ans = 0;\t\t\n while(end < n){ \n freq[s[end]]++; \n while(freq[s[end]] != 1){\n freq[s[st]]--;\n st++;\n } \n ans = max(ans, end - st + 1);\n end++; \n } \n return ans; \n }\n};\n``` | 28 | 1 | ['C', 'Sliding Window'] | 3 |
longest-substring-without-repeating-characters | ✔️ 100% Fastest TypeScript Solution | 100-fastest-typescript-solution-by-serge-bg9p | \nfunction lengthOfLongestSubstring(s: string): number {\n const scanner: string[] = []\n let longest = 0\n\n for (const char of s) {\n const possibleInde | sergeyleschev | NORMAL | 2022-03-27T12:34:35.844577+00:00 | 2022-03-30T16:44:12.017654+00:00 | 7,959 | false | ```\nfunction lengthOfLongestSubstring(s: string): number {\n const scanner: string[] = []\n let longest = 0\n\n for (const char of s) {\n const possibleIndex = scanner.indexOf(char)\n\n if (possibleIndex !== -1) { scanner.splice(0, possibleIndex + 1) }\n scanner.push(char)\n longest = Math.max(longest, scanner.length)\n }\n\n return longest\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 28 | 1 | ['TypeScript', 'JavaScript'] | 6 |
longest-substring-without-repeating-characters | C++/Java/Python/JavaScript || ✅✅Sliding Window || ✅🔥🚀100% Solution Explained | cjavapythonjavascript-sliding-window-100-6trh | Intuition:\n\nThe problem requires us to find the length of the longest substring without repeating characters in a given string. We can use a sliding window te | devanshupatel | NORMAL | 2023-05-07T13:58:17.058470+00:00 | 2023-05-07T13:58:17.058507+00:00 | 21,299 | false | # Intuition:\n\nThe problem requires us to find the length of the longest substring without repeating characters in a given string. We can use a sliding window technique to keep track of the longest substring without repeating characters. \n\n# Approach:\n1. Initialize ans=0, l=0, r=0.\n2. Create a map of size 256 to store the last occurrence of each character in the string, initialized with -1.\n3. Traverse the string from left to right, with the right end of the window (r) expanding as long as there are no repeating characters.\n4. When a repeating character is found at index r, we update the left end of the window (l) to the next index of the repeated character. \n5. Update the map with the current index of the repeated character.\n6. Update ans with the maximum length of the current substring and the previous maximum.\n7. Return ans.\n\n# Complexity:\n- Time complexity: The algorithm traverses the given string only once. The time complexity is O(n), where n is the length of the string.\n- Space complexity: The space required to store the map is O(256), which is constant. Therefore, the space complexity is O(1).\n\n---\n# C++\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int ans=0,l=0,r=0;\n int n =s.size();\n vector<int> map(256,-1);\n while(r<n){\n if(map[s[r]]!=-1){\n l=max(map[s[r]]+1,l);\n }\n map[s[r]]=r;\n ans= max(ans,r-l+1);\n r++;\n }\n return ans;\n }\n};\n```\n\n---\n# JAVA\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int ans = 0, l = 0, r = 0;\n int n = s.length();\n int[] map = new int[256];\n Arrays.fill(map, -1);\n while (r < n) {\n if (map[s.charAt(r)] != -1) {\n l = Math.max(map[s.charAt(r)] + 1, l);\n }\n map[s.charAt(r)] = r;\n ans = Math.max(ans, r - l + 1);\n r++;\n }\n return ans;\n }\n}\n\n```\n\n---\n\n# Python\n```\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n ans, l, r = 0, 0, 0\n n = len(s)\n map = [-1] * 256\n while r < n:\n if map[ord(s[r])] != -1:\n l = max(map[ord(s[r])] + 1, l)\n map[ord(s[r])] = r\n ans = max(ans, r - l + 1)\n r += 1\n return ans\n\n```\n---\n\n# JavaScript\n```\nvar lengthOfLongestSubstring = function(s) {\n let ans = 0, l = 0, r = 0;\n let n = s.length;\n let map = new Array(256).fill(-1);\n while (r < n) {\n if (map[s.charCodeAt(r)] != -1) {\n l = Math.max(map[s.charCodeAt(r)] + 1, l);\n }\n map[s.charCodeAt(r)] = r;\n ans = Math.max(ans, r - l + 1);\n r++;\n }\n return ans;\n};\n``` | 27 | 0 | ['Sliding Window', 'Python', 'C++', 'Java', 'JavaScript'] | 4 |
longest-substring-without-repeating-characters | Intuitive JavaScript solution with Sliding Window | intuitive-javascript-solution-with-slidi-qxi9 | \n/**\n * @param {string} s\n * @return {number}\n */\nvar lengthOfLongestSubstring = function(s) {\n const set = new Set();\n let longest = 0;\n let i | dawchihliou | NORMAL | 2020-04-13T09:31:54.691407+00:00 | 2020-04-13T09:31:54.691456+00:00 | 2,840 | false | ```\n/**\n * @param {string} s\n * @return {number}\n */\nvar lengthOfLongestSubstring = function(s) {\n const set = new Set();\n let longest = 0;\n let i = 0;\n let j = 0;\n /**\n * The goal is to anchor i and find the longest range of [i, j].\n * When s[i, j] has a duplicate letter, we remove s[i] from the\n * set and move i to the next position so we don\'t include \n * s[prev i] in the next range calculation.\n */\n while (i < s.length && j < s.length) {\n if (!set.has(s[j])) {\n set.add(s[j]);\n longest = Math.max(longest, j - i + 1);\n j += 1;\n } else {\n set.delete(s[i]);\n i += 1;\n }\n }\n return longest;\n};\n``` | 27 | 0 | ['Sliding Window', 'JavaScript'] | 1 |
longest-substring-without-repeating-characters | Simple Python3 Solution using Sliding window || Beats 99% || 💻🧑💻🤖 | simple-python3-solution-using-sliding-wi-mx3s | \n\n# Code\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n l=len(s)\n if l==0:\n return 0\n dicts={ | Abhishek2708 | NORMAL | 2023-09-08T16:59:29.890257+00:00 | 2023-09-13T11:21:57.207303+00:00 | 3,404 | false | \n\n# Code\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n l=len(s)\n if l==0:\n return 0\n dicts={}\n max_len=0\n start=0\n for i in range(l):\n if s[i] in dicts and start<=dicts[s[i]]:\n start = dicts[s[i]]+1\n else:\n max_len=max(max_len,i-start+1)\n dicts[s[i]]=i\n return max_len\n \n```\n\n | 26 | 0 | ['Python3'] | 3 |
longest-substring-without-repeating-characters | Python. Cool & easy solution. O(n) time. O(1) space. | python-cool-easy-solution-on-time-o1-spa-ctfb | \tclass Solution:\n\t\tdef lengthOfLongestSubstring(self, s: str) -> int:\n\t\t\tcharacters = set()\n\t\t\tleft = right = ans = 0\n\t\t\tlength = len(s)\n\t\t\t | m-d-f | NORMAL | 2021-01-07T08:58:48.325249+00:00 | 2021-01-07T08:58:48.325304+00:00 | 3,522 | false | \tclass Solution:\n\t\tdef lengthOfLongestSubstring(self, s: str) -> int:\n\t\t\tcharacters = set()\n\t\t\tleft = right = ans = 0\n\t\t\tlength = len(s)\n\t\t\t\n\t\t\twhile right < length:\n\t\t\t\tif s[right] in characters:\n\t\t\t\t\tcharacters.remove(s[left])\n\t\t\t\t\tleft += 1\n\t\t\t\telse:\n\t\t\t\t\tcharacters.add(s[right])\n\t\t\t\t\tright += 1\n\t\t\t\t\tans = max(ans, right - left)\n\t\t\t\n\t\t\treturn ans | 26 | 3 | ['Python', 'Python3'] | 6 |
longest-substring-without-repeating-characters | c# | c-by-csharp-3i9x | ```\npublic class Solution {\n public int LengthOfLongestSubstring(string s) {\n if (s == null || s == String.Empty)\n return 0;\n\ | csharp | NORMAL | 2020-06-02T07:04:35.480255+00:00 | 2020-06-02T07:04:35.480294+00:00 | 5,392 | false | ```\npublic class Solution {\n public int LengthOfLongestSubstring(string s) {\n if (s == null || s == String.Empty)\n return 0;\n\n HashSet<char> set = new HashSet<char>();\n int currentMax = 0,\n i = 0,\n j = 0;\n\n while (j < s.Length)\n if (!set.Contains(s[j]))\n {\n set.Add(s[j++]);\n currentMax = Math.Max(currentMax, j - i);\n }\n else\n set.Remove(s[i++]);\n\n return currentMax;\n }\n} | 26 | 4 | [] | 0 |
longest-substring-without-repeating-characters | Swift, faster than 79.38% of swift submissions | swift-faster-than-7938-of-swift-submissi-u3ij | O(n)\n\nclass Solution {\n func lengthOfLongestSubstring(_ s: String) -> Int {\n var longest = 0, startIndex = 0\n var charMap: [Character: Int | rshev | NORMAL | 2020-03-07T18:07:23.154515+00:00 | 2020-03-07T18:07:23.154547+00:00 | 2,887 | false | O(n)\n```\nclass Solution {\n func lengthOfLongestSubstring(_ s: String) -> Int {\n var longest = 0, startIndex = 0\n var charMap: [Character: Int] = [:]\n\n for (index, char) in s.enumerated() {\n if let foundIndex = charMap[char] {\n startIndex = max(foundIndex+1, startIndex)\n }\n longest = max(longest, index - startIndex + 1)\n charMap[char] = index\n }\n return longest\n }\n}\n``` | 26 | 0 | ['Swift'] | 3 |
longest-substring-without-repeating-characters | Java concise HashMap solution. | java-concise-hashmap-solution-by-oldcodi-clr7 | \n public int lengthOfLongestSubstring(String s) {\n int ret = 0;\n Map<Character, Integer> map = new HashMap<>();\n for (int i = 0, sta | oldcodingfarmer | NORMAL | 2016-04-10T13:33:07+00:00 | 2016-04-10T13:33:07+00:00 | 4,867 | false | \n public int lengthOfLongestSubstring(String s) {\n int ret = 0;\n Map<Character, Integer> map = new HashMap<>();\n for (int i = 0, start = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (map.containsKey(c)) \n start = Math.max(map.get(c)+1, start);\n ret = Math.max(ret, i-start+1); \n map.put(c, i);\n }\n return ret;\n } | 26 | 4 | ['Java'] | 0 |
longest-substring-without-repeating-characters | Simple and fast C++ solution | simple-and-fast-c-solution-by-shubit-dcl8 | Intuition\nWe iterate over the input and maintain a [start, i] interval that only contains unique characters. For every character s[i] we first advance start un | shubit | NORMAL | 2023-04-20T18:05:44.017880+00:00 | 2023-04-20T18:05:44.017919+00:00 | 6,056 | false | # Intuition\nWe iterate over the input and maintain a $$[start, i]$$ interval that only contains unique characters. For every character $$s[i]$$ we first advance $$start$$ until $$[start, i-1]$$ doesn\'t $$s[i]$$. The longest $$i-start+1$$ is the longest substring.\n\n# Complexity\n- Time complexity: $$O(n)$$ (iterate once over the input)\n\n- Space complexity: $$O(1)$$ (space needed doesn\'t depend on input size)\n\n# Code\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n\t\t\tif (s.empty()) return 0; \n\t\t int result = 0; // Length of longest substring found so far.\n\t\t int start = 0; // Start index of current substring with unique characters.\n\t\t\t// Track if a character is in [start, i]. `char` is 8-bit (hence 256 possibilties).\n\t\t\t// More generic, but slower, would be a std::unordered_set<char>.\n\t\t std::vector<bool> chars_in_substring;\n\t\t chars_in_substring.resize(256);\n\t\t for (int i = 0; i < s.size(); ++i) {\n\t\t\t\t// Advance `start` until [start, i] contains only unique characters.\n\t\t\t\t// This means s[i] cannot be in [start, i-1].\n\t\t\t while (chars_in_substring[s[i]]) {\n\t\t\t\t chars_in_substring[s[start++]] = false;\n\t\t\t }\n\t\t\t chars_in_substring[s[i]] = true;\n\t\t\t\t// Is this our new longest substring?\n\t\t\t result = std::max(result, i-start+1);\t\n\t\t }\n\t\t return result;\n }\n};\n``` | 25 | 0 | ['C++'] | 9 |
longest-substring-without-repeating-characters | Python Easy 2 approaches ✅ | python-easy-2-approaches-by-constantine7-zd7z | Sliding Window - Counter\n\nThis approach uses counter variable to track number of characters in a sliding window. Whenever we encounter a state where the windo | constantine786 | NORMAL | 2022-06-10T00:29:20.091247+00:00 | 2022-06-10T00:29:20.091276+00:00 | 3,919 | false | 1. ## **Sliding Window - Counter**\n\nThis approach uses `counter` variable to track number of characters in a sliding window. Whenever we encounter a state where the window becomes invalid due to number of characters(count of any character > 1), we would update the left bound of the new valid window.\n\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n counter = defaultdict(int) # track counts of each character\n l=0\n max_length=0\n for r, c in enumerate(s):\n counter[c]+=1 \n if counter[c] > 1: \n while l<r and counter[c]>1: # iterate until window is valid\n counter[s[l]]-=1\n l+=1\n max_length=max(max_length, r-l+1)\n return max_length\n```\n**Time - O(2n)** - Iterates both `l` and `r` once through the input `s`.\n**Space - O(n)**\n\n---\n\n2. ## **Sliding Window - Last Seen**\n\nIf we observe the previous approach, we would notice we don\'t need to track the counts of each character in a sliding window. We just need to track the last seen of a character. This will help us figure out whether a character exists in the current sliding window.\n\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n last_seen = {}\n l=0\n max_length=0\n for r in range(len(s)):\n if s[r] in last_seen:\n l=max(last_seen[s[r]], l)\n \n last_seen[s[r]]=r+1\n max_length=max(max_length, r-l+1)\n return max_length\n \n```\n\n**Time - O(n)** - Iterates both `l` and `r` once through the input `s`.\n**Space - O(n)**\n\n\n---\n\n***Please upvote if you find it useful*** | 25 | 1 | ['Python', 'Python3'] | 3 |
longest-substring-without-repeating-characters | [Python] One pass - Clean & Concise | python-one-pass-clean-concise-by-hiepit-prsa | Python\npython\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n ans = 0\n l = 0\n lastIndex = [-1] * 128\n | hiepit | NORMAL | 2019-04-03T08:31:06.097723+00:00 | 2021-09-06T08:27:22.165258+00:00 | 558 | false | **Python**\n```python\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n ans = 0\n l = 0\n lastIndex = [-1] * 128\n for r, c in enumerate(s):\n l = max(l, lastIndex[ord(c)] + 1)\n lastIndex[ord(c)] = r\n ans = max(ans, r - l + 1)\n return ans\n```\n**Complexity**\n- Time: `O(N)`, where `N <= 5 * 10^4` is length of string `s`.\n- Space: `O(128)` | 25 | 0 | [] | 1 |
longest-substring-without-repeating-characters | C Super-Simple Clean Solution 0ms | c-super-simple-clean-solution-0ms-by-yeh-n2po | \nint lengthOfLongestSubstring(char * s){\n /*letter_map is to keep track if we saw this character in this substring*/\n int letter_map[128] = {0}, res = | yehudisk | NORMAL | 2021-01-07T11:53:24.643225+00:00 | 2021-01-07T11:53:49.291239+00:00 | 2,726 | false | ```\nint lengthOfLongestSubstring(char * s){\n /*letter_map is to keep track if we saw this character in this substring*/\n int letter_map[128] = {0}, res = 0;\n char* start = s, *end = s;\n \n while (*end) {\n /* If we reached a letter we saw already - check max length and start a new substring*/\n if (letter_map[*end]) {\n res = (end - start > res) ? end - start : res;\n while (*start != *end) {\n letter_map[*start] = 0;\n start++;\n }\n start++;\n end++;\n }\n else {\n letter_map[*end] = 1;\n end++;\n } \n }\n return end-start > res ? end-start : res;\n}\n```\n**Like it? please upvote...** | 24 | 0 | ['C'] | 2 |
longest-substring-without-repeating-characters | Python | Easy Solution✅ | python-easy-solution-by-gmanayath-5qq5 | \n# Code\u2705\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n output = 0\n count = {}\n pos = -1\n for | gmanayath | NORMAL | 2022-11-10T11:55:39.057941+00:00 | 2022-12-22T16:42:37.829264+00:00 | 10,839 | false | \n# Code\u2705\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n output = 0\n count = {}\n pos = -1\n for index, letter in enumerate(s):\n if letter in count and count[letter] > pos:\n pos = count[letter]\n count[letter] = index \n output = max(output,index-pos)\n return output\n``` | 23 | 0 | ['Hash Table', 'Sliding Window', 'Python', 'Python3'] | 4 |
longest-substring-without-repeating-characters | My O(n) solution , runtime: 5ms | my-on-solution-runtime-5ms-by-loggerhead-6kcj | int lengthOfLongestSubstring(char *s) {\n int m[129] = {0};\n int i, j;\n int cnt = 0, pre = 0;\n int max = 0;\n int c;\n | loggerhead | NORMAL | 2015-02-11T11:36:09+00:00 | 2018-10-11T23:34:01.357458+00:00 | 8,074 | false | int lengthOfLongestSubstring(char *s) {\n int m[129] = {0};\n int i, j;\n int cnt = 0, pre = 0;\n int max = 0;\n int c;\n \n for (i = 0; c = s[i]; i++) {\n if (pre < m[c]) {\n if (max < cnt)\n max = cnt;\n \n cnt = i-m[c];\n pre = m[c];\n }\n \n cnt++;\n m[c] = i+1;\n }\n return max > cnt ? max : cnt;\n } | 23 | 1 | [] | 8 |
longest-substring-without-repeating-characters | Short'n'Sweet Python solution, beats 99% | shortnsweet-python-solution-beats-99-by-g6swo | class Solution(object):\n def lengthOfLongestSubstring(self, s):\n last, res, st = {}, 0, 0\n for i, v in enumerate(string):\n | agave | NORMAL | 2016-05-30T12:31:58+00:00 | 2018-10-12T21:47:07.241576+00:00 | 7,100 | false | class Solution(object):\n def lengthOfLongestSubstring(self, s):\n last, res, st = {}, 0, 0\n for i, v in enumerate(string):\n if v not in last or last[v] < st:\n res = max(res, i - st + 1)\n else:\n st = last[v] + 1\n last[v] = i\n return res | 23 | 0 | [] | 4 |
longest-substring-without-repeating-characters | Java || HashSet || Sliding Window | java-hashset-sliding-window-by-emirhanoz-ims9 | Intuition\nUpon encountering this problem, my initial instinct is to utilize the sliding window technique to identify the length of the longest substring withou | emirhanozcan | NORMAL | 2023-08-30T05:44:29.910453+00:00 | 2023-08-30T05:44:29.910482+00:00 | 985 | false | # Intuition\nUpon encountering this problem, my initial instinct is to utilize the sliding window technique to identify the length of the longest substring without repeating characters.\n\n# Approach\nMy approach to tackling this problem involves implementing the sliding window technique to ascertain the length of the longest substring that does not contain any repeated characters. To do so, I maintain a HashSet called `uniqueChars` to keep track of the characters present in the current window. Additionally, two pointers named `start` and `end` denote the beginning and end of the present substring segment. Furthermore, a variable named `maxSubstringLength` is utilized to track the length of the longest valid substring.\n\nThe algorithm operates as follows:\n1. While the `end` pointer remains within the bounds of the string:\n - If the character at the `end` position is not present in the `uniqueChars` set:\n - Add the character to the set.\n - Update the `maxSubstringLength` by comparing it to the length of the current substring (`end - start + 1`).\n - Increment the `end` pointer.\n - If the character at the `end` position is already in the `uniqueChars` set:\n - Remove the character at the `start` position from the set.\n - Increment the `start` pointer to slide the window to the right.\n\nUpon completing the iteration, the algorithm returns the calculated `maxSubstringLength`.\n\nThis sliding window approach efficiently identifies the length of the longest substring without repeating characters, accomplishing the task in a single traversal of the string.\n\n# Complexity\n- Time complexity: O(n)\n The algorithm traverses the provided string once, performing constant-time operations at each step.\n\n- Space complexity: O(k)\n The algorithm employs a HashSet named `uniqueChars` to store distinct characters in the current window. In the worst case, the HashSet may contain all characters from the input string, leading to a space complexity of O(k), where k is the size of the character set.\n\n# Code\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\nHashSet<Character> uniqueChars = new HashSet<>();\n int start = 0;\n int end = 0;\n int maxSubstringLength = 0;\n\n while (end < s.length()) {\n if (!uniqueChars.contains(s.charAt(end))) {\n uniqueChars.add(s.charAt(end));\n maxSubstringLength = Math.max(maxSubstringLength, end - start + 1);\n end++;\n } else {\n uniqueChars.remove(s.charAt(start));\n start++;\n }\n }\n\n return maxSubstringLength;\n }\n}\n```\n | 22 | 0 | ['Java'] | 2 |
longest-substring-without-repeating-characters | Python solution || simple and fast || 44ms (99%) || 12.9MB (100%) | python-solution-simple-and-fast-44ms-99-hnz89 | If you find it nice, please upvote!\n\n\ndef lengthOfLongestSubstring(s: str):\n max_len = 0\n sub = \'\'\n \n for l in s:\n if l in sub:\n | mbronis | NORMAL | 2019-12-28T00:11:06.402618+00:00 | 2019-12-28T00:11:06.402655+00:00 | 1,741 | false | If you find it nice, please upvote!\n\n```\ndef lengthOfLongestSubstring(s: str):\n max_len = 0\n sub = \'\'\n \n for l in s:\n if l in sub:\n sub = sub[sub.find(l)+1:] \n sub += l\n if len(sub) > max_len:\n max_len = len(sub)\n \n return max_len\n``` | 22 | 0 | ['Python'] | 2 |
longest-substring-without-repeating-characters | Python solution | python-solution-by-zitaowang-2msp | We initialize the result res = 0, and two pointers j = 0, and i = 0. We initialize a dictionary dic which maps every element in s[:i+1] to its index of rightmos | zitaowang | NORMAL | 2019-02-13T23:25:29.033866+00:00 | 2019-02-13T23:25:29.033927+00:00 | 5,121 | false | We initialize the result `res = 0`, and two pointers `j = 0`, and `i = 0`. We initialize a dictionary `dic` which maps every element in `s[:i+1]` to its index of rightmost occurrence in `s[:i+1]`. Then we iterate `i` over `range(len(s))`, if `s[i]` is not in `dic`, we add it to `dic`: `dic[s[i]] = i`; Otherwise, we move `j` to `max(j, dic[s[i]]+1)`, so that within the window `[j:i+1]`, the element `s[i]` only occur once. Then we update the result `res = max(res, i-j+1)`. Finally, we return `res`.\n\nTime complexity: `O(n)`, space complexity: `O(n)`.\n\n```\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n """\n :type s: str\n :rtype: int\n """\n dic = {}\n res = 0\n j = 0\n for i in range(len(s)):\n if s[i] not in dic:\n dic[s[i]] = i\n else:\n j = max(j, dic[s[i]]+1)\n dic[s[i]] = i\n res = max(res, i-j+1)\n return res\n``` | 22 | 0 | [] | 5 |
longest-substring-without-repeating-characters | ✅ [Rust] 0 ms, no HashMap, simply use position differences (with detailed comments) | rust-0-ms-no-hashmap-simply-use-position-u33q | This solution employs simple calculation of position differences for repeated characters. It demonstrated 0 ms runtime (100.00%) and used 2.1 MB memory (97.34%) | stanislav-iablokov | NORMAL | 2022-09-16T14:12:16.585992+00:00 | 2022-10-23T12:57:31.718011+00:00 | 1,649 | false | This [solution](https://leetcode.com/submissions/detail/801296870/) employs simple calculation of position differences for repeated characters. It demonstrated **0 ms runtime (100.00%)** and used **2.1 MB memory (97.34%)**. Detailed comments are provided.\n\n**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n```\nimpl Solution \n{\n pub fn length_of_longest_substring(s: String) -> i32 \n {\n let mut max_len: usize = 0;\n \n // [1] longest substring is the one with the largest\n // difference of positions of repeated characters;\n // thus, we should create a storage for such positions\n let mut pos: [usize;128] = [0;128];\n \n // [2] while iterating through the string (i.e., moving\n // the end of the sliding window), we should also\n // update the start of the window\n let mut start: usize = 0;\n \n for (end, ch) in s.chars().enumerate()\n {\n // [3] get the position for the start of sliding window\n // with no other occurences of \'ch\' in it\n start = start.max(pos[ch as usize]);\n \n // [4] update maximum length \n max_len = max_len.max(end-start+1);\n \n // [5] set the position to be used in [3] on next iterations\n pos[ch as usize] = end + 1;\n }\n \n return max_len as i32;\n }\n}\n``` | 21 | 0 | ['Rust'] | 1 |
longest-substring-without-repeating-characters | Simplest way (with explanation) [97% faster] | simplest-way-with-explanation-97-faster-98xnj | \nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n \n string = s\n \n max_length = 0 # we set max_leng | tony_stark_47 | NORMAL | 2021-10-17T16:56:06.255314+00:00 | 2021-10-17T17:17:07.790113+00:00 | 1,805 | false | ```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n \n string = s\n \n max_length = 0 # we set max_length to 0 because string may be empty.\n seen_character = \'\' # a empty string to store the character that we have already seen.\n \n for letter in string: # we are checking every letter/character in string...\n if letter not in seen_character:\n seen_character += letter # if letter not in there then we add to it.\n \n else:\n ## now if the letter is already in seen_character then we get the index of that letter by using seen_character.index() and then we slice the string from that index+1 to last, so that the the first seen letter will be removed.\n # for example - \'abcabbd\' # here after \'abc\' , again "a" was there so we get the index of first "a" and slice the string then be get string = "bc" .\n seen_character = seen_character[seen_character.index(letter) + 1:] + letter\n # and then we add the letter "a" to the last. so the string will become "bca"\n \n max_length = max(max_length, len(seen_character)) # here we use a function max() that everytime return the maximum value between two number. it sets max_length each time the loop runs.\n return max_length # finally return the maximum length.\n \n #by - Tony Stark\n``` | 21 | 0 | ['Python', 'Python3'] | 5 |
longest-substring-without-repeating-characters | Golang solution | golang-solution-by-linfongi-bi7s | func lengthOfLongestSubstring(str string) int {\n \tm, max, left := make(map[rune]int), 0, 0\n \tfor idx, c := range str {\n \t\tif _, okay := m[c]; ok | linfongi | NORMAL | 2016-03-28T01:40:16+00:00 | 2016-03-28T01:40:16+00:00 | 3,277 | false | func lengthOfLongestSubstring(str string) int {\n \tm, max, left := make(map[rune]int), 0, 0\n \tfor idx, c := range str {\n \t\tif _, okay := m[c]; okay == true && m[c] >= left {\n \t\t\tif idx-left > max {\n \t\t\t\tmax = idx - left\n \t\t\t}\n \t\t\tleft = m[c] + 1\n \t\t}\n \t\tm[c] = idx\n \t}\n \tif len(str)-left > max {\n \t\tmax = len(str) - left\n \t}\n \treturn max\n } | 20 | 9 | ['Go'] | 1 |
longest-substring-without-repeating-characters | Golang: explanation (100% speed & memory) | golang-explanation-100-speed-memory-by-a-40rw | dict is our dictionary of previously encountered characters\n2. Increment i and use character s[i] as index in dict to set value to true: dict[s[i]] = true\n3. | andnik | NORMAL | 2019-12-01T19:43:54.994509+00:00 | 2019-12-01T19:43:54.994566+00:00 | 3,821 | false | 1. `dict` is our dictionary of previously encountered characters\n2. Increment `i` and use character `s[i]` as index in `dict` to set value to `true`: `dict[s[i]] = true`\n3. With each step we increment `length` and compare it to `max` value and set `max = length` if length now bigger.\n4. When we face character we already marked in `dict` (`dict[s[i]] == true`), we increment secord iterator j, unmark characters in dictionary `dict[s[j]] = false` and decrement `length` until `dict[s[i]] == false`.\n5. We repeat steps `(2)-(4)` while `i < len(s)`.\n\n```go\nfunc lengthOfLongestSubstring(s string) int {\n dict := [128]bool{}\n length, max := 0, 0\n for i, j := 0, 0; i < len(s); i++ {\n index := s[i]\n if dict[index] {\n for ;dict[index]; j++ {\n length--\n dict[s[j]] = false\n }\n }\n \n dict[index] = true\n length++\n if length > max {\n max = length\n }\n }\n return max\n}\n``` | 19 | 1 | ['Go'] | 1 |
longest-substring-without-repeating-characters | Simple java solution | simple-java-solution-by-band-bfp6 | public class Solution {\n public int lengthOfLongestSubstring(String s) {\n Map<Character,Integer> indices = new HashMap<Character,Integer>(); | band | NORMAL | 2015-10-23T02:57:23+00:00 | 2018-09-10T18:31:08.535095+00:00 | 6,123 | false | public class Solution {\n public int lengthOfLongestSubstring(String s) {\n Map<Character,Integer> indices = new HashMap<Character,Integer>();\n int length = 0;\n int start = -1;\n int end = 0;\n for(end=0; end < s.length(); end++){\n char c = s.charAt(end);\n if(indices.containsKey(c)){\n int newstart = indices.get(c);\n start = Math.max(start,newstart);\n }\n length = Math.max(length,end-start);\n indices.put(c,end);\n }\n return length;\n }\n } | 19 | 0 | ['Java'] | 4 |
longest-substring-without-repeating-characters | python | python-by-vote4-tbek | \ndef lengthOfLongestSubstring(self, s: str) -> int:\n maxLength = 0\n dict = {}\n\n i,j = 0,0\n n = len(s)\n\n while(j < n): | vote4 | NORMAL | 2022-12-17T06:47:16.456319+00:00 | 2022-12-17T06:47:16.456351+00:00 | 3,462 | false | ```\ndef lengthOfLongestSubstring(self, s: str) -> int:\n maxLength = 0\n dict = {}\n\n i,j = 0,0\n n = len(s)\n\n while(j < n):\n c = s[j] \n \n dict[c] = 1 if not c in dict else dict[c] + 1\n \n \n if dict[c] > 1:\n while(dict[c] > 1):\n dict[s[i]] -= 1\n i += 1\n \n maxLength = max(maxLength, j - i + 1)\n j += 1\n\n return maxLength\n``` | 18 | 0 | [] | 1 |
longest-substring-without-repeating-characters | [Fastest Solution Explained][0ms][100%] O(n)time complexity O(n)space complexity | fastest-solution-explained0ms100-ontime-uwfs9 | \n(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, please upvote this post.)\nTake care brother, | darian-catalin-cucer | NORMAL | 2022-08-05T14:56:08.986727+00:00 | 2022-08-05T14:56:08.986775+00:00 | 5,349 | false | \n(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful, ***please upvote*** this post.)\n***Take care brother, peace, love!***\n\n```\n```\n\nThe best result for the code below is ***0ms / 3.27MB*** (beats 99.04% / 90.42%).\n* *** Java ***\n\n```\n\npublic int lengthOfLongestSubstring(String s) {\n int i = 0, j = 0, max = 0;\n Set<Character> set = new HashSet<>();\n \n while (j < s.length()) {\n if (!set.contains(s.charAt(j))) {\n set.add(s.charAt(j++));\n max = Math.max(max, set.size());\n } else {\n set.remove(s.charAt(i++));\n }\n }\n \n return max;\n}\n\n```\nThe idea is use a hash set to track the longest substring without repeating characters so far, use a fast pointer j to see if character j is in the hash set or not, if not, great, add it to the hash set, move j forward and update the max length, otherwise, delete from the head by using a slow pointer i until we can put character j to the hash set.\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 10MB*** (beats 100.00% / 95.49%).\n* *** Python ***\n\n```\nSliding window\nWe use a dictionary to store the character as the key, the last appear index has been seen so far as value.\nseen[charactor] = index\n\nmove the pointer when you met a repeated character in your window.\n```\n\n```\n\nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n ^ ^\n | |\n\t\tleft right\n\t\tseen = {a : 0, c : 1, b : 2, d: 3} \n\t\t# case 1: seen[b] = 2, current window is s[0:4] , \n\t\t# b is inside current window, seen[b] = 2 > left = 0. Move left pointer to seen[b] + 1 = 3\n\t\tseen = {a : 0, c : 1, b : 4, d: 3} \nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n\t\t\t\t\t\t ^ ^\n\t\t\t\t\t | |\n\t\t\t\t left right\t\t\nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n\t\t\t\t\t ^ ^\n\t\t\t\t\t | |\n\t\t\t\t left right\t\t\n\t\t# case 2: seen[a] = 0,which means a not in current window s[3:5] , since seen[a] = 0 < left = 3 \n\t\t# we can keep moving right pointer.\n\n```\n\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n seen = {}\n l = 0\n output = 0\n for r in range(len(s)):\n """\n If s[r] not in seen, we can keep increasing the window size by moving right pointer\n """\n if s[r] not in seen:\n output = max(output,r-l+1)\n """\n There are two cases if s[r] in seen:\n case1: s[r] is inside the current window, we need to change the window by moving left pointer to seen[s[r]] + 1.\n case2: s[r] is not inside the current window, we can keep increase the window\n """\n else:\n if seen[s[r]] < l:\n output = max(output,r-l+1)\n else:\n l = seen[s[r]] + 1\n seen[s[r]] = r\n return output\n```\n* Time complexity :O(n).\nn is the length of the input string.\nIt will iterate n times to get the result.\n\n* Space complexity: O(m)\nm is the number of unique characters of the input.\nWe need a dictionary to store unique characters.\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 23.7MB*** (beats 59.24% / 60.42%).\n* *** C++ ***\n\n\n```\n\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n \n //SLIDING WINDOW - TIME COMPLEXITY O(2n)\n // SPACE COMPLEXITY O(m) //size of array\n \n int store[256]={0}; //array to store the occurences of all the characters\n int l=0; //left pointer\n int r=0; //right pointer\n int ans=0; //initializing the required length as 0\n \n while(r<s.length()) //iterate over the string till the right pointer reaches the end of the string \n {\n store[s[r]]++; //increment the count of the character present in the right pointer \n \n while(store[s[r]]>1) //if the occurence become more than 1 means the char is repeated\n { \n store[s[l]]--; //reduce the occurence of temp as it might be present ahead also in the string\n l++; //contraction of the present window till the occurence of the \'t\' char becomes 1\n }\n \n ans = max(ans,r-l+1); //As the index starts from 0 , ans will be (right pointer-left pointer + 1)\n r++; // now will increment the right pointer \n }\n return ans;\n }\n};\n\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 78MB*** (beats 100.00% / 100.00%).\n* *** JavaScript ***\n\n\n```\n\nfunction lengthOfLongestSubstring(s) {\n const map = {};\n var left = 0;\n \n return s.split(\'\').reduce((max, v, i) => {\n left = map[v] >= left ? map[v] + 1 : left;\n map[v] = i;\n return Math.max(max, i - left + 1);\n }, 0);\n}\n\n```\n\n```\nTime Complexity = O(N)\nSpace Complexity = O(N)\n```\n\n```\nvar lengthOfLongestSubstring = function(s) {\n // keeps track of the most recent index of each letter.\n const seen = new Map();\n // keeps track of the starting index of the current substring.\n let start = 0;\n // keeps track of the maximum substring length.\n let maxLen = 0;\n \n for(let i = 0; i < s.length; i++) {\n // if the current char was seen, move the start to (1 + the last index of this char)\n // max prevents moving backward, \'start\' can only move forward\n if(seen.has(s[i])) start = Math.max(seen.get(s[i]) + 1, start)\n seen.set(s[i], i);\n // maximum of the current substring length and maxLen\n maxLen = Math.max(i - start + 1, maxLen);\n } \n \n return maxLen; \n};\n```\n\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 33.33MB*** (beats 99.00% / 60.12%).\n* *** Kotlin ***\n\n\n```\n\nfun lengthOfLongestSubstring(s: String): Int {\n var maxLength = 0\n val queue = LinkedList<Char>()\n for (i in s.indices) {\n if (queue.isNotEmpty()) {\n when {\n queue.first == s[i] -> queue.poll()\n queue.last == s[i] -> queue.clear()\n queue.contains(s[i]) -> {\n while (queue.isNotEmpty()) {\n if (queue.poll() == s[i]) break\n }\n }\n }\n }\n\n maxLength = max(maxLength, queue.size+1)\n queue.offer(s[i])\n }\n\n return maxLength\n}\n```\n\n```\nimport kotlin.math.*\n\nclass Solution {\n private val hashMap = mutableMapOf<Char, Int>()\n private var longest = Pair<Int, Int>(0, 1)\n \n fun lengthOfLongestSubstring(s: String): Int {\n if (s.length == 0) {\n return 0\n }\n \n var start = 0\n \n for (i in 0 until s.length) {\n val letter = s[i]\n if (hashMap.containsKey(letter)) {\n // start = max(start, hashMap[letter]!! + 1)\n // why use max() ? "abba": if we take not max, then when visiting second \'a\' ->\n // we\'ll take b, but don\'t need it as it\'ll include duplicate\n start = hashMap[letter]!! + 1\n // +1 as we don\'t need current that has duplication, but next letter after it\n }\n val (firstIdx: Int, secondIdx: Int) = longest\n \n if (secondIdx - firstIdx < i - start + 1) {\n longest = Pair<Int, Int>(start, i+1)\n // +1 is to include current last letter as otherwise it will be excluding\n }\n hashMap.put(letter, i)\n }\n val (firstIdx: Int, secondIdx: Int) = longest\n \n return secondIdx - firstIdx\n }\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 13.17MB*** (beats 79.34% / 99.92%).\n* *** Swift ***\n\n\n```\n\nclass Solution {\n func lengthOfLongestSubstring(_ s: String) -> Int {\n guard !s.isEmpty else { return 0 }\n var len = 0, chars = [Character]()\n for c in s {\n if let idx = chars.firstIndex(of: c) {\n chars.removeSubrange(0...idx)\n }\n chars.append(c)\n len = max(len, chars.count)\n }\n return len\n }\n}\n\n```\n* O(N)\n```\nclass Solution {\n func lengthOfLongestSubstring(_ s: String) -> Int {\n var longest = 0, startIndex = 0\n var charMap: [Character: Int] = [:]\n\n for (index, char) in s.enumerated() {\n if let foundIndex = charMap[char] {\n startIndex = max(foundIndex+1, startIndex)\n }\n longest = max(longest, index - startIndex + 1)\n charMap[char] = index\n }\n return longest\n }\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 62.07MB*** (beats 99.99% / 99.99%).\n* *** PHP ***\n\n\n```\n\nclass Solution {\n\n/**\n * @param String $s\n * @return Integer\n */\nfunction lengthOfLongestSubstring($s) {\n\t$start = 0; //current starting position of search\n $length = 0; //current max length of substring\n for($i = 0; $i < strlen($s); $i++){\n $char = $s[$i];\n if(isset($arr[$char]) && $arr[$char] >= $start){\n $start = $arr[$char] + 1;\n } elseif($i - $start === $length) {\n $length++;\n }\n $arr[$char] = $i;\n }\n return $length;\n}\n}\n\n```\n\n```\nclass Solution {\n\n /**\n * @param String $s\n * @return Integer\n */\n function lengthOfLongestSubstring($s) \n {\n if (strlen($s) === 0) return 0;\n if (strlen($s) === 1) return 1;\n \n $chars = str_split($s);\n \n $i = $j = $max = 0;\n $seen = [];\n \n while ($i < count($chars))\n {\n $c = $chars[$i];\n \n while (array_key_exists($c, $seen))\n {\n unset($seen[$chars[$j]]);\n \t\t$j++;\n }\n \n $seen[$chars[$i]] = true;\n \n $max = max($i - $j + 1, $max);\n $i++;\n }\n return $max;\n }\n}\n```\n\n```\n```\n\n```\n```\n\nThe best result for the code below is ***0ms / 1.17MB*** (beats 99.64% / 99.92%).\n* *** C ***\n\n\n```\n\nint lengthOfLongestSubstring(char * s){\n /*letter_map is to keep track if we saw this character in this substring*/\n int letter_map[128] = {0}, res = 0;\n char* start = s, *end = s;\n \n while (*end) {\n /* If we reached a letter we saw already - check max length and start a new substring*/\n if (letter_map[*end]) {\n res = (end - start > res) ? end - start : res;\n while (*start != *end) {\n letter_map[*start] = 0;\n start++;\n }\n start++;\n end++;\n }\n else {\n letter_map[*end] = 1;\n end++;\n } \n }\n return end-start > res ? end-start : res;\n}\n\n```\n\n```\n```\n\n```\n```\n\n***"Open your eyes. Expect us." - \uD835\uDCD0\uD835\uDCF7\uD835\uDCF8\uD835\uDCF7\uD835\uDD02\uD835\uDCF6\uD835\uDCF8\uD835\uDCFE\uD835\uDCFC***\n | 18 | 1 | ['Swift', 'C', 'PHP', 'Python', 'C++', 'Java', 'Python3', 'Kotlin', 'JavaScript'] | 2 |
longest-substring-without-repeating-characters | 8 Lines C++ Solution | 8-lines-c-solution-by-xiaoli727-2g8t | Description\nLongest Substring Without Repeating Characters: Given a string s, find the length of the longest substring without repeating characters.\nExample:\ | xiaoli727 | NORMAL | 2021-08-04T16:22:12.554130+00:00 | 2021-08-04T16:23:03.805321+00:00 | 2,247 | false | **Description**\n[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/): Given a string `s`, find the length of the **longest substring** without repeating characters.\nExample:\n```\nInput: s = "pwwkew"\nOutput: 3\nExplanation: The answer is "wke", with the length of 3.\nNotice that the answer must be a substring, "pwke" is a subsequence and not a substring.\n```\n\n**Solution**\nThe basic idea is to use a dictionary (called `cache`) to keep track **where the character last appeared**.\nThis is easy to see that **length = end - start**. For each character, we take its index as `end`. For `start`, we hope to use the index, all characters after it are not repeated. So, the `start` will be the maximum of `start` and `the index of the character last appeared`. Finally, we return the max length.\nThe idea is as follows:\n\n\n**Code**\n```cpp\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n vector<int> cache(256, -1);\n int start = -1, maxRes = 0;\n for(int i = 0; i < s.length(); i++) {\n start = max(start, cache[s[i]]);\n cache[s[i]] = i;\n maxRes = max(maxRes, i - start);\n }\n return maxRes;\n }\n};\n```\n\n**Complexity**\nTime complexity: O(n)\nSpace complexity: only use 256 array space, so the space cost is O(1) | 18 | 0 | ['C'] | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.