Given two strings, check if the second string is a subsequence of the first string.

A subsequence is a sequence that can be obtained by deleting some characters from a string without changing the relative order of the other characters. For example,

Input: first = abcde, second = abd
Output: true
Explanation: abd is a subsequence of abcde
 
Input: first = abcde, second = acb
Output: false
Explanation: acb is not a subsequence of abcde

 
The idea is very simple: simultaneously traverse both strings and compare the current character of the first string with the next character of the second string, both starting from the beginning. We increment the pointer of the first string at each iteration of the loop and increment the second string’s pointer only if a match is found. We return true if the end of the second string is reached at any time and false otherwise.

Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

Subsequence found

Java


Download  Run Code

Output:

Subsequence found

Python


Download  Run Code

Output:

Subsequence found

The time complexity of the above solution is O(n) where n is the length of the string.