Check If Word Is Valid After Substitutions Problem
Description
LeetCode Problem 1003.
Given a string s, determine if it is valid.
A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times:
- Insert string
"abc"into any position int. More formally,tbecomest_left + "abc" + t_right, wheret == t_left + t_right. Note thatt_leftandt_rightmay be empty.
Return true if s is a valid string, otherwise, return false.
Example 1:
Input: s = "aabcbc"
Output: true
Explanation:
"" -> "abc" -> "aabcbc"
Thus, "aabcbc" is valid.
Example 2:
Input: s = "abcabcababcc"
Output: true
Explanation:
"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
Thus, "abcabcababcc" is valid.
Example 3:
Input: s = "abccba"
Output: false
Explanation: It is impossible to get "abccba" using the operation.
Constraints:
1 <= s.length <= 2 * 10^4sconsists of letters'a','b', and'c'
Solution
Approach: Stack
Run the process backwards: s is valid if we can keep deleting a substring "abc" until the string is empty. Deleting with repeated string searches would be quadratic, but a stack does it in one pass.
Push the characters of s one by one. Whenever the top three characters of the stack are a, b, c (in that order), pop them: they are one inserted "abc", and removing it may join the characters around it into a new "abc", which the stack finds as the scan goes on. At the end, s is valid exactly when the stack is empty.
Why is it enough to look only at the top of the stack? An inserted "abc" that contains no later insertion is a contiguous block, and its c is the moment it is completed; anything inserted inside it was completed (and popped) before its c arrives. So the innermost blocks are always found first. For example 2, "abcabcababcc": the first two "abc"s are popped as soon as they appear, then a b a b c leaves a b after popping, and the final c completes that "abc" too.
A quick extra check: every insertion adds three characters, so if the length of s is not a multiple of 3, it cannot be valid. The stack handles that case anyway; the check is only a shortcut. Note that the order inside a block matters, so "bac" and "cba" are invalid even though they have the right letters.
Complexity: O(n) time and O(n) extra space for the stack.
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 3:
return False
stack = []
for ch in s:
stack.append(ch)
# An "abc" on top of the stack is one finished insertion: undo it.
if stack[-3:] == ["a", "b", "c"]:
del stack[-3:]
return not stack