Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

792. Number of Matching Subsequences 🌟🌟

Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

Brute Force (TLE)

Optimization (TLE)

Hashmap (AC)

Code

class Solution {
    bool isSubsequence(string& s, string& a)
    {
        int n = s.size(), m = a.size();
        if (m > n)
            return false;

        int i = 0, j = 0;
        while (i < n && j < m) {
            if (s[i] == a[j]) {
                j++;
            }
            i++;
        }
        return j == m;
    }

public:
    int numMatchingSubseq(string s, vector<string>& words)
    {
        int res = 0;
        unordered_map<string, int> wordsMap;
        for (auto x : words) {
            wordsMap[x]++;
        }
        for (auto x : wordsMap) {
            string newString = x.first;
            if (isSubsequence(s, newString)) {
                res += x.second;
            }
        }
        return res;
    }
};