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
Valid String: Can Be Built Using Only "abc" Insertions"aabcbc"Input StringRemove "abc"patternsProcesstrueValid Result"abacbc"Cannotremove allfalseInvalid Example🎯 Key Insight: Valid strings can always be reduced to empty by removing "abc" patterns
Understanding the Visualization
1
Input
String containing only a, b, c characters
2
Process
Remove abc patterns using stack or string replacement
3
Output
True if string reduces to empty, false otherwise
Key Takeaway
🎯 Key Insight: Valid strings can always be reduced to empty by removing "abc" patterns
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