I was doing the question Validate Stack Sequences. My first attempt was this
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int], stack = []) -> bool:
print(pushed, popped, stack)
if popped == []:
return True
else:
if popped[0] not in stack:
stack.append(pushed.pop(0))
return self.validateStackSequences(pushed, popped, stack)
elif popped[0] == stack[-1]:
stack.pop()
popped.pop(0)
return self.validateStackSequences(pushed, popped, stack)
else:
return FalseWhen it ran against test case pushed = [0,1] popped = [1,0] I printed out the results and my stack = [1,2]
However, when I implemented a helper function
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
return self.helper(pushed, popped, stack = [])
def helper(self, pushed, popped, stack):
if popped == []:
return True
else:
if popped[0] not in stack:
stack.append(pushed.pop(0))
return self.helper(pushed, popped, stack)
elif popped[0] == stack[-1]:
stack.pop()
popped.pop(0)
return self.helper(pushed, popped, stack)
else:
return FalseIt passed all test cases.
Is this something due to how leetcode runs the test cases?