Check If a String is Subsequence of Another String

In this tutorial, I am going to discuss a problem Is Subsequence (check if a string is subsequence of another string).

Given two strings str1 and str2, check if str1 is a subsequence of str2. Both strings consists only of lowercase characters.

Example 1:

Input: str1 = “abc”, str2 = “ahbgdc”

Output: true

Example 2:

Input: s = “axc”, t = “ahbgdc”

Output: false

What is Subsequence?

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

For example : abd is a subsequence of abcde.

In this tutorial, I am going to discuss iterative and recursive approach to solve this problem.

Data Structure Video Tutorials

Programming Questions on Arrays

Programming Questions on Linked List

Programming Questions on Binary Tree

Check If a String is Subsequence of Another String (Is Subsequence) – Two Pointers

In this example, we are going to solve this problem using two pointers.

Take two pointers sIndex and tIndex. The pointer sIndex points to String str1 and pointer tIndex points to string str2. The initial value is zero for both the pointers.

Then compare the character present at both the indexes. If it is equal then increment the value of both the pointers. Else increment the value of pointer which points to String str2.

If all the characters of string str1 is present in string str2 it means the value of sIndex is equal to s.length.

The time complexity of this approach is O(n), where n is the length of string s. It’s space complexity is O(1).

Check whether two strings are anagrams of each other

Check If a String is Subsequence of Another String using Recursion – Java Code

We have written an iterative code to solve this problem. Let’s write it’s recursive version.

The time complexity and space complexity of this approach is O(n), where n is the length of string s.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.