String Subsequence and Substring in Python
Last Updated :
22 Aug, 2024
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.
Substring of a String
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 :
- Start a while loop from first to last index of the string.
- Take another nested for loop which will run from the index in outer loop to the end of the string.
- At each iteration of the inner loop store the current substring which will start from the index in outer loop and end at the index in inner loop.
- Move to the next iteration.
- Print all the substrings.
Below is the implementation of above algorithm:
Python
# Python program to generate all substrings of a given string
def substrings(s):
all_substrings = []
n = len(s) # Length of the string
# Set the starting index of the substring
for i in range(n):
# Set the ending index of the substring
for j in range(i + 1, n + 1):
# Append the substring s[i:j] to the list
all_substrings.append(s[i:j])
return all_substrings
if __name__ == "__main__":
input_string = "abc"
# Get all substrings
substrings_list = substrings(input_string)
# Print all the substrings
print("All substrings:")
for substring in substrings_list:
print(substring, end = " ")
OutputAll 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 of the String
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 deleting some 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 :
- Initialize a array to store all the Subsequences .
- Make a function , say printSubSequences.
- The base case is if we reach at the index which is greater than of equal to size of string then we will store the current string in the array and return.
- In first call we will include the character at the current index and then move to next index.
- In second call we will move to next index without including character at current index in the string.
- Print all the subsequences formed.
Below is the implementation of above algorithm:
Python
# Python program to print all subsequences of a string
def print_subsequences(s, subseq="", index=0):
# Function to print all subsequences of a string.
if index == len(s):
# Print the current subsequence
print(subseq, end=" ")
return
# Include the character at the current index
# in the subsequence
print_subsequences(s, subseq + s[index], index + 1)
# Exclude the character at the current index
# from the subsequence
print_subsequences(s, subseq, index + 1)
if __name__ == "__main__":
print("All Subsequences:")
input_string = "abc"
print_subsequences(input_string)
OutputAll 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:
Similar Reads
String, Subsequence & Substring What is a Substring? A substring is a contiguous part of a string, i.e., a string inside another string. In general, for an string of size n, there are n*(n+1)/2 non-empty substrings. For example, Consider the string "geeks", There are 15 non-empty substrings. The subarrays are: g, ge, gee, geek, ge
6 min read
Print all subsequences of a string in Python Given a string s of size n (1 ⤠n ⤠20), the task is to print all subsequences of string. 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.Examples: Input: s = "abc"Output: ["", "a", "b", "c", "
3 min read
How to Substring a String in Python A String is a collection of characters arranged in a particular order. A portion of a string is known as a substring. For instance, suppose we have the string "GeeksForGeeks". In that case, some of its substrings are "Geeks", "For", "eeks", and so on. This article will discuss how to substring a str
4 min read
Check if String Contains Substring in Python This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
8 min read
Python - Check if substring present in string The task is to check if a specific substring is present within a larger string. Python offers several methods to perform this check, from simple string methods to more advanced techniques. In this article, we'll explore these different methods to efficiently perform this check.Using in operatorThis
2 min read
String Slicing in Python String slicing in Python is a way to get specific parts of a string by using start, end and step values. Itâs especially useful for text manipulation and data parsing.Letâs take a quick example of string slicing:Pythons = "Hello, Python!" print(s[0:5])OutputHello Explanation: In this example, we use
4 min read
SequenceMatcher in Python for Longest Common Substring Given two strings âXâ and âYâ, print the longest common sub-string. Examples: Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : Geeks Input : X = "zxabcdezy", Y = "yzabcdezx" Output : abcdez We have existing solution for this problem please refer Print the longest common substring link. We will
2 min read
Subsequence meaning in DSA A subsequence is defined as a sequence that can be derived from another string/sequence by deleting some or none of the elements without changing the order of the remaining elements. For example: Let's take "GeeksForGeeks", GeeksF will be a subsequence of "GeeksForGeeks". Example of SubsequencePrope
2 min read
How to Index and Slice Strings in Python? In Python, indexing and slicing are techniques used to access specific characters or parts of a string. Indexing means referring to an element of an iterable by its position whereas slicing is a feature that enables accessing parts of the sequence.Table of ContentIndexing Strings in PythonAccessing
2 min read
Print all subsequences of a string | Iterative Method Given a string s, print all possible subsequences of the given string in an iterative manner. We have already discussed Recursive method to print all subsequences of a string. Examples: Input : abc Output : a, b, c, ab, ac, bc, abc Input : aab Output : a, b, aa, ab, aab Approach 1 : Here, we discuss
15 min read