LeetCode solutions

1045. Check If Word Is Valid After Substitutions

My accepted Python solution to LeetCode problem 1045, Check If Word Is Valid After Substitutions, running in 32ms.

  • Difficulty: Medium
  • Python
  • Runtime 32ms
  • Memory 17.9MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 32ms, memory 17.9MB, accepted 2026-01-02.

python
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for c in s:
            stack.append(c)
            if len(stack) >= 3 and stack[-3:] == ['a', 'b', 'c']:
                stack.pop()
                stack.pop()
                stack.pop()
        return len(stack) == 0

Source