Sobes.tech
Middle

More formally known as approximate string matching. It is required to check whether the first string is a subsequence of the second. A subsequence is when the first string can be obtained from the second by deleting some characters. Input: 'car', 'cartwheel' Output: true Input: 'cwhl', 'cartwheel' Output: true Input: 'cwhee', 'cartwheel' Output: true Input: 'cartwheel', 'cartwheel' Output: true Input: 'cwheeel', 'cartwheel' Output: false Input: 'lw', 'cartwheel' Output: false

sobes.tech AI

Answer from AI

The task is to check whether the first string is a subsequence of the second. This means that all characters of the first string appear in the second in the same order, but not necessarily consecutively.

Example solution in Go:

 type void struct{}

 func isSubsequence(s, t string) bool {
     i, j := 0, 0
     for i < len(s) && j < len(t) {
         if s[i] == t[j] {
             i++
         }
         j++
     }
     return i == len(s)
 }

// Usage example:
// fmt.Println(isSubsequence("car", "cartwheel")) // true
// fmt.Println(isSubsequence("cwheeel", "cartwheel")) // false

Idea: iterate through both strings with two pointers. If the characters match — move the pointer of the first string. In the end, if the entire first string is traversed, it means it is a subsequence of the second.