![]() |
VOOZH | about |
Subsequence and Substring both are parts of the given String with some differences between them. Both of them are made using the characters in the given String only. The difference between them is that the Substring is the contiguous part of the string and the Subsequence is the non-contiguous part of the string . Although Subsequence is a non-contiguous part but it preserves the order of characters as in the original string. In this article, we will learn about the Substring and Subsequence of the given String in detail.
A substring of the given string is the contiguous part of the original String. A substring can start at any index of the String and can end at any index. The only condition for the part of the String to be a Substring is that it should be the contiguous part of the String. Note - A string itself is also the Substring of the given String.
Example:
Input: "abc"
Output: "a", "b", "c", "ab", "bc", "abc" .
Explanation: The strings given in the output are the contiguous parts of the given String.Input: "ac"
Output: "a", "c", "ac" .
Explanation: The strings given in the output are the contiguous parts of the given String.
Algorithm :
Below is the implementation of above algorithm:
All substrings: a ab abc b bc c
Time complexity : O(n^2) , where n is the size of string
Auxiliary space : O(n^2).
Subsequence is the non-contiguous part of the given string. Although it is non-contiguous but the order of the characters should say same as the original String. Basically Subsequence of the String can be generated by deletingsome number of characters form the given String. While deleting characters we should keep in mind that we can also delete zero characters which means that the String itself is the subsequence of the given string. Also we can delete all the characters which indicated that an empty String is also Subsequence of the given String.
Example:
Input: "abc"
Output: "" , "a" , "b" , "c" , "ab" , "ac" , "bc" , "abc".
Explanation: The strings given in the output are the non- contiguous parts of the given String.Input: "ac"
Output: "" , "a" , "c" , "ac" .
Explanation: The strings given in the output are the non- contiguous parts of the given String.
Algorithm:
As we have discussed that we can get the Subsequences by deleting any number of characters which also mean that we can take and leave any character. For every character we have two options , either we can take the character or leave it. We will use this approach to get all the Subsequences of the given String.
Step-By-Step explanation of above approach :
Below is the implementation of above algorithm:
All Subsequences: abc ab ac a bc b c
Time complexity: O(2^n) because we have two options, include or exclude
Auxiliary space: O(n)
Related articles: