392. Is Subsequence

 

Building an Efficient Subsequence Checker in JavaScript

When working with strings, one common task is to determine if one string is a subsequence of another. A subsequence maintains the relative order of characters but does not require them to be contiguous. In this blog post, we'll walk through an efficient implementation of a subsequence checker in JavaScript.

Problem Statement

Given two strings s and t, the goal is to determine if s is a subsequence of t. A subsequence of a string is formed by deleting some (or no) characters from the string without changing the order of the remaining characters.

Example

  • Input: s = "abc", t = "ahbgdc"

  • Output: true

  • Input: s = "axc", t = "ahbgdc"

  • Output: false

Intuition

To determine if s is a subsequence of t, we need to verify if the characters in s appear in t in the same order. This can be achieved using a simple iteration approach combined with a stack-like behavior.

Approach

  1. Convert s to an Array: Convert the string s into an array of characters. This allows us to use array operations like pop.

  2. Iterate Through t from End to Start: Use a loop to iterate through the string t from the last character to the first.

  3. Check for Matching Characters: For each character in t, if it matches the last character of the s array, remove that character from s using s.pop().

  4. Return Result: After iterating through t, if the s array is empty, it means all characters of s have been found in t in the correct order, and we return true. Otherwise, return false.

Code Implementation

Here's how you can implement the subsequence checker in JavaScript:

javascript
var isSubsequence = function(s, t) {
    s = Array.from(s);
    for(let i = t.length - 1; i >= 0; i--) {
        if(t[i] === s[s.length - 1]) {
            s.pop();
        }
    }
    return s.length ? false : true;
};

Complexity Analysis

  • Time Complexity: O(n), where n is the length of the string t. This is because we iterate through t once.

  • Space Complexity: O(m), where m is the length of the string s. This is because we convert s to an array, which takes up additional space.

Conclusion

This solution provides an efficient way to determine if a string s is a subsequence of another string t. By using a simple iteration and array manipulation, we can ensure that the characters of s appear in the correct order within t. This approach is straightforward and handles the problem effectively.

If you're looking for more detailed explanations and additional solutions, check out the discussion on LeetCode: https://leetcode.com/problems/is-subsequence/solutions/6143778/two-pointer-easy-solution-by-bikash_kuma-f66r/

Happy coding! 😊

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

14. Longest Common Prefix