Exploring the JavaScript Function ‘isSubsequence’ for Efficient String Matching

Akhil Kumar
TheCodingWay
Published in
2 min readOct 15, 2023
Photo by Danial Igdery on Unsplash

Understanding the isSubsequence Function

The isSubsequence function is a JavaScript function designed to check if a given string s can be derived from another string t by deleting some (or no) characters, without changing the relative order of the remaining characters in t.

function isSubsequence(s, t) {
let p1 = 0;
let l1 = s.length;
for (let i = 0; i < t.length; i++) {
if (s[p1] === t[i]) {
p1++;
}
if (p1 === l1) {
return true;
}
}
return false;
}

How the Function Works

  1. The function takes two string parameters, s and t.
  2. It initializes two pointers, p1 and l1, to 0 and the length of s, respectively.
  3. The function then iterates over each character in the target string t using a for loop.
  4. Inside the loop, it checks if the character at position p1 in the subsequence s matches the current character in the target t.
  5. If there is a match, it increments the pointer p1.
  6. The function also checks if p1 has reached the length of s. If this condition is met, it means that all characters in s have been found in t in the same order, so it returns true.
  7. If the loop completes without finding all characters of s in t, it returns false.

Example Usage

Let’s see some examples of how the isSubsequence function can be used:

console.log(isSubsequence('abc', 'ahbgdc')); // Output: true
console.log(isSubsequence('axc', 'ahbgdc')); // Output: false

Conclusion

The isSubsequence function provides an efficient way to determine if one string can be formed from another by deleting characters while maintaining their relative order. This is a versatile tool that can be used in various applications, such as text processing, bioinformatics, and more. Understanding and utilizing functions like isSubsequence is essential for every JavaScript developer's toolkit.

Resource: Leetcode 392. Is Subsequence

--

--