#3407

Substring Matching Pattern

Easy
StringString MatchingString MatchingTwo Pointers
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass to check if the left and right parts of the pattern can be found in the string while allowing for any characters in between. This is more efficient than checking every substring.

⚙️

Algorithm

4 steps
  1. 1Step 1: Split the pattern 'p' into left and right parts around '*'.
  2. 2Step 2: Check if the left part exists at the start of 's'.
  3. 3Step 3: Check if the right part exists at the end of 's'.
  4. 4Step 4: If both parts match, return true; otherwise, return false.
solution.py3 lines
1def isMatch(s, p):
2    left, right = p.split('*')
3    return s.startswith(left) and s.endswith(right) and len(s) >= len(left) + len(right)

Complexity note: The time complexity is O(n) because we only check the start and end of the string once, making it linear in relation to the length of 's'.

  • 1The '*' can represent any sequence, so focus on the fixed parts of the pattern.
  • 2The order of characters matters; ensure both left and right parts are checked.

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