392: Is Subsequence (Using Javascript)

Akinmegha Temitope SamuelAkinmegha Temitope Samuel

Hello everyone, my goal to solve DSA questions by giving optimal solutions with detailed explanations will continue with various platforms including Leetcode,I already have a series on hackerrank you could check that out as well. Now to the Problem we have at hand "Is Subsequence"

Problem: Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:

Input: s = "abc", t = "ahbgdc" Output: true

Example 2:

Input: s = "axc", t = "ahbgdc" Output: false

Constraints:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 104 s and t consist only of lowercase English letters.

Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?

lets do this.gif

Solution: From the problem above, It is understood that there's a sequence that can be in form of an array, and a subsequence will be formed from the sequence. We'll use Pseudocodes to find a clearer analogy of the process

Pseudocode:

  1. Initialize the subsequence(s) to be zero(0).

  2. Use Comparison operators in Conditional statements to compare values (check the array size).

  3. loop through the array index to check if a subsequence is true for all elements.

  4. Compare using a triple equals(===) to see if the s value are of similar types or not.

  5. Return the subsequence equivalent to the length of the s string( Boolean value: True)

JavaScript Code:

var isSubsequence = function(s, t) {
    // initialise the subsequence to be 0
    let subsequence = 0;
    // use comparison operator to check the size of the strings 't' and 's'
    if (s.length > t.length) 
        return false;
    //loop through the array index to check if a subsequence is true for all elements
    for (let i = 0; i < t.length; i++) {
        // compare using a triple equals to see if the value are of similar types or not
        if (s[subsequence] === t[i]){
        subsequence++;
    }
   }
    return subsequence == s.length;
};

quite simple.gif

Definitely, there are other ways in finding Optimal solutions to this problem.Array methods like slice(), Filter() can also be implemented to achieve great solutions. Let me know what you think about the solution to this problem and ways to make it better. Follow me for more DSA concepts and Step by Step Solutions to Problems.

Thank you.