Wednesday, January 29, 2025

Is Subsequence

    Profile Pic of Akash AmanAkash Aman

    Updated: January 2025

    Is Subsequence
    easy

    💡 Intuition

    • We can iterate through the characters of the main string while keeping track of the index in the subsequence.
    • Whenever we find a matching character, we move to the next character in the subsequence.
    • If we successfully traverse the entire subsequence, it confirms that it is present in the main string.

    abgdhcabcabgdhcabcabgdhcabcabgdhcabcabgdhcabcabgdhcabcIteration 6Iteration 5Iteration 4Iteration 3Iteration 2Iteration 1str[i] = str[k] : k=k+1k = 0i = 0k = 1i = 1str[i] != str[k]str[i] = str[k] : k=k+1str[i] != str[k]str[i] != str[k]str[i] = str[k] : k=k+1k = 1i = 2k = 2i = 3i = 4i = 5k = 2k = 3

    🚀 Solution

    go
    function isSubsequence(s: string, t: string): boolean {
        let indx = 0;
    
        for ( let i = 0 ; i < t.length; i++ ) {
            if ( indx < s.length && s[indx] == t[i] ) {
                indx = indx+1;
            }
        }
    
        if (indx == s.length) {
            return true;
        }
    
        return false;
    };

    ⏳ Time Complexity

    • Since we are taking single loop for the array of length n, the time complexity will be O(n)

    © 2026 Akash Aman | All rights reserved