Complete-Preparation

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

View the Project on GitHub

392. Is Subsequence 🌟

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., β€œace” is a subsequence of β€œabcde” while β€œaec” is not).

Code

class Solution {
public:
    bool isSubsequence(string s, string t)
    {
        int n = s.size();
        int m = t.size();
        if (n > m) return false;
        int i = 0, j = 0;
        while (i < n && j < m) {
            if (s[i] == t[j]) {
                i++;
            }
            j++;
        }
        if (i >= n) return true;
        return false;
    }
};

Recursive solution

Code

class Solution {
public:
    bool isSubsequence(string s, string t)
    {
        if (s.size() == 0) return true;
        if (t.size() == 0) return false;
        if (s[0] == t[0]){ // first character matches
            // check for strings starting from next character
            return isSubsequence(s.substr(1), t.substr(1));
        } else {
            // check for strings starting from next character of t
            return isSubsequence(s, t.substr(1));
        }
    }
};

Dynamic Programming

Code

class Solution {
public:
    bool isSubsequence(string s, string t)
    {
        int m = s.size(), n = t.size();
        unordered_map<char, vector<int>> mp;
        for (int i = 0; i < n; i++) {
            mp[t[i]].push_back(i);
        }
        int prev = -1;
        for (int i = 0; i < m; i++) {
            if (mp.find(s[i]) == mp.end()) {
                return false;
            }
            auto it = upper_bound(mp[s[i]].begin(), mp[s[i]].end(), prev);
            if (it == mp[s[i]].end()) {
                return false;
            }
            prev = *it;
        }
        return true;
    }
};