educative.io

"No-repeat Substring" alternate solution?

Hey, what do you think about this solution?

const non_repeat_substring = function(str) {
    const chars = {};
    let windowStart = 0;
    let maxLength = 0;

    for (let windowEnd = 0; windowEnd < str.length; windowEnd++) {
        const char = str[windowEnd];

        // check if char is repeating (using previous windowEnd position)
        if (char in chars && chars[char] === windowEnd - 1) {
            windowStart = windowEnd;
        }

        // add or update char index
        chars[char] = windowEnd;

        const length = windowEnd - windowStart;

        // store max length of non-repeating characters
        if (maxLength < length) {
            maxLength = length;
        }
    }

    return maxLength;
}

Thanks

Hi @Stanislav_Dzhus,

You’re almost there. There’s only one change you need to make to the following line:
const length = windowEnd - windowStart;

It should be changed to:
const length = windowEnd - windowStart + 1;
This formula allows you to calculate the actual length of the sliding window.

Thank you for reaching out to us.