Subsequence of a string

A subsequence of a string is a string that is obtained by deleting 0 or more elements from that string without changing the order of the elements.

For example, for the string “abc”, the subsequences are a, b, c, ab, bc, ac, abc.

There can be multiple questions based on a subsequence of a string like:

  • Find all the subsequences of a string.
  • Given two strings, check whether one is a subsequence of the other string.
  • How many times a given subsequence occurs in a string?
  • Find all subsequences starting with a vowel
  • Find all subsequences ending with a consonant.

and many more.

Let’s dive deeper into some problems!

Finding all the subsequences of a string

Recursion approach

We need to find subsets, so either a character will come or it won’t.

Algorithm:

  • Create a temp array.
  • There are two options either to keep the current character and then move to the next character or to ignore the current character and move to the next character.
  • We start with keeping the current character and then move to the next character. We then check if our base condition is reached i.e we reach the end of the initial string while traversing. If the base case is reached, return the temp array.
  • When traversing back, we pop the last element as now we need to ignore the character and move to the next character.

Subsequences

Time Complexity:

The complexity of our algorithm is O(2^n). For every element, we have two options, to keep or not to keep.
Space Complexity:

Space complexity = O(n), for the temp array.

Given two strings, check whether one is a subsequence of the other string.

Example – 

String1 = “codingninjas”

String2 = “ninja”

Output = true

String1 = “codingninjas”

String2= “code”

Output = false

Approach

We know that only a shorter string can be a subsequence of a larger string and not vice-versa. (Or if both the strings are the same and of equal length then it’s fine). So first we will find the shorter string and then iterate over the strings to check if is a subsequence or not.

Algorithm:

  • Check if both the strings are the same. If it is true, then return true.
  • If the strings are not the same, find the shorter and the longer string.
  • Now initialize the index for the shorter string as i=0
  • Then iterate over the longer string using a variable say j, and if 

longer_string[j] == shorter_string[i], increment i by 1 i.e i++.

  • When the complete iteration over the longer string completes, check whether i equals the length of the shorter string.
  • If i equals the length of the shorter string, then the shorter string is a subsequence of the larger string and hence return true, else return false.

Time Complexity:

The complexity of our algorithm is O(n), iterating over the longer string.

Space Complexity:

Space complexity = O(1)

Comments are closed