1

The current problem I'm having is that when the code runs it shows me "None" in the terminal.

/usr/local/bin/python3.12/Users/jaredmccarthy/Desktop/2025/ejercicios_leetcode.py 
None

Process finished with exit code 0

I want find the length of the longest substring without duplicate characters using the siding window algorithm.

First I had tried with a pointer to the start of the string and then with a max_length but with a while, and what happens is that I could not go through all the elements using only the while and that is why I tried to change to the "for" and this time using two pointers, one that stays from the start and the other to go through all the elements and when they reach the window if they are repeated it takes them out and if not it puts them inside the window, do I make myself understood?

Here is my code:

def longest_substring(s):
    ventana = set(s)
    max_longitud = 0
    inicio = 0

    for fin in range(len(s)):
        if fin != len(ventana):
            ventana.add(fin)
            max_longitud += 1

        if fin == len(s):
            ventana.remove(inicio)
            inicio += 1


if __name__ == "__main__":
    s = "abcabcbb"
    print(longest_substring(s))
1
  • 1
    Your function does not explicitly return anything. Therefore it will implicitly return None. That's a fundamental feature of Python functions Commented Sep 12 at 6:31

1 Answer 1

4

You can try this way:

def longest_substring(s):
    ventana = set()
    max_longitud = 0
    inicio = 0

    for fin in range(len(s)):
        while s[fin] in ventana:
            ventana.remove(s[inicio])
            inicio += 1
        ventana.add(s[fin])
        max_longitud = max(max_longitud, fin - inicio + 1)

    return max_longitud


if __name__ == "__main__":
    s = "abcabcbb"
    print(longest_substring(s))  
    # output: 3
  • First of all, your function doesn't return anything, so Python returns None by default. That’s why you see None in the terminal.

  • In your code, you set ventana = set(s) , but the idea of the sliding window algorithm is to build the set dynamically as you iterate.

  • other issue is (ventana.add(fin)) that you’re adding the index (0, 1,2, ....) instead of the actual character (s[fin]) into the set.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.