Check if Given String Subsequence of Another String in Java

Write a Java program to check if given String is subsequence of another string is asked quite often in Java interviews.

If you have two strings str1 and str2 then str1 is a subsequence of str2 if all the characters in str1 are found in str2, characters may not be found consecutively but characters should be in order.
For example – If str1 = “code” and str2=”cportde” then str1 is a subsequence of str2 as you can get all the characters of str1 in str2 in the same order by deleting some of the characters in str2.

If str1=”abc” and str2=”bsdafgc” then str1 is not the subsequence of str2, as all the characters of str1 are present in str2 but order is different.

Java program to check if string subsequence of another string

To check if string str1 is a subsequence of str2, start from the first character of str1 and iterate the string str2 to check if that character is found.
If yes then move to next character for str1 and check that in str2.
If no then check for the same character of str1 in str2.

There are both recursive and iterative Java programs for checking if the String is subsequence of another string. In this post we’ll see both of the ways.

Iterative Java program to check if String is subsequence of another string

Output

Recursive Java program to check if String is subsequence of another string

Output

That’s all for the topic Check if Given String Subsequence of Another String in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.