📖
Coding problems
  • Overview
  • Second time
  • Third time
  • 2 sum
    • 2 sum?
    • 2 Sum All Pair I
    • 2 Sum All Pair II
    • 3 Sum
  • Array
    • Smallest and Largest
    • Largest and second largest
    • Longest Palindromic Substring
  • BFS
    • Array Hopper IV
    • Deep copy graph(possible loops)
    • Kth Smallest With Only 3, 5, 7 As Factors
    • Word Ladder
  • Binary Search
    • Closest in Sorted Array
    • Smallest Element that is larger than target
    • Search in unknown size array
  • Bit Operations
    • Basic Operations
    • Power of two?
    • Different bits
    • Reverse all bits of a number
    • Unique String
  • Deque
    • Deque with 3 stacks
    • Largest Rectangle in histogram
  • DFS Permutations
    • All subsets I
    • All subsets size k
    • Combinations For Telephone Pad I
    • Subsets of all permuations
    • Generate N valid parentheses I
    • Generate N valid parentheses II
    • Generate N valid parentheses III
    • Combinations of Coin
    • All Permutation String
    • All Permutations II
    • Telephone Combinations
  • Dynamic Programming
    • Array Hopper I
    • Array Hopper II
    • Array Hopper III
    • Cut Rope
    • Dictionary Word 1
    • Dictionary Word II
    • Eat Pizza
    • Largest Cross of Ones
    • Largest Square Surrounded By One
    • Largest X of 1s
    • Largest Square of Matches
    • Largest Submatrix Sum
    • Longest Ascending Subsequence I & II
    • Longest Common Sequence between two strings
    • Most with positive slope
    • Palindrome Partition
    • Edit Distance
    • Square of ones
    • Wild card matching
    • Wood Cutting
    • 188. Best Time to Buy and Sell Stock IV
  • Graph Search
    • Kth closest to <0, 0, 0>
    • Largest Product of Length
  • HashTable
    • Top K frequent words
    • Bipartite
  • Heap
  • LinkedList
    • Reverse
    • Merge Sort Linked List
    • Re-Order LinkedList
  • Slow fast pointers
    • Remove duplicate elements in array
  • Problem Solving
    • Water Level I
    • Largest rectangle in histogram
    • Range Addition II
  • Recursion
    • ReverseTree
    • NQueen
    • NQueen optimized
    • Spiral Order Print I
    • Spiral Order Print II
    • String Abbreviation Matching
  • Sliding Window
    • Longest subarray contains only 1s
    • Longest Substring Without Repeating Characters
    • Maximum Number within Window
  • Sorts
    • QuickSort
  • String
    • All Anagrams
    • is substring of string
    • Reverse String
    • Reverse Words on sentence
    • Remove Chars from String in place
    • Right shift N characters
    • Remove Leading/duplicate/trailing spaces
    • Shuffle String
    • String Abbreviation Matching
  • Tree Traversal
    • Check balanced tree
    • Check if complete tree
    • Delete in binary tree
    • LCA of two tree nodes
    • Get Keys In Binary Search Tree In Given Range
    • Height of Tree
    • Symmetric Tree?
    • Tweaked Binary tree
    • Set left node count
    • Greatest difference Left and Right subtree count Node
    • Largest Number Smaller in BST
    • Closest Number in Binary Search Tree II
    • Max Path Sum From Leaf To Root
    • Maximum Path Sum Binary Tree I
    • Maximum Path Sum Binary Tree II
    • Maximum Path Sum Binary Tree III
    • Flatten Binary Tree to Linked List
    • Iterative Post-Order Traversal
  • Unsorted Array
    • Find missing number
Powered by GitBook
On this page

Was this helpful?

  1. Dynamic Programming

Wild card matching

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

  • '?' Matches any single character.

  • '*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

Example 1:

Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.

Example 3:

Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input: s = "adceb", p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Explanation

State Transition

  • Case 1: If the current pattern character matches the current input character or is a '?", mark the current cell as true.

  • Case 2: If the current pattern character is a '*', mark the current cell as true if

    • [null match] the current input character can be matched by the previous pattern character

      • M[i][j] = M[i][j-1]

    • OR

    • [1+ match] the current character can be matched by the '*' if last input char is_match

      • can be thought of as "skipping" over the current input character

      • M[i][j] = M[i-1][j]

  • Case 3: No match

State Definition

  • i (int)

    • the index up to which the input is matched

  • j (int)

    • the index up to which the pattern is matched

  • is_match (bool):

    • True if for the given i, j the pattern+input substrings are a match

State Initialization (base case)

  • i=0, j=0 is true

    • empty pattern matches the empty string

  • i>0, j=0 is false

    • empty pattern cannot match non-empty string

  • i=0, j>0 is true if the current pattern character is '*' and the previous is also a match

    • can be thought of as a 'leading asterisk' case

    • any leading characters which can match an empty string are true. Otherwise false

func Match(pattern string, input string) bool {
  // init memo matrix
  M := make([][]bool, len(input)+1)

  for i := 0; i <= len(input); i++ {
    M[i] = make([]bool, len(pattern)+1)
  }

  // base case
  // empty pattern matches empty string
  M[0][0] = true
  
  for i := 1; i <= len(input); i++ {
    // cannot match empty pattern against non-empty string
    M[i][0] = false
  }

  for j := 1; j <= len(pattern); j++ {
    // asterisks match empty string
    // iff they are leading
    if pattern[j-1] == '*' {
      M[0][j] = M[0][j-1]
    } else {
      M[0][j] = false // redundant
    }
  }

  //case 1: p[j - 1] == a[i - 1] || p[j - 1] == '?' . Inherit from diagonal
  //case 2: p[j - 1] == '*' 
  //case 2a: Match nothing, M[i][j] = M[i][j - 1]. Matching nothing against prev input char
  //case 2b: Match one or more, M[i][j] = M[i - 1][j]. Matching wildcard to cur input char
  //case 3: p[j - 1] != a[i - 1] False. Can not match no matter what

  for i := 1; i <= len(input); i++ {
    for j := 1; j <= len(pattern); j++ {
      if pattern[j - 1] == input[i - 1] || pattern[j - 1] == '?' {
        M[i][j] = M[i - 1][j - 1]
      } else if pattern[j - 1] == '*' {
        M[i][j] = M[i][j - 1] || M[i - 1][j]
      } else {
        M[i][j] = false
      }
    }  
  }
  return M[len(input)][len(pattern)]
}

TC: O(N^2)

SC: O(N^2) can be lowered to O(2N) as only two rows are relevant

PreviousSquare of onesNextWood Cutting

Last updated 3 years ago

Was this helpful?