longest substring

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:

  1. Initialize Pointers and Variables:
    • We start with two pointers, start and end, 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.
  2. Iterate Through the String:
    • We use a while loop to iterate through the string (s) from the beginning to the end.
  3. Check for Repeating Characters:
    • If the character at the end pointer is not in the char set, we add it to the set and update the maxLength accordingly.
    • We then move the end pointer to the next character.
  4. Adjust Pointers for Repeating Characters:
    • If a repeating character is found, we remove the character at the start pointer from the set and move the start pointer forward.
  5. Repeat Until End of String:
    • We repeat these steps until we reach the end of the string.
  6. Return the Maximum Length:
    • The maxLength variable now holds the length of the longest substring without repeating characters.

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

Leave a Reply

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