1
   class Solution:
        def lengthOfLongestSubstring(self, s: str,unique=[]) -> int:
            i=0
            m=0
            j=0
            l=0
            while(i<len(s)):

                if(s[i] not in unique):
                    unique.append(s[i])
                    m=m+1
                    l = max(l,m)
                    i=i+1

                else:
                    unique=[]
                    j=j+1
                    i=j
                    m=0

            print(l)
            return

Input = "c" output = "1" during runcode but fails(0) on submit. It also works during the playground debug for the same testcase. unable to figure it out.

1 Answers1

1

This is a problem that appears because of the way Python handles mutable default arguments in function definitions, in this case unique=[]. The suggested fix for this is:

def lengthOfLongestSubstring(self, s: str,unique=None) -> int:
    if unique is None:
        unique = []

This is rather strange behavior, but since everything is an object in Python, what it appears to mean is that such arguments result in the function remembering its state after each call (behaving rather like a function with a static variable inside it in other languages). I ran the code with the changed statement and it seems to solve the problem. Here is a more complete discussion of the issue:

https://docs.python-guide.org/writing/gotchas/

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11