Substring Matching Pattern - Problem

You are given a string s and a pattern string p, where p contains exactly one '*' character. The '*' in p can be replaced with any sequence of zero or more characters.

Return true if p can be made a substring of s, and false otherwise.

Note: A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Pattern Match
$ Input: s = "hello", p = "l*e"
Output: true
💡 Note: The pattern 'l*e' can match substring 'lle' by replacing '*' with 'l'. The substring 'lle' exists in 'hello' at positions 2-4.
Example 2 — No Match Possible
$ Input: s = "hello", p = "a*b"
Output: false
💡 Note: There's no way to form a substring of 'hello' using pattern 'a*b' because 'hello' doesn't contain 'a' or 'b'.
Example 3 — Star as Empty String
$ Input: s = "abc", p = "a*c"
Output: true
💡 Note: The pattern 'a*c' matches substring 'ac' by replacing '*' with empty string. 'ac' is a substring of 'abc'.

Constraints

  • 1 ≤ s.length ≤ 1000
  • 1 ≤ p.length ≤ 1000
  • p contains exactly one '*' character
  • s and p consist of lowercase English letters and '*'

Visualization

Tap to expand
Substring Matching Pattern INPUT String s: h e l l o idx: 0 1 2 3 4 Pattern p: l * e Split at '*': prefix="l" suffix="e" s = "hello" p = "l*e" ALGORITHM STEPS 1 Split Pattern Divide at '*' into prefix/suffix 2 Find Prefix "l" Search left-to-right in s h e l l o Found! 3 Find Suffix "e" Search right-to-left in s h e l l o Found! 4 Check Order prefix_end <= suffix_start? idx 2 (l) <= idx 1 (e)? 2<=1 NO But "lle" contains "l*e" FINAL RESULT Substring Match Found: l l e ... Pattern "l*e" matches: "l" + "l" + "e" Where '*' is replaced by "l" Output: true Pattern is a valid substring of s Key Insight: The two-pass approach splits the pattern at '*' and searches for prefix from the left and suffix from the right. If both are found and their positions allow for '*' to match any substring (including empty), then the pattern matches. Time: O(n*m), Space: O(m) where m = pattern length. TutorialsPoint - Substring Matching Pattern | Two-Pass String Matching Approach
Asked in
Google 25 Amazon 20 Microsoft 15
25.5K Views
Medium Frequency
~15 min Avg. Time
850 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