#1003

Check If Word Is Valid After Substitutions

Medium
StringStackStackGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a stack to keep track of the characters and ensures that every 'abc' sequence is properly formed. This is efficient and directly checks for the validity of the string.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty stack.
  2. 2Step 2: Traverse each character in the string s.
  3. 3Step 3: Push each character onto the stack. If the top three characters of the stack are 'abc', pop them off.
  4. 4Step 4: After processing all characters, check if the stack is empty; if it is, return true; otherwise, return false.
solution.py9 lines
1def is_valid(s):
2    stack = []
3    for char in s:
4        stack.append(char)
5        if len(stack) >= 3 and stack[-3:] == ['a', 'b', 'c']:
6            stack.pop()
7            stack.pop()
8            stack.pop()
9    return len(stack) == 0

Complexity note: The time complexity is O(n) because we traverse the string once, and the stack operations (push/pop) are O(1). The space complexity is O(n) in the worst case when no 'abc' sequences are formed.

  • 1The string must be able to form complete 'abc' sequences.
  • 2Using a stack helps efficiently manage the formation and removal of 'abc' sequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.