Check If Word Is Valid After Substitutions - Problem

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 in t. More formally, t becomes t_left + "abc" + t_right, where t == t_left + t_right. Note that t_left and t_right may be empty.

Return true if s is a valid string, otherwise, return false.

Input & Output

Example 1 — Valid String
$ Input: s = "aabcbc"
Output: true
💡 Note: Start with empty string, insert "abc" to get "abc", then insert "abc" at beginning to get "abcabc", but wait - we can think of it as: "aabcbc" → remove "abc" from middle → "abc" → remove "abc" → empty string.
Example 2 — Invalid String
$ Input: s = "abacbc"
Output: false
💡 Note: Cannot form this by inserting only "abc" patterns. The 'a' in the middle breaks the pattern.
Example 3 — Simple Valid
$ Input: s = "abcabcabc"
Output: true
💡 Note: Three "abc" patterns in sequence can be built by inserting "abc" three times.

Constraints

  • 1 ≤ s.length ≤ 2 × 104
  • s consists only of letters 'a', 'b', and 'c'

Visualization

Tap to expand
Check If Word Is Valid After Substitutions INPUT String s = "aabcbc" a a b c b c 0 1 2 3 4 5 Stack-based Approach Empty Stack [] Push 'a', 'b' Pop on 'c' if pattern matches "abc" ALGORITHM STEPS 1 Initialize Stack Create empty stack [] 2 Process Each Char If 'a' or 'b': push to stack 3 On 'c': Check Pattern Pop 'b' then 'a' from stack 4 Final Check Stack must be empty Trace: Char Stack Action 'a' [a] push 'a' [a,a] push 'b' [a,a,b] push 'c' [a] pop b,a (abc found) 'b' [a,b] push 'c' [] pop b,a (abc found) FINAL RESULT Stack is empty after processing [ ] Empty Stack Output: true String is VALID Decomposition: "aabcbc" = a + abc + bc = a + abc + bc = abc nested in abc Key Insight: Use a stack to simulate removing "abc" substrings. When we see 'c', check if the top two elements are 'b' and 'a' (in that order). If yes, pop them both. If stack is empty at the end, the string is valid. Time: O(n), Space: O(n). This works because valid strings are built by nesting "abc". TutorialsPoint - Check If Word Is Valid After Substitutions | Optimal Solution (Stack)
Asked in
Google 15 Facebook 12
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen