VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-string-is-a-subsequence-of-another-string-using-stacks/

⇱ Check if a string is a subsequence of another string ( using Stacks ) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a string is a subsequence of another string ( using Stacks )

Last Updated : 23 Jul, 2025

Given a stringS, the task is to check if the string target is a subsequence of string S or not, using a Stack.

Examples:

Input: S = ”KOTTAYAM”, target = ”KOTA”
Output: Yes
Explanation: “KOTA” is a subsequence of “KOTTAYAM”.

Input: S = ”GEEKSFORGEEKS”, target =”FORFOR”
Output: No

Approach: Follow the steps to solve the problem:

👁 Image
target pushed into the stack
👁 Image
Traversing in S
👁 Image
Traversing in S
👁 Image
Popping from stack
👁 Image
Traversing in S
👁 Image
Popping from stack
👁 Image
Traversing in st
👁 Image
Popping from stack
👁 Image
Traversing in S
👁 Image
Stack becomes empty

Below is the implementation of the above approach:


Output
Yes

Time Complexity : O(N) 
Auxiliary Space : O(N)

Approach 2: Using the find() function

Another approach to check if a string is a subsequence of another string is to use the find() function. We can call find() on the second string to find the index of the first occurrence of the first character of the first string. Then, we can iterate over the first string and call find() on the second string with the starting index set to the index of the previous character plus one. If find() returns string::npos, it means that the current character in the first string is not present in the second string and hence the first string is not a subsequence of the second string.

    Define a function that takes two string arguments s1 and s2.

   Initialize an integer variable index to -1. This will be used to keep track of the starting index for each find() call.

   Iterate over each character c in s1 using a range-based for loop.

   Call the find() function on s2 with the arguments c and index + 1. The second argument specifies the starting index for the search, which is the index of the previous character plus one.

   If find() returns string::npos, which indicates that the character was not found in s2, return false immediately, as s1 is not a subsequence of s2.

   If find() returns a valid index, update index to the returned value.

   After iterating over all the characters in s1, return true, as s1 is a subsequence of s2.


Output
 yes

Time Complexity : O(M*N) 
Auxiliary Space : O(1)


Comment