Glob Pattern File Matcher - Problem

Implement a file system glob pattern matcher that supports advanced wildcards:

  • * - matches any number of characters within a single path segment (does not cross directory separators)
  • ** - matches across multiple directory levels (can cross directory separators)
  • ? - matches exactly one character

Given a glob pattern and a file path, return true if the pattern matches the path, false otherwise.

Note: Directory separators are represented by forward slashes (/)

Input & Output

Example 1 — Single Segment Wildcard
$ Input: pattern = "*.txt", filepath = "file.txt"
Output: true
💡 Note: The '*' matches 'file', then '.txt' matches exactly. Pattern successfully matches the filepath.
Example 2 — Multi-Level Wildcard
$ Input: pattern = "**/test.py", filepath = "src/utils/test.py"
Output: true
💡 Note: The '**' matches 'src/utils' (crossing directory separator), then '/test.py' matches exactly.
Example 3 — Question Mark Wildcard
$ Input: pattern = "file?.txt", filepath = "file1.txt"
Output: true
💡 Note: The '?' matches exactly one character '1', and the rest matches exactly.

Constraints

  • 1 ≤ pattern.length ≤ 2000
  • 1 ≤ filepath.length ≤ 2000
  • Pattern contains only lowercase letters, digits, '.', '/', '*', '?'
  • Filepath contains only lowercase letters, digits, '.', '/'

Visualization

Tap to expand
INPUTPattern*.txtFilepathfile.txtWildcards:* = any chars (one segment)** = any chars (cross dirs)? = exactly one charALGORITHM1Create 2D DP Tabledp[i][j] = pattern[0:i] matches path[0:j]2Initialize Base Casesdp[0][0] = true (empty matches empty)3Fill DP TableHandle *, **, ?, and regular chars4Return Final Resultdp[pattern_len][filepath_len]Time: O(n×m)Space: O(n×m)n = pattern lengthm = filepath lengthRESULTMatch Found!truePattern: *.txtFilepath: file.txt✓ '*' matches 'file'✓ '.txt' matches '.txt'Key Insight:Dynamic programming eliminates redundant subproblem computation by memoizingpattern-filepath position pairs, achieving optimal O(n×m) complexity for glob matching.TutorialsPoint - Glob Pattern File Matcher | Bottom-Up DP
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
23.4K Views
Medium Frequency
~35 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