Challenge: Longest Substring Without Repeating Characters
Welcome to Day 4 of our 100 Days DSA Challenge! 🚀 Today’s challenge dives into the world of strings. We’ll be unraveling the mystery of finding the length of the longest substring without repeating characters.
The Challenge:
Given a string s
, our task is to find the length of the longest substring without repeating characters.
Example:
const s = "abcabcbb";
// Output: 3 (because the longest substring without repeating characters is "abc")
Challenge Yourself:
Before exploring the solution, challenge yourself to think about how you would approach this problem. Can you come up with an alternative solution?
The Solution:
const longestSubString = (s) => {
let start = 0;
let end = 0;
let maxLength = 0;
const char = new Set();
while (end < s.length) {
if (!char.has(s[end])) {
char.add(s[end]);
maxLength = Math.max(maxLength, end - start + 1);
end++;
} else {
char.delete(s[start]);
start++;
}
}
return maxLength;
}
Solution Logic:
- Initialize Pointers and Variables:
- We start with two pointers,
start
andend
, both initially set to 0. maxLength
is the variable to keep track of the length of the longest substring.char
is a Set used to store unique characters in the current substring.
- We start with two pointers,
- Iterate Through the String:
- We use a
while
loop to iterate through the string (s
) from the beginning to the end.
- We use a
- Check for Repeating Characters:
- If the character at the
end
pointer is not in thechar
set, we add it to the set and update themaxLength
accordingly.
- We then move the
end
pointer to the next character.
- If the character at the
- Adjust Pointers for Repeating Characters:
- If a repeating character is found, we remove the character at the
start
pointer from the set and move thestart
pointer forward.
- If a repeating character is found, we remove the character at the
- Repeat Until End of String:
- We repeat these steps until we reach the end of the string.
- Return the Maximum Length:
- The
maxLength
variable now holds the length of the longest substring without repeating characters.
- The
Conclusion:
Congratulations on completing Day 4 of our DSA Challenge! Strings are a fundamental part of coding, and mastering them opens up a world of possibilities. Stay tuned for tomorrow’s challenge, and keep the coding spirit alive!
Happy coding! 🌟💻
#100DaysDSAChallenge #DataStructures #Algorithms #ProgrammingCommunity #CodeNewbie